blob: 70fb808c8e5bfc37a96320718fa057b4532849cd [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
248}
249
Dima Zavin799a70e2011-04-18 16:57:27 -0700250audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
251{
252 /* first matching HW device is returned */
253 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
254 audio_hw_device_t *dev = mAudioHwDevs[i];
255 if ((dev->get_supported_devices(dev) & devices) == devices)
256 return dev;
257 }
258 return NULL;
259}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260
261status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
262{
263 const size_t SIZE = 256;
264 char buffer[SIZE];
265 String8 result;
266
267 result.append("Clients:\n");
268 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800269 sp<Client> client = mClients.valueAt(i).promote();
270 if (client != 0) {
271 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
272 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700275
276 result.append("Global session refs:\n");
277 result.append(" session pid cnt\n");
278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
279 AudioSessionRef *r = mAudioSessionRefs[i];
280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
281 result.append(buffer);
282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 write(fd, result.string(), result.size());
284 return NO_ERROR;
285}
286
287
288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800293 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294
295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
296 result.append(buffer);
297 write(fd, result.string(), result.size());
298 return NO_ERROR;
299}
300
301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306 snprintf(buffer, SIZE, "Permission Denial: "
307 "can't dump AudioFlinger from pid=%d, uid=%d\n",
308 IPCThreadState::self()->getCallingPid(),
309 IPCThreadState::self()->getCallingUid());
310 result.append(buffer);
311 write(fd, result.string(), result.size());
312 return NO_ERROR;
313}
314
315static bool tryLock(Mutex& mutex)
316{
317 bool locked = false;
318 for (int i = 0; i < kDumpLockRetries; ++i) {
319 if (mutex.tryLock() == NO_ERROR) {
320 locked = true;
321 break;
322 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800323 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 }
325 return locked;
326}
327
328status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
329{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800330 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331 dumpPermissionDenial(fd, args);
332 } else {
333 // get state of hardware lock
334 bool hardwareLocked = tryLock(mHardwareLock);
335 if (!hardwareLocked) {
336 String8 result(kHardwareLockedString);
337 write(fd, result.string(), result.size());
338 } else {
339 mHardwareLock.unlock();
340 }
341
342 bool locked = tryLock(mLock);
343
344 // failed to lock - AudioFlinger is probably deadlocked
345 if (!locked) {
346 String8 result(kDeadlockedString);
347 write(fd, result.string(), result.size());
348 }
349
350 dumpClients(fd, args);
351 dumpInternals(fd, args);
352
353 // dump playback threads
354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
355 mPlaybackThreads.valueAt(i)->dump(fd, args);
356 }
357
358 // dump record threads
359 for (size_t i = 0; i < mRecordThreads.size(); i++) {
360 mRecordThreads.valueAt(i)->dump(fd, args);
361 }
362
Dima Zavin799a70e2011-04-18 16:57:27 -0700363 // dump all hardware devs
364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
365 audio_hw_device_t *dev = mAudioHwDevs[i];
366 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 if (locked) mLock.unlock();
369 }
370 return NO_ERROR;
371}
372
373
374// IAudioFlinger interface
375
376
377sp<IAudioTrack> AudioFlinger::createTrack(
378 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800379 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800381 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700382 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 int frameCount,
384 uint32_t flags,
385 const sp<IMemory>& sharedBuffer,
386 int output,
387 int *sessionId,
388 status_t *status)
389{
390 sp<PlaybackThread::Track> track;
391 sp<TrackHandle> trackHandle;
392 sp<Client> client;
393 wp<Client> wclient;
394 status_t lStatus;
395 int lSessionId;
396
Glenn Kasten263709e2012-01-06 08:40:01 -0800397 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
398 // but if someone uses binder directly they could bypass that and cause us to crash
399 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000400 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 lStatus = BAD_VALUE;
402 goto Exit;
403 }
404
405 {
406 Mutex::Autolock _l(mLock);
407 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700408 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000410 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414
415 wclient = mClients.valueFor(pid);
416
417 if (wclient != NULL) {
418 client = wclient.promote();
419 } else {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
Steve Block3856b092011-10-20 11:56:00 +0100424 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700425 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700426 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700427 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
428 if (mPlaybackThreads.keyAt(i) != output) {
429 // prevent same audio session on different output threads
430 uint32_t sessions = t->hasAudioSession(*sessionId);
431 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000432 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700433 lStatus = BAD_VALUE;
434 goto Exit;
435 }
436 // check if an effect with same session ID is waiting for a track to be created
437 if (sessions & PlaybackThread::EFFECT_SESSION) {
438 effectThread = t.get();
439 }
Eric Laurentde070132010-07-13 04:45:46 -0700440 }
441 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 lSessionId = *sessionId;
443 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700444 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700445 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 if (sessionId != NULL) {
447 *sessionId = lSessionId;
448 }
449 }
Steve Block3856b092011-10-20 11:56:00 +0100450 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451
452 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700453 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700454
455 // move effect chain to this output thread if an effect on same session was waiting
456 // for a track to be created
457 if (lStatus == NO_ERROR && effectThread != NULL) {
458 Mutex::Autolock _dl(thread->mLock);
459 Mutex::Autolock _sl(effectThread->mLock);
460 moveEffectChain_l(lSessionId, effectThread, thread, true);
461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700462 }
463 if (lStatus == NO_ERROR) {
464 trackHandle = new TrackHandle(track);
465 } else {
466 // remove local strong reference to Client before deleting the Track so that the Client
467 // destructor is called by the TrackBase destructor with mLock held
468 client.clear();
469 track.clear();
470 }
471
472Exit:
473 if(status) {
474 *status = lStatus;
475 }
476 return trackHandle;
477}
478
479uint32_t AudioFlinger::sampleRate(int output) const
480{
481 Mutex::Autolock _l(mLock);
482 PlaybackThread *thread = checkPlaybackThread_l(output);
483 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000484 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700485 return 0;
486 }
487 return thread->sampleRate();
488}
489
490int AudioFlinger::channelCount(int output) const
491{
492 Mutex::Autolock _l(mLock);
493 PlaybackThread *thread = checkPlaybackThread_l(output);
494 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000495 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 return 0;
497 }
498 return thread->channelCount();
499}
500
Glenn Kasten58f30212012-01-12 12:27:51 -0800501audio_format_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700502{
503 Mutex::Autolock _l(mLock);
504 PlaybackThread *thread = checkPlaybackThread_l(output);
505 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000506 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800507 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700508 }
509 return thread->format();
510}
511
512size_t AudioFlinger::frameCount(int output) const
513{
514 Mutex::Autolock _l(mLock);
515 PlaybackThread *thread = checkPlaybackThread_l(output);
516 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000517 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700518 return 0;
519 }
520 return thread->frameCount();
521}
522
523uint32_t AudioFlinger::latency(int output) const
524{
525 Mutex::Autolock _l(mLock);
526 PlaybackThread *thread = checkPlaybackThread_l(output);
527 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000528 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 return 0;
530 }
531 return thread->latency();
532}
533
534status_t AudioFlinger::setMasterVolume(float value)
535{
Eric Laurenta1884f92011-08-23 08:25:03 -0700536 status_t ret = initCheck();
537 if (ret != NO_ERROR) {
538 return ret;
539 }
540
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 // check calling permissions
542 if (!settingsAllowed()) {
543 return PERMISSION_DENIED;
544 }
545
546 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800547 { // scope for the lock
548 AutoMutex lock(mHardwareLock);
549 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700550 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800551 value = 1.0f;
552 }
553 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555
Eric Laurent93575202011-01-18 18:39:02 -0800556 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 mMasterVolume = value;
558 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
559 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
560
561 return NO_ERROR;
562}
563
Glenn Kastenf78aee72012-01-04 11:00:47 -0800564status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565{
Eric Laurenta1884f92011-08-23 08:25:03 -0700566 status_t ret = initCheck();
567 if (ret != NO_ERROR) {
568 return ret;
569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700570
571 // check calling permissions
572 if (!settingsAllowed()) {
573 return PERMISSION_DENIED;
574 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800575 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000576 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 return BAD_VALUE;
578 }
579
580 { // scope for the lock
581 AutoMutex lock(mHardwareLock);
582 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700583 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 mHardwareStatus = AUDIO_HW_IDLE;
585 }
586
587 if (NO_ERROR == ret) {
588 Mutex::Autolock _l(mLock);
589 mMode = mode;
590 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
591 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700592 }
593
594 return ret;
595}
596
597status_t AudioFlinger::setMicMute(bool state)
598{
Eric Laurenta1884f92011-08-23 08:25:03 -0700599 status_t ret = initCheck();
600 if (ret != NO_ERROR) {
601 return ret;
602 }
603
Mathias Agopian65ab4712010-07-14 17:59:35 -0700604 // check calling permissions
605 if (!settingsAllowed()) {
606 return PERMISSION_DENIED;
607 }
608
609 AutoMutex lock(mHardwareLock);
610 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700611 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 mHardwareStatus = AUDIO_HW_IDLE;
613 return ret;
614}
615
616bool AudioFlinger::getMicMute() const
617{
Eric Laurenta1884f92011-08-23 08:25:03 -0700618 status_t ret = initCheck();
619 if (ret != NO_ERROR) {
620 return false;
621 }
622
Dima Zavinfce7a472011-04-19 22:30:36 -0700623 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700625 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 mHardwareStatus = AUDIO_HW_IDLE;
627 return state;
628}
629
630status_t AudioFlinger::setMasterMute(bool muted)
631{
632 // check calling permissions
633 if (!settingsAllowed()) {
634 return PERMISSION_DENIED;
635 }
636
Eric Laurent93575202011-01-18 18:39:02 -0800637 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700638 mMasterMute = muted;
639 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
640 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
641
642 return NO_ERROR;
643}
644
645float AudioFlinger::masterVolume() const
646{
Glenn Kasten98067102011-12-13 11:47:54 -0800647 Mutex::Autolock _l(mLock);
648 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700649}
650
651bool AudioFlinger::masterMute() const
652{
Glenn Kasten98067102011-12-13 11:47:54 -0800653 Mutex::Autolock _l(mLock);
654 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655}
656
Glenn Kastenfff6d712012-01-12 16:38:12 -0800657status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Glenn Kasten263709e2012-01-06 08:40:01 -0800664 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000665 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 return BAD_VALUE;
667 }
668
669 AutoMutex lock(mLock);
670 PlaybackThread *thread = NULL;
671 if (output) {
672 thread = checkPlaybackThread_l(output);
673 if (thread == NULL) {
674 return BAD_VALUE;
675 }
676 }
677
678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
683 }
684 } else {
685 thread->setStreamVolume(stream, value);
686 }
687
688 return NO_ERROR;
689}
690
Glenn Kastenfff6d712012-01-12 16:38:12 -0800691status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Glenn Kasten263709e2012-01-06 08:40:01 -0800698 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000700 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 return BAD_VALUE;
702 }
703
Eric Laurent93575202011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
708
709 return NO_ERROR;
710}
711
Glenn Kastenfff6d712012-01-12 16:38:12 -0800712float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700713{
Glenn Kasten263709e2012-01-06 08:40:01 -0800714 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715 return 0.0f;
716 }
717
718 AutoMutex lock(mLock);
719 float volume;
720 if (output) {
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
723 return 0.0f;
724 }
725 volume = thread->streamVolume(stream);
726 } else {
727 volume = mStreamTypes[stream].volume;
728 }
729
730 return volume;
731}
732
Glenn Kastenfff6d712012-01-12 16:38:12 -0800733bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734{
Glenn Kasten263709e2012-01-06 08:40:01 -0800735 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 return true;
737 }
738
739 return mStreamTypes[stream].mute;
740}
741
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
743{
744 status_t result;
745
Steve Block3856b092011-10-20 11:56:00 +0100746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
751 }
752
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753 // ioHandle == 0 means the parameters are global to the audio hardware interface
754 if (ioHandle == 0) {
755 AutoMutex lock(mHardwareLock);
756 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700757 status_t final_result = NO_ERROR;
758 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759 audio_hw_device_t *dev = mAudioHwDevs[i];
760 result = dev->set_parameters(dev, keyValuePairs.string());
761 final_result = result ?: final_result;
762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700764 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765 AudioParameter param = AudioParameter(keyValuePairs);
766 String8 value;
767 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700771 for (size_t i = 0; i < mRecordThreads.size(); i++) {
772 sp<RecordThread> thread = mRecordThreads.valueAt(i);
773 RecordThread::RecordTrack *track = thread->track();
774 if (track != NULL) {
775 audio_devices_t device = (audio_devices_t)(
776 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700778 thread->setEffectSuspended(FX_IID_AEC,
779 suspend,
780 track->sessionId());
781 thread->setEffectSuspended(FX_IID_NS,
782 suspend,
783 track->sessionId());
784 }
785 }
Eric Laurentbee53372011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700789 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 }
791
792 // hold a strong ref on thread in case closeOutput() or closeInput() is called
793 // and the thread is exited once the lock is released
794 sp<ThreadBase> thread;
795 {
796 Mutex::Autolock _l(mLock);
797 thread = checkPlaybackThread_l(ioHandle);
798 if (thread == NULL) {
799 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800800 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700801 // indicate output device change to all input threads for pre processing
802 AudioParameter param = AudioParameter(keyValuePairs);
803 int value;
804 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807 }
808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800811 if (thread != 0) {
812 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
814 return BAD_VALUE;
815}
816
Glenn Kastenf587ba52012-01-26 16:25:10 -0800817String8 AudioFlinger::getParameters(int ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818{
Steve Block3856b092011-10-20 11:56:00 +0100819// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
821
822 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700823 String8 out_s8;
824
Dima Zavin799a70e2011-04-18 16:57:27 -0700825 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
826 audio_hw_device_t *dev = mAudioHwDevs[i];
827 char *s = dev->get_parameters(dev, keys.string());
828 out_s8 += String8(s);
829 free(s);
830 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700831 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700832 }
833
834 Mutex::Autolock _l(mLock);
835
836 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
837 if (playbackThread != NULL) {
838 return playbackThread->getParameters(keys);
839 }
840 RecordThread *recordThread = checkRecordThread_l(ioHandle);
841 if (recordThread != NULL) {
842 return recordThread->getParameters(keys);
843 }
844 return String8("");
845}
846
Glenn Kastenf587ba52012-01-26 16:25:10 -0800847size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848{
Eric Laurenta1884f92011-08-23 08:25:03 -0700849 status_t ret = initCheck();
850 if (ret != NO_ERROR) {
851 return 0;
852 }
853
Dima Zavin799a70e2011-04-18 16:57:27 -0700854 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700855}
856
Glenn Kastenf587ba52012-01-26 16:25:10 -0800857unsigned int AudioFlinger::getInputFramesLost(int ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858{
859 if (ioHandle == 0) {
860 return 0;
861 }
862
863 Mutex::Autolock _l(mLock);
864
865 RecordThread *recordThread = checkRecordThread_l(ioHandle);
866 if (recordThread != NULL) {
867 return recordThread->getInputFramesLost();
868 }
869 return 0;
870}
871
872status_t AudioFlinger::setVoiceVolume(float value)
873{
Eric Laurenta1884f92011-08-23 08:25:03 -0700874 status_t ret = initCheck();
875 if (ret != NO_ERROR) {
876 return ret;
877 }
878
Mathias Agopian65ab4712010-07-14 17:59:35 -0700879 // check calling permissions
880 if (!settingsAllowed()) {
881 return PERMISSION_DENIED;
882 }
883
884 AutoMutex lock(mHardwareLock);
885 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700886 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700887 mHardwareStatus = AUDIO_HW_IDLE;
888
889 return ret;
890}
891
Glenn Kastenf587ba52012-01-26 16:25:10 -0800892status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893{
894 status_t status;
895
896 Mutex::Autolock _l(mLock);
897
898 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
899 if (playbackThread != NULL) {
900 return playbackThread->getRenderPosition(halFrames, dspFrames);
901 }
902
903 return BAD_VALUE;
904}
905
906void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
907{
908
909 Mutex::Autolock _l(mLock);
910
Glenn Kastenbb001922012-02-03 11:10:26 -0800911 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700912 if (mNotificationClients.indexOfKey(pid) < 0) {
913 sp<NotificationClient> notificationClient = new NotificationClient(this,
914 client,
915 pid);
Steve Block3856b092011-10-20 11:56:00 +0100916 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700917
918 mNotificationClients.add(pid, notificationClient);
919
920 sp<IBinder> binder = client->asBinder();
921 binder->linkToDeath(notificationClient);
922
923 // the config change is always sent from playback or record threads to avoid deadlock
924 // with AudioSystem::gLock
925 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
926 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
927 }
928
929 for (size_t i = 0; i < mRecordThreads.size(); i++) {
930 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
931 }
932 }
933}
934
935void AudioFlinger::removeNotificationClient(pid_t pid)
936{
937 Mutex::Autolock _l(mLock);
938
939 int index = mNotificationClients.indexOfKey(pid);
940 if (index >= 0) {
941 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100942 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943 mNotificationClients.removeItem(pid);
944 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700945
Steve Block3856b092011-10-20 11:56:00 +0100946 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700947 int num = mAudioSessionRefs.size();
948 bool removed = false;
949 for (int i = 0; i< num; i++) {
950 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100951 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700952 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 mAudioSessionRefs.removeAt(i);
955 delete ref;
956 removed = true;
957 i--;
958 num--;
959 }
960 }
961 if (removed) {
962 purgeStaleEffects_l();
963 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700964}
965
966// audioConfigChanged_l() must be called with AudioFlinger::mLock held
967void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
968{
969 size_t size = mNotificationClients.size();
970 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800971 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
972 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700973 }
974}
975
976// removeClient_l() must be called with AudioFlinger::mLock held
977void AudioFlinger::removeClient_l(pid_t pid)
978{
Steve Block3856b092011-10-20 11:56:00 +0100979 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mClients.removeItem(pid);
981}
982
983
984// ----------------------------------------------------------------------------
985
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800986AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
987 type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800989 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800990 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
991 // mChannelMask
992 mChannelCount(0),
993 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
994 mParamStatus(NO_ERROR),
995 mStandby(false), mId(id), mExiting(false),
996 mDevice(device),
997 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998{
999}
1000
1001AudioFlinger::ThreadBase::~ThreadBase()
1002{
1003 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001004 // do not lock the mutex in destructor
1005 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001006 if (mPowerManager != 0) {
1007 sp<IBinder> binder = mPowerManager->asBinder();
1008 binder->unlinkToDeath(mDeathRecipient);
1009 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010}
1011
1012void AudioFlinger::ThreadBase::exit()
1013{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001014 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 // destroyed in the middle of requestExitAndWait()
1016 sp <ThreadBase> strongMe = this;
1017
Steve Block3856b092011-10-20 11:56:00 +01001018 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001020 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 mExiting = true;
1022 requestExit();
1023 mWaitWorkCV.signal();
1024 }
1025 requestExitAndWait();
1026}
1027
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1029{
1030 status_t status;
1031
Steve Block3856b092011-10-20 11:56:00 +01001032 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033 Mutex::Autolock _l(mLock);
1034
1035 mNewParameters.add(keyValuePairs);
1036 mWaitWorkCV.signal();
1037 // wait condition with timeout in case the thread loop has exited
1038 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001039 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040 status = mParamStatus;
1041 mWaitWorkCV.signal();
1042 } else {
1043 status = TIMED_OUT;
1044 }
1045 return status;
1046}
1047
1048void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1049{
1050 Mutex::Autolock _l(mLock);
1051 sendConfigEvent_l(event, param);
1052}
1053
1054// sendConfigEvent_l() must be called with ThreadBase::mLock held
1055void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1056{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001057 ConfigEvent configEvent;
1058 configEvent.mEvent = event;
1059 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001061 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 mWaitWorkCV.signal();
1063}
1064
1065void AudioFlinger::ThreadBase::processConfigEvents()
1066{
1067 mLock.lock();
1068 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001069 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001070 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001071 mConfigEvents.removeAt(0);
1072 // release mLock before locking AudioFlinger mLock: lock order is always
1073 // AudioFlinger then ThreadBase to avoid cross deadlock
1074 mLock.unlock();
1075 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001076 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mLock.lock();
1079 }
1080 mLock.unlock();
1081}
1082
1083status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1084{
1085 const size_t SIZE = 256;
1086 char buffer[SIZE];
1087 String8 result;
1088
1089 bool locked = tryLock(mLock);
1090 if (!locked) {
1091 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1092 write(fd, buffer, strlen(buffer));
1093 }
1094
1095 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1096 result.append(buffer);
1097 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1098 result.append(buffer);
1099 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1100 result.append(buffer);
1101 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1102 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001103 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1104 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001105 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1106 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001107 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 result.append(buffer);
1109
1110 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1111 result.append(buffer);
1112 result.append(" Index Command");
1113 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1114 snprintf(buffer, SIZE, "\n %02d ", i);
1115 result.append(buffer);
1116 result.append(mNewParameters[i]);
1117 }
1118
1119 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, " Index event param\n");
1122 result.append(buffer);
1123 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001124 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001125 result.append(buffer);
1126 }
1127 result.append("\n");
1128
1129 write(fd, result.string(), result.size());
1130
1131 if (locked) {
1132 mLock.unlock();
1133 }
1134 return NO_ERROR;
1135}
1136
Eric Laurent1d2bff02011-07-24 17:49:51 -07001137status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1138{
1139 const size_t SIZE = 256;
1140 char buffer[SIZE];
1141 String8 result;
1142
1143 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1144 write(fd, buffer, strlen(buffer));
1145
1146 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1147 sp<EffectChain> chain = mEffectChains[i];
1148 if (chain != 0) {
1149 chain->dump(fd, args);
1150 }
1151 }
1152 return NO_ERROR;
1153}
1154
Eric Laurentfeb0db62011-07-22 09:04:31 -07001155void AudioFlinger::ThreadBase::acquireWakeLock()
1156{
1157 Mutex::Autolock _l(mLock);
1158 acquireWakeLock_l();
1159}
1160
1161void AudioFlinger::ThreadBase::acquireWakeLock_l()
1162{
1163 if (mPowerManager == 0) {
1164 // use checkService() to avoid blocking if power service is not up yet
1165 sp<IBinder> binder =
1166 defaultServiceManager()->checkService(String16("power"));
1167 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001168 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001169 } else {
1170 mPowerManager = interface_cast<IPowerManager>(binder);
1171 binder->linkToDeath(mDeathRecipient);
1172 }
1173 }
1174 if (mPowerManager != 0) {
1175 sp<IBinder> binder = new BBinder();
1176 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1177 binder,
1178 String16(mName));
1179 if (status == NO_ERROR) {
1180 mWakeLockToken = binder;
1181 }
Steve Block3856b092011-10-20 11:56:00 +01001182 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001183 }
1184}
1185
1186void AudioFlinger::ThreadBase::releaseWakeLock()
1187{
1188 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001189 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001190}
1191
1192void AudioFlinger::ThreadBase::releaseWakeLock_l()
1193{
1194 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001195 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001196 if (mPowerManager != 0) {
1197 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1198 }
1199 mWakeLockToken.clear();
1200 }
1201}
1202
1203void AudioFlinger::ThreadBase::clearPowerManager()
1204{
1205 Mutex::Autolock _l(mLock);
1206 releaseWakeLock_l();
1207 mPowerManager.clear();
1208}
1209
1210void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1211{
1212 sp<ThreadBase> thread = mThread.promote();
1213 if (thread != 0) {
1214 thread->clearPowerManager();
1215 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001216 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001217}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001218
Eric Laurent59255e42011-07-27 19:49:51 -07001219void AudioFlinger::ThreadBase::setEffectSuspended(
1220 const effect_uuid_t *type, bool suspend, int sessionId)
1221{
1222 Mutex::Autolock _l(mLock);
1223 setEffectSuspended_l(type, suspend, sessionId);
1224}
1225
1226void AudioFlinger::ThreadBase::setEffectSuspended_l(
1227 const effect_uuid_t *type, bool suspend, int sessionId)
1228{
Glenn Kasten090f0192012-01-30 13:00:02 -08001229 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001230 if (chain != 0) {
1231 if (type != NULL) {
1232 chain->setEffectSuspended_l(type, suspend);
1233 } else {
1234 chain->setEffectSuspendedAll_l(suspend);
1235 }
1236 }
1237
1238 updateSuspendedSessions_l(type, suspend, sessionId);
1239}
1240
1241void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1242{
1243 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1244 if (index < 0) {
1245 return;
1246 }
1247
1248 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1249 mSuspendedSessions.editValueAt(index);
1250
1251 for (size_t i = 0; i < sessionEffects.size(); i++) {
1252 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1253 for (int j = 0; j < desc->mRefCount; j++) {
1254 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1255 chain->setEffectSuspendedAll_l(true);
1256 } else {
Steve Block3856b092011-10-20 11:56:00 +01001257 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001258 desc->mType.timeLow);
1259 chain->setEffectSuspended_l(&desc->mType, true);
1260 }
1261 }
1262 }
1263}
1264
Eric Laurent59255e42011-07-27 19:49:51 -07001265void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1266 bool suspend,
1267 int sessionId)
1268{
1269 int index = mSuspendedSessions.indexOfKey(sessionId);
1270
1271 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1272
1273 if (suspend) {
1274 if (index >= 0) {
1275 sessionEffects = mSuspendedSessions.editValueAt(index);
1276 } else {
1277 mSuspendedSessions.add(sessionId, sessionEffects);
1278 }
1279 } else {
1280 if (index < 0) {
1281 return;
1282 }
1283 sessionEffects = mSuspendedSessions.editValueAt(index);
1284 }
1285
1286
1287 int key = EffectChain::kKeyForSuspendAll;
1288 if (type != NULL) {
1289 key = type->timeLow;
1290 }
1291 index = sessionEffects.indexOfKey(key);
1292
1293 sp <SuspendedSessionDesc> desc;
1294 if (suspend) {
1295 if (index >= 0) {
1296 desc = sessionEffects.valueAt(index);
1297 } else {
1298 desc = new SuspendedSessionDesc();
1299 if (type != NULL) {
1300 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1301 }
1302 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001303 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001304 }
1305 desc->mRefCount++;
1306 } else {
1307 if (index < 0) {
1308 return;
1309 }
1310 desc = sessionEffects.valueAt(index);
1311 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001312 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001313 sessionEffects.removeItemsAt(index);
1314 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001316 sessionId);
1317 mSuspendedSessions.removeItem(sessionId);
1318 }
1319 }
1320 }
1321 if (!sessionEffects.isEmpty()) {
1322 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1323 }
1324}
1325
1326void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1327 bool enabled,
1328 int sessionId)
1329{
1330 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001331 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1332}
Eric Laurent59255e42011-07-27 19:49:51 -07001333
Eric Laurenta85a74a2011-10-19 11:44:54 -07001334void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1335 bool enabled,
1336 int sessionId)
1337{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001338 if (mType != RECORD) {
1339 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1340 // another session. This gives the priority to well behaved effect control panels
1341 // and applications not using global effects.
1342 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1343 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1344 }
1345 }
Eric Laurent59255e42011-07-27 19:49:51 -07001346
1347 sp<EffectChain> chain = getEffectChain_l(sessionId);
1348 if (chain != 0) {
1349 chain->checkSuspendOnEffectEnabled(effect, enabled);
1350 }
1351}
1352
Mathias Agopian65ab4712010-07-14 17:59:35 -07001353// ----------------------------------------------------------------------------
1354
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001355AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1356 AudioStreamOut* output,
1357 int id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001358 uint32_t device,
1359 type_t type)
1360 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001361 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1362 // Assumes constructor is called by AudioFlinger with it's mLock held,
1363 // but it would be safer to explicitly pass initial masterMute as parameter
1364 mMasterMute(audioFlinger->masterMute_l()),
1365 // mStreamTypes[] initialized in constructor body
1366 mOutput(output),
1367 // Assumes constructor is called by AudioFlinger with it's mLock held,
1368 // but it would be safer to explicitly pass initial masterVolume as parameter
1369 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001370 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001371{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001372 snprintf(mName, kNameLength, "AudioOut_%d", id);
1373
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374 readOutputParameters();
1375
Glenn Kasten263709e2012-01-06 08:40:01 -08001376 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001377 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1378 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1379 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1381 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001382 // initialized by stream_type_t default constructor
1383 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 }
1385}
1386
1387AudioFlinger::PlaybackThread::~PlaybackThread()
1388{
1389 delete [] mMixBuffer;
1390}
1391
1392status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1393{
1394 dumpInternals(fd, args);
1395 dumpTracks(fd, args);
1396 dumpEffectChains(fd, args);
1397 return NO_ERROR;
1398}
1399
1400status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1401{
1402 const size_t SIZE = 256;
1403 char buffer[SIZE];
1404 String8 result;
1405
1406 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1407 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001408 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 -07001409 for (size_t i = 0; i < mTracks.size(); ++i) {
1410 sp<Track> track = mTracks[i];
1411 if (track != 0) {
1412 track->dump(buffer, SIZE);
1413 result.append(buffer);
1414 }
1415 }
1416
1417 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1418 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001419 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001421 sp<Track> track = mActiveTracks[i].promote();
1422 if (track != 0) {
1423 track->dump(buffer, SIZE);
1424 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001425 }
1426 }
1427 write(fd, result.string(), result.size());
1428 return NO_ERROR;
1429}
1430
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1432{
1433 const size_t SIZE = 256;
1434 char buffer[SIZE];
1435 String8 result;
1436
1437 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1438 result.append(buffer);
1439 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1440 result.append(buffer);
1441 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1442 result.append(buffer);
1443 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1444 result.append(buffer);
1445 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1450 result.append(buffer);
1451 write(fd, result.string(), result.size());
1452
1453 dumpBase(fd, args);
1454
1455 return NO_ERROR;
1456}
1457
1458// Thread virtuals
1459status_t AudioFlinger::PlaybackThread::readyToRun()
1460{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001461 status_t status = initCheck();
1462 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001463 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001464 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001465 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001467 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468}
1469
1470void AudioFlinger::PlaybackThread::onFirstRef()
1471{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001472 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473}
1474
1475// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1476sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1477 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001478 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001480 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001481 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 int frameCount,
1483 const sp<IMemory>& sharedBuffer,
1484 int sessionId,
1485 status_t *status)
1486{
1487 sp<Track> track;
1488 status_t lStatus;
1489
1490 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001491 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1492 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001493 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001494 "for output %p with format %d",
1495 sampleRate, format, channelMask, mOutput, mFormat);
1496 lStatus = BAD_VALUE;
1497 goto Exit;
1498 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 }
1500 } else {
1501 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1502 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001503 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 lStatus = BAD_VALUE;
1505 goto Exit;
1506 }
1507 }
1508
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001509 lStatus = initCheck();
1510 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001511 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 goto Exit;
1513 }
1514
1515 { // scope for mLock
1516 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001517
1518 // all tracks in same audio session must share the same routing strategy otherwise
1519 // conflicts will happen when tracks are moved from one output to another by audio policy
1520 // manager
1521 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001522 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001523 for (size_t i = 0; i < mTracks.size(); ++i) {
1524 sp<Track> t = mTracks[i];
1525 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001526 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1527 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001528 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001529 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001530 lStatus = BAD_VALUE;
1531 goto Exit;
1532 }
1533 }
1534 }
1535
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001537 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001538 if (track->getCblk() == NULL || track->name() < 0) {
1539 lStatus = NO_MEMORY;
1540 goto Exit;
1541 }
1542 mTracks.add(track);
1543
1544 sp<EffectChain> chain = getEffectChain_l(sessionId);
1545 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001546 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001548 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001549 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001551
1552 // invalidate track immediately if the stream type was moved to another thread since
1553 // createTrack() was called by the client process.
1554 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001555 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001556 this, streamType);
1557 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 }
1560 lStatus = NO_ERROR;
1561
1562Exit:
1563 if(status) {
1564 *status = lStatus;
1565 }
1566 return track;
1567}
1568
1569uint32_t AudioFlinger::PlaybackThread::latency() const
1570{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001571 Mutex::Autolock _l(mLock);
1572 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001573 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001574 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001575 return 0;
1576 }
1577}
1578
1579status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1580{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 mMasterVolume = value;
1582 return NO_ERROR;
1583}
1584
1585status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1586{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 mMasterMute = muted;
1588 return NO_ERROR;
1589}
1590
Glenn Kastenfff6d712012-01-12 16:38:12 -08001591status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 mStreamTypes[stream].volume = value;
1594 return NO_ERROR;
1595}
1596
Glenn Kastenfff6d712012-01-12 16:38:12 -08001597status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599 mStreamTypes[stream].mute = muted;
1600 return NO_ERROR;
1601}
1602
Glenn Kastenfff6d712012-01-12 16:38:12 -08001603float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604{
1605 return mStreamTypes[stream].volume;
1606}
1607
Glenn Kastenfff6d712012-01-12 16:38:12 -08001608bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609{
1610 return mStreamTypes[stream].mute;
1611}
1612
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613// addTrack_l() must be called with ThreadBase::mLock held
1614status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1615{
1616 status_t status = ALREADY_EXISTS;
1617
1618 // set retry count for buffer fill
1619 track->mRetryCount = kMaxTrackStartupRetries;
1620 if (mActiveTracks.indexOf(track) < 0) {
1621 // the track is newly added, make sure it fills up all its
1622 // buffers before playing. This is to ensure the client will
1623 // effectively get the latency it requested.
1624 track->mFillingUpStatus = Track::FS_FILLING;
1625 track->mResetDone = false;
1626 mActiveTracks.add(track);
1627 if (track->mainBuffer() != mMixBuffer) {
1628 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1629 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001630 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001631 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632 }
1633 }
1634
1635 status = NO_ERROR;
1636 }
1637
Steve Block3856b092011-10-20 11:56:00 +01001638 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 mWaitWorkCV.broadcast();
1640
1641 return status;
1642}
1643
1644// destroyTrack_l() must be called with ThreadBase::mLock held
1645void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1646{
1647 track->mState = TrackBase::TERMINATED;
1648 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001649 removeTrack_l(track);
1650 }
1651}
1652
1653void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1654{
1655 mTracks.remove(track);
1656 deleteTrackName_l(track->name());
1657 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1658 if (chain != 0) {
1659 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 }
1661}
1662
1663String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1664{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001665 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001666 char *s;
1667
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001668 Mutex::Autolock _l(mLock);
1669 if (initCheck() != NO_ERROR) {
1670 return out_s8;
1671 }
1672
Dima Zavin799a70e2011-04-18 16:57:27 -07001673 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001674 out_s8 = String8(s);
1675 free(s);
1676 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677}
1678
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001679// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1681 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001682 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683
Steve Block3856b092011-10-20 11:56:00 +01001684 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685
1686 switch (event) {
1687 case AudioSystem::OUTPUT_OPENED:
1688 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001689 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 desc.samplingRate = mSampleRate;
1691 desc.format = mFormat;
1692 desc.frameCount = mFrameCount;
1693 desc.latency = latency();
1694 param2 = &desc;
1695 break;
1696
1697 case AudioSystem::STREAM_CONFIG_CHANGED:
1698 param2 = &param;
1699 case AudioSystem::OUTPUT_CLOSED:
1700 default:
1701 break;
1702 }
1703 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1704}
1705
1706void AudioFlinger::PlaybackThread::readOutputParameters()
1707{
Dima Zavin799a70e2011-04-18 16:57:27 -07001708 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001709 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1710 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001711 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001712 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001713 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714
1715 // FIXME - Current mixer implementation only supports stereo output: Always
1716 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001717 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 mMixBuffer = new int16_t[mFrameCount * 2];
1719 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1720
Eric Laurentde070132010-07-13 04:45:46 -07001721 // force reconfiguration of effect chains and engines to take new buffer size and audio
1722 // parameters into account
1723 // Note that mLock is not held when readOutputParameters() is called from the constructor
1724 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1725 // matter.
1726 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1727 Vector< sp<EffectChain> > effectChains = mEffectChains;
1728 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001729 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001730 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001731}
1732
1733status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1734{
Glenn Kastena0d68332012-01-27 16:47:15 -08001735 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 return BAD_VALUE;
1737 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001738 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001739 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 return INVALID_OPERATION;
1741 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001742 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743
Dima Zavin799a70e2011-04-18 16:57:27 -07001744 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745}
1746
Eric Laurent39e94f82010-07-28 01:32:47 -07001747uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748{
1749 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001750 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001752 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 }
1754
1755 for (size_t i = 0; i < mTracks.size(); ++i) {
1756 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001757 if (sessionId == track->sessionId() &&
1758 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001759 result |= TRACK_SESSION;
1760 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 }
1762 }
1763
Eric Laurent39e94f82010-07-28 01:32:47 -07001764 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001765}
1766
Eric Laurentde070132010-07-13 04:45:46 -07001767uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1768{
Dima Zavinfce7a472011-04-19 22:30:36 -07001769 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001770 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001771 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1772 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001773 }
1774 for (size_t i = 0; i < mTracks.size(); i++) {
1775 sp<Track> track = mTracks[i];
1776 if (sessionId == track->sessionId() &&
1777 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001778 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001779 }
1780 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001781 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001782}
1783
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784
Glenn Kastenaed850d2012-01-26 09:46:34 -08001785AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001786{
1787 Mutex::Autolock _l(mLock);
1788 return mOutput;
1789}
1790
1791AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1792{
1793 Mutex::Autolock _l(mLock);
1794 AudioStreamOut *output = mOutput;
1795 mOutput = NULL;
1796 return output;
1797}
1798
1799// this method must always be called either with ThreadBase mLock held or inside the thread loop
1800audio_stream_t* AudioFlinger::PlaybackThread::stream()
1801{
1802 if (mOutput == NULL) {
1803 return NULL;
1804 }
1805 return &mOutput->stream->common;
1806}
1807
Eric Laurent162b40b2011-12-05 09:47:19 -08001808uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1809{
1810 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1811 // decoding and transfer time. So sleeping for half of the latency would likely cause
1812 // underruns
1813 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1814 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1815 } else {
1816 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1817 }
1818}
1819
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820// ----------------------------------------------------------------------------
1821
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001822AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1823 int id, uint32_t device, type_t type)
1824 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001825 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1826 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 // FIXME - Current mixer implementation only supports stereo output
1829 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001830 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 }
1832}
1833
1834AudioFlinger::MixerThread::~MixerThread()
1835{
1836 delete mAudioMixer;
1837}
1838
1839bool AudioFlinger::MixerThread::threadLoop()
1840{
1841 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001842 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 nsecs_t standbyTime = systemTime();
1844 size_t mixBufferSize = mFrameCount * mFrameSize;
1845 // FIXME: Relaxed timing because of a certain device that can't meet latency
1846 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001847 // increase threshold again due to low power audio mode. The way this warning threshold is
1848 // calculated and its usefulness should be reconsidered anyway.
1849 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 nsecs_t lastWarning = 0;
1851 bool longStandbyExit = false;
1852 uint32_t activeSleepTime = activeSleepTimeUs();
1853 uint32_t idleSleepTime = idleSleepTimeUs();
1854 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001855 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001857#ifdef DEBUG_CPU_USAGE
1858 ThreadCpuUsage cpu;
1859 const CentralTendencyStatistics& stats = cpu.statistics();
1860#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861
Eric Laurentfeb0db62011-07-22 09:04:31 -07001862 acquireWakeLock();
1863
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 while (!exitPending())
1865 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001866#ifdef DEBUG_CPU_USAGE
1867 cpu.sampleAndEnable();
1868 unsigned n = stats.n();
1869 // cpu.elapsed() is expensive, so don't call it every loop
1870 if ((n & 127) == 1) {
1871 long long elapsed = cpu.elapsed();
1872 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1873 double perLoop = elapsed / (double) n;
1874 double perLoop100 = perLoop * 0.01;
1875 double mean = stats.mean();
1876 double stddev = stats.stddev();
1877 double minimum = stats.minimum();
1878 double maximum = stats.maximum();
1879 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001880 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 -07001881 elapsed * .000000001, n, perLoop * .000001,
1882 mean * .001,
1883 stddev * .001,
1884 minimum * .001,
1885 maximum * .001,
1886 mean / perLoop100,
1887 stddev / perLoop100,
1888 minimum / perLoop100,
1889 maximum / perLoop100);
1890 }
1891 }
1892#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 processConfigEvents();
1894
1895 mixerStatus = MIXER_IDLE;
1896 { // scope for mLock
1897
1898 Mutex::Autolock _l(mLock);
1899
1900 if (checkForNewParameters_l()) {
1901 mixBufferSize = mFrameCount * mFrameSize;
1902 // FIXME: Relaxed timing because of a certain device that can't meet latency
1903 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001904 // increase threshold again due to low power audio mode. The way this warning
1905 // threshold is calculated and its usefulness should be reconsidered anyway.
1906 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 activeSleepTime = activeSleepTimeUs();
1908 idleSleepTime = idleSleepTimeUs();
1909 }
1910
1911 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1912
1913 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001914 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1915 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001917 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001918 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 mStandby = true;
1920 mBytesWritten = 0;
1921 }
1922
1923 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1924 // we're about to wait, flush the binder command buffer
1925 IPCThreadState::self()->flushCommands();
1926
1927 if (exitPending()) break;
1928
Eric Laurentfeb0db62011-07-22 09:04:31 -07001929 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001931 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001933 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001934 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935
Eric Laurent27741442012-01-17 19:20:12 -08001936 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001937 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 char value[PROPERTY_VALUE_MAX];
1939 property_get("ro.audio.silent", value, "0");
1940 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001941 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 setMasterMute(true);
1943 }
1944 }
1945
1946 standbyTime = systemTime() + kStandbyTimeInNsecs;
1947 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001948 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 continue;
1950 }
1951 }
1952
1953 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1954
1955 // prevent any changes in effect chain list and in each effect chain
1956 // during mixing and effect process as the audio buffers could be deleted
1957 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001958 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
Glenn Kastenf6b16782011-12-15 09:51:17 -08001961 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 // mix buffers...
1963 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001964 // increase sleep time progressively when application underrun condition clears.
1965 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1966 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1967 // such that we would underrun the audio HAL.
1968 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001969 sleepTimeShift--;
1970 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001971 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 standbyTime = systemTime() + kStandbyTimeInNsecs;
1973 //TODO: delay standby when effects have a tail
1974 } else {
1975 // If no tracks are ready, sleep once for the duration of an output
1976 // buffer size, then write 0s to the output
1977 if (sleepTime == 0) {
1978 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001979 sleepTime = activeSleepTime >> sleepTimeShift;
1980 if (sleepTime < kMinThreadSleepTimeUs) {
1981 sleepTime = kMinThreadSleepTimeUs;
1982 }
1983 // reduce sleep time in case of consecutive application underruns to avoid
1984 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1985 // duration we would end up writing less data than needed by the audio HAL if
1986 // the condition persists.
1987 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1988 sleepTimeShift++;
1989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 } else {
1991 sleepTime = idleSleepTime;
1992 }
1993 } else if (mBytesWritten != 0 ||
1994 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1995 memset (mMixBuffer, 0, mixBufferSize);
1996 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01001997 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001998 }
1999 // TODO add standby time extension fct of effect tail
2000 }
2001
2002 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002003 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 }
2005 // sleepTime == 0 means we must write to audio hardware
2006 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002007 for (size_t i = 0; i < effectChains.size(); i ++) {
2008 effectChains[i]->process_l();
2009 }
2010 // enable changes in effect chain
2011 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 mLastWriteTime = systemTime();
2013 mInWrite = true;
2014 mBytesWritten += mixBufferSize;
2015
Dima Zavin799a70e2011-04-18 16:57:27 -07002016 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2018 mNumWrites++;
2019 mInWrite = false;
2020 nsecs_t now = systemTime();
2021 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002022 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002024 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002025 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 ns2ms(delta), mNumDelayedWrites, this);
2027 lastWarning = now;
2028 }
2029 if (mStandby) {
2030 longStandbyExit = true;
2031 }
2032 }
2033 mStandby = false;
2034 } else {
2035 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002036 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 usleep(sleepTime);
2038 }
2039
2040 // finally let go of all our tracks, without the lock held
2041 // since we can't guarantee the destructors won't acquire that
2042 // same lock.
2043 tracksToRemove.clear();
2044
2045 // Effect chains will be actually deleted here if they were removed from
2046 // mEffectChains list during mixing or effects processing
2047 effectChains.clear();
2048 }
2049
2050 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002051 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 }
2053
Eric Laurentfeb0db62011-07-22 09:04:31 -07002054 releaseWakeLock();
2055
Steve Block3856b092011-10-20 11:56:00 +01002056 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 return false;
2058}
2059
2060// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002061AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2062 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063{
2064
Glenn Kasten29c23c32012-01-26 13:37:52 -08002065 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 // find out which tracks need to be processed
2067 size_t count = activeTracks.size();
2068 size_t mixedTracks = 0;
2069 size_t tracksWithEffect = 0;
2070
2071 float masterVolume = mMasterVolume;
2072 bool masterMute = mMasterMute;
2073
Eric Laurent571d49c2010-08-11 05:20:11 -07002074 if (masterMute) {
2075 masterVolume = 0;
2076 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002078 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002080 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002081 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 masterVolume = (float)((v + (1 << 23)) >> 24);
2083 chain.clear();
2084 }
2085
2086 for (size_t i=0 ; i<count ; i++) {
2087 sp<Track> t = activeTracks[i].promote();
2088 if (t == 0) continue;
2089
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002090 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 Track* const track = t.get();
2092 audio_track_cblk_t* cblk = track->cblk();
2093
2094 // The first time a track is added we wait
2095 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002096 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002097 // make sure that we have enough frames to mix one full buffer.
2098 // enforce this condition only once to enable draining the buffer in case the client
2099 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002100 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002101 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002102 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002103 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002104 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002105 if (t->sampleRate() == (int)mSampleRate) {
2106 minFrames = mFrameCount;
2107 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002108 // +1 for rounding and +1 for additional sample needed for interpolation
2109 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2110 // add frames already consumed but not yet released by the resampler
2111 // because cblk->framesReady() will include these frames
2112 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2113 // the minimum track buffer size is normally twice the number of frames necessary
2114 // to fill one buffer and the resampler should not leave more than one buffer worth
2115 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002116 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002117 }
2118 }
2119 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 !track->isPaused() && !track->isTerminated())
2121 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002122 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123
2124 mixedTracks++;
2125
2126 // track->mainBuffer() != mMixBuffer means there is an effect chain
2127 // connected to the track
2128 chain.clear();
2129 if (track->mainBuffer() != mMixBuffer) {
2130 chain = getEffectChain_l(track->sessionId());
2131 // Delegate volume control to effect in track effect chain if needed
2132 if (chain != 0) {
2133 tracksWithEffect++;
2134 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002135 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002136 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137 }
2138 }
2139
2140
2141 int param = AudioMixer::VOLUME;
2142 if (track->mFillingUpStatus == Track::FS_FILLED) {
2143 // no ramp for the first volume setting
2144 track->mFillingUpStatus = Track::FS_ACTIVE;
2145 if (track->mState == TrackBase::RESUMING) {
2146 track->mState = TrackBase::ACTIVE;
2147 param = AudioMixer::RAMP_VOLUME;
2148 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002149 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 } else if (cblk->server != 0) {
2151 // If the track is stopped before the first frame was mixed,
2152 // do not apply ramp
2153 param = AudioMixer::RAMP_VOLUME;
2154 }
2155
2156 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002157 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002158 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002160 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 if (track->isPausing()) {
2162 track->setPaused();
2163 }
2164 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002165
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 // read original volumes with volume control
2167 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002169 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002170 vl = vlr & 0xFFFF;
2171 vr = vlr >> 16;
2172 // track volumes come from shared memory, so can't be trusted and must be clamped
2173 if (vl > MAX_GAIN_INT) {
2174 ALOGV("Track left volume out of range: %04X", vl);
2175 vl = MAX_GAIN_INT;
2176 }
2177 if (vr > MAX_GAIN_INT) {
2178 ALOGV("Track right volume out of range: %04X", vr);
2179 vr = MAX_GAIN_INT;
2180 }
2181 // now apply the master volume and stream type volume
2182 vl = (uint32_t)(v * vl) << 12;
2183 vr = (uint32_t)(v * vr) << 12;
2184 // assuming master volume and stream type volume each go up to 1.0,
2185 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186
Glenn Kasten05632a52012-01-03 14:22:33 -08002187 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2188 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002189 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002190 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002191 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002192 }
2193 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002195 // Delegate volume control to effect in track effect chain if needed
2196 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2197 // Do not ramp volume if volume is controlled by effect
2198 param = AudioMixer::VOLUME;
2199 track->mHasVolumeController = true;
2200 } else {
2201 // force no volume ramp when volume controller was just disabled or removed
2202 // from effect chain to avoid volume spike
2203 if (track->mHasVolumeController) {
2204 param = AudioMixer::VOLUME;
2205 }
2206 track->mHasVolumeController = false;
2207 }
2208
2209 // Convert volumes from 8.24 to 4.12 format
2210 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002211 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002212 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2213 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2214 left = int16_t(v_clamped);
2215 v_clamped = (vr + (1 << 11)) >> 12;
2216 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2217 right = int16_t(v_clamped);
2218
2219 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2220 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002223 mAudioMixer->setBufferProvider(name, track);
2224 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002226 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2227 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2228 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002230 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231 AudioMixer::TRACK,
2232 AudioMixer::FORMAT, (void *)track->format());
2233 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002234 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002236 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002238 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 AudioMixer::RESAMPLE,
2240 AudioMixer::SAMPLE_RATE,
2241 (void *)(cblk->sampleRate));
2242 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002243 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 AudioMixer::TRACK,
2245 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2246 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002247 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 AudioMixer::TRACK,
2249 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2250
2251 // reset retry count
2252 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002253 // If one track is ready, set the mixer ready if:
2254 // - the mixer was not ready during previous round OR
2255 // - no other track is not ready
2256 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2257 mixerStatus != MIXER_TRACKS_ENABLED) {
2258 mixerStatus = MIXER_TRACKS_READY;
2259 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002261 //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 -07002262 if (track->isStopped()) {
2263 track->reset();
2264 }
2265 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2266 // We have consumed all the buffers of this track.
2267 // Remove it from the list of active tracks.
2268 tracksToRemove->add(track);
2269 } else {
2270 // No buffers for this track. Give it a few chances to
2271 // fill a buffer, then remove it from active list.
2272 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002273 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002275 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002276 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002277 // If one track is not ready, mark the mixer also not ready if:
2278 // - the mixer was ready during previous round OR
2279 // - no other track is ready
2280 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2281 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 mixerStatus = MIXER_TRACKS_ENABLED;
2283 }
2284 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002285 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 }
2287 }
2288
2289 // remove all the tracks that need to be...
2290 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002291 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 for (size_t i=0 ; i<count ; i++) {
2293 const sp<Track>& track = tracksToRemove->itemAt(i);
2294 mActiveTracks.remove(track);
2295 if (track->mainBuffer() != mMixBuffer) {
2296 chain = getEffectChain_l(track->sessionId());
2297 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002298 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002299 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300 }
2301 }
2302 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002303 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304 }
2305 }
2306 }
2307
2308 // mix buffer must be cleared if all tracks are connected to an
2309 // effect chain as in this case the mixer will not write to
2310 // mix buffer and track effects will accumulate into it
2311 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2312 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2313 }
2314
Eric Laurent27741442012-01-17 19:20:12 -08002315 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 return mixerStatus;
2317}
2318
Glenn Kastenfff6d712012-01-12 16:38:12 -08002319void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320{
Steve Block3856b092011-10-20 11:56:00 +01002321 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002322 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002324
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325 size_t size = mTracks.size();
2326 for (size_t i = 0; i < size; i++) {
2327 sp<Track> t = mTracks[i];
2328 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002329 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 }
2332 }
2333}
2334
Glenn Kastenfff6d712012-01-12 16:38:12 -08002335void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002336{
Steve Block3856b092011-10-20 11:56:00 +01002337 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002338 this, streamType, valid);
2339 Mutex::Autolock _l(mLock);
2340
2341 mStreamTypes[streamType].valid = valid;
2342}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343
2344// getTrackName_l() must be called with ThreadBase::mLock held
2345int AudioFlinger::MixerThread::getTrackName_l()
2346{
2347 return mAudioMixer->getTrackName();
2348}
2349
2350// deleteTrackName_l() must be called with ThreadBase::mLock held
2351void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2352{
Steve Block3856b092011-10-20 11:56:00 +01002353 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354 mAudioMixer->deleteTrackName(name);
2355}
2356
2357// checkForNewParameters_l() must be called with ThreadBase::mLock held
2358bool AudioFlinger::MixerThread::checkForNewParameters_l()
2359{
2360 bool reconfig = false;
2361
2362 while (!mNewParameters.isEmpty()) {
2363 status_t status = NO_ERROR;
2364 String8 keyValuePair = mNewParameters[0];
2365 AudioParameter param = AudioParameter(keyValuePair);
2366 int value;
2367
2368 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2369 reconfig = true;
2370 }
2371 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002372 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373 status = BAD_VALUE;
2374 } else {
2375 reconfig = true;
2376 }
2377 }
2378 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002379 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002380 status = BAD_VALUE;
2381 } else {
2382 reconfig = true;
2383 }
2384 }
2385 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2386 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002387 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 // if frame count is changed after track creation
2389 if (!mTracks.isEmpty()) {
2390 status = INVALID_OPERATION;
2391 } else {
2392 reconfig = true;
2393 }
2394 }
2395 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002396 // when changing the audio output device, call addBatteryData to notify
2397 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002398 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002399 uint32_t params = 0;
2400 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002401 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002402 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2403 }
2404
2405 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002406 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002407 // check if any other device (except speaker) is on
2408 if (value & deviceWithoutSpeaker ) {
2409 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2410 }
2411
2412 if (params != 0) {
2413 addBatteryData(params);
2414 }
2415 }
2416
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 // forward device change to effects that have requested to be
2418 // aware of attached audio device.
2419 mDevice = (uint32_t)value;
2420 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002421 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 }
2423 }
2424
2425 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002426 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002427 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002429 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 mStandby = true;
2431 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002432 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002433 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 }
2435 if (status == NO_ERROR && reconfig) {
2436 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002437 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2438 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 readOutputParameters();
2440 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2441 for (size_t i = 0; i < mTracks.size() ; i++) {
2442 int name = getTrackName_l();
2443 if (name < 0) break;
2444 mTracks[i]->mName = name;
2445 // limit track sample rate to 2 x new output sample rate
2446 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2447 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2448 }
2449 }
2450 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2451 }
2452 }
2453
2454 mNewParameters.removeAt(0);
2455
2456 mParamStatus = status;
2457 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002458 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2459 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002460 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 }
2462 return reconfig;
2463}
2464
2465status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2466{
2467 const size_t SIZE = 256;
2468 char buffer[SIZE];
2469 String8 result;
2470
2471 PlaybackThread::dumpInternals(fd, args);
2472
2473 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2474 result.append(buffer);
2475 write(fd, result.string(), result.size());
2476 return NO_ERROR;
2477}
2478
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2480{
Eric Laurent60e18242010-07-29 06:50:24 -07002481 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482}
2483
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002484uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2485{
2486 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2487}
2488
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002490AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002491 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002492 // mLeftVolFloat, mRightVolFloat
2493 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495}
2496
2497AudioFlinger::DirectOutputThread::~DirectOutputThread()
2498{
2499}
2500
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501static inline
2502int32_t mul(int16_t in, int16_t v)
2503{
2504#if defined(__arm__) && !defined(__thumb__)
2505 int32_t out;
2506 asm( "smulbb %[out], %[in], %[v] \n"
2507 : [out]"=r"(out)
2508 : [in]"%r"(in), [v]"r"(v)
2509 : );
2510 return out;
2511#else
2512 return in * int32_t(v);
2513#endif
2514}
2515
2516void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2517{
2518 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002519 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002520 return;
2521 }
2522
2523 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002524 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002525 size_t count = mFrameCount * mChannelCount;
2526 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2527 int16_t *dst = mMixBuffer + count-1;
2528 while(count--) {
2529 *dst-- = (int16_t)(*src--^0x80) << 8;
2530 }
2531 }
2532
2533 size_t frameCount = mFrameCount;
2534 int16_t *out = mMixBuffer;
2535 if (ramp) {
2536 if (mChannelCount == 1) {
2537 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2538 int32_t vlInc = d / (int32_t)frameCount;
2539 int32_t vl = ((int32_t)mLeftVolShort << 16);
2540 do {
2541 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2542 out++;
2543 vl += vlInc;
2544 } while (--frameCount);
2545
2546 } else {
2547 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2548 int32_t vlInc = d / (int32_t)frameCount;
2549 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2550 int32_t vrInc = d / (int32_t)frameCount;
2551 int32_t vl = ((int32_t)mLeftVolShort << 16);
2552 int32_t vr = ((int32_t)mRightVolShort << 16);
2553 do {
2554 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2555 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2556 out += 2;
2557 vl += vlInc;
2558 vr += vrInc;
2559 } while (--frameCount);
2560 }
2561 } else {
2562 if (mChannelCount == 1) {
2563 do {
2564 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2565 out++;
2566 } while (--frameCount);
2567 } else {
2568 do {
2569 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2570 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2571 out += 2;
2572 } while (--frameCount);
2573 }
2574 }
2575
2576 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002577 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002578 size_t count = mFrameCount * mChannelCount;
2579 int16_t *src = mMixBuffer;
2580 uint8_t *dst = (uint8_t *)mMixBuffer;
2581 while(count--) {
2582 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2583 }
2584 }
2585
2586 mLeftVolShort = leftVol;
2587 mRightVolShort = rightVol;
2588}
2589
2590bool AudioFlinger::DirectOutputThread::threadLoop()
2591{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002592 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 sp<Track> trackToRemove;
2594 sp<Track> activeTrack;
2595 nsecs_t standbyTime = systemTime();
2596 int8_t *curBuf;
2597 size_t mixBufferSize = mFrameCount*mFrameSize;
2598 uint32_t activeSleepTime = activeSleepTimeUs();
2599 uint32_t idleSleepTime = idleSleepTimeUs();
2600 uint32_t sleepTime = idleSleepTime;
2601 // use shorter standby delay as on normal output to release
2602 // hardware resources as soon as possible
2603 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2604
Eric Laurentfeb0db62011-07-22 09:04:31 -07002605 acquireWakeLock();
2606
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 while (!exitPending())
2608 {
2609 bool rampVolume;
2610 uint16_t leftVol;
2611 uint16_t rightVol;
2612 Vector< sp<EffectChain> > effectChains;
2613
2614 processConfigEvents();
2615
2616 mixerStatus = MIXER_IDLE;
2617
2618 { // scope for the mLock
2619
2620 Mutex::Autolock _l(mLock);
2621
2622 if (checkForNewParameters_l()) {
2623 mixBufferSize = mFrameCount*mFrameSize;
2624 activeSleepTime = activeSleepTimeUs();
2625 idleSleepTime = idleSleepTimeUs();
2626 standbyDelay = microseconds(activeSleepTime*2);
2627 }
2628
2629 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002630 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2631 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 // wait until we have something to do...
2633 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002634 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002635 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 mStandby = true;
2637 mBytesWritten = 0;
2638 }
2639
2640 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2641 // we're about to wait, flush the binder command buffer
2642 IPCThreadState::self()->flushCommands();
2643
2644 if (exitPending()) break;
2645
Eric Laurentfeb0db62011-07-22 09:04:31 -07002646 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002647 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002649 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002650 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651
Glenn Kastenf1d45922012-01-13 15:54:24 -08002652 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 char value[PROPERTY_VALUE_MAX];
2654 property_get("ro.audio.silent", value, "0");
2655 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002656 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657 setMasterMute(true);
2658 }
2659 }
2660
2661 standbyTime = systemTime() + standbyDelay;
2662 sleepTime = idleSleepTime;
2663 continue;
2664 }
2665 }
2666
2667 effectChains = mEffectChains;
2668
2669 // find out which tracks need to be processed
2670 if (mActiveTracks.size() != 0) {
2671 sp<Track> t = mActiveTracks[0].promote();
2672 if (t == 0) continue;
2673
2674 Track* const track = t.get();
2675 audio_track_cblk_t* cblk = track->cblk();
2676
2677 // The first time a track is added we wait
2678 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002679 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 !track->isPaused() && !track->isTerminated())
2681 {
Steve Block3856b092011-10-20 11:56:00 +01002682 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683
2684 if (track->mFillingUpStatus == Track::FS_FILLED) {
2685 track->mFillingUpStatus = Track::FS_ACTIVE;
2686 mLeftVolFloat = mRightVolFloat = 0;
2687 mLeftVolShort = mRightVolShort = 0;
2688 if (track->mState == TrackBase::RESUMING) {
2689 track->mState = TrackBase::ACTIVE;
2690 rampVolume = true;
2691 }
2692 } else if (cblk->server != 0) {
2693 // If the track is stopped before the first frame was mixed,
2694 // do not apply ramp
2695 rampVolume = true;
2696 }
2697 // compute volume for this track
2698 float left, right;
2699 if (track->isMuted() || mMasterMute || track->isPausing() ||
2700 mStreamTypes[track->type()].mute) {
2701 left = right = 0;
2702 if (track->isPausing()) {
2703 track->setPaused();
2704 }
2705 } else {
2706 float typeVolume = mStreamTypes[track->type()].volume;
2707 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002708 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002709 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2711 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002712 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2714 right = v_clamped/MAX_GAIN;
2715 }
2716
2717 if (left != mLeftVolFloat || right != mRightVolFloat) {
2718 mLeftVolFloat = left;
2719 mRightVolFloat = right;
2720
2721 // If audio HAL implements volume control,
2722 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002723 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002724 left = 1.0f;
2725 right = 1.0f;
2726 }
2727
2728 // Convert volumes from float to 8.24
2729 uint32_t vl = (uint32_t)(left * (1 << 24));
2730 uint32_t vr = (uint32_t)(right * (1 << 24));
2731
2732 // Delegate volume control to effect in track effect chain if needed
2733 // only one effect chain can be present on DirectOutputThread, so if
2734 // there is one, the track is connected to it
2735 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002736 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002737 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 rampVolume = false;
2739 }
2740 }
2741
2742 // Convert volumes from 8.24 to 4.12 format
2743 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2744 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2745 leftVol = (uint16_t)v_clamped;
2746 v_clamped = (vr + (1 << 11)) >> 12;
2747 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2748 rightVol = (uint16_t)v_clamped;
2749 } else {
2750 leftVol = mLeftVolShort;
2751 rightVol = mRightVolShort;
2752 rampVolume = false;
2753 }
2754
2755 // reset retry count
2756 track->mRetryCount = kMaxTrackRetriesDirect;
2757 activeTrack = t;
2758 mixerStatus = MIXER_TRACKS_READY;
2759 } else {
Steve Block3856b092011-10-20 11:56:00 +01002760 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 if (track->isStopped()) {
2762 track->reset();
2763 }
2764 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2765 // We have consumed all the buffers of this track.
2766 // Remove it from the list of active tracks.
2767 trackToRemove = track;
2768 } else {
2769 // No buffers for this track. Give it a few chances to
2770 // fill a buffer, then remove it from active list.
2771 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002772 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773 trackToRemove = track;
2774 } else {
2775 mixerStatus = MIXER_TRACKS_ENABLED;
2776 }
2777 }
2778 }
2779 }
2780
2781 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002782 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783 mActiveTracks.remove(trackToRemove);
2784 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002785 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002786 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002787 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 }
2789 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002790 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 }
2792 }
2793
Eric Laurentde070132010-07-13 04:45:46 -07002794 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 }
2796
Glenn Kastenf6b16782011-12-15 09:51:17 -08002797 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 AudioBufferProvider::Buffer buffer;
2799 size_t frameCount = mFrameCount;
2800 curBuf = (int8_t *)mMixBuffer;
2801 // output audio to hardware
2802 while (frameCount) {
2803 buffer.frameCount = frameCount;
2804 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002805 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 memset(curBuf, 0, frameCount * mFrameSize);
2807 break;
2808 }
2809 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2810 frameCount -= buffer.frameCount;
2811 curBuf += buffer.frameCount * mFrameSize;
2812 activeTrack->releaseBuffer(&buffer);
2813 }
2814 sleepTime = 0;
2815 standbyTime = systemTime() + standbyDelay;
2816 } else {
2817 if (sleepTime == 0) {
2818 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2819 sleepTime = activeSleepTime;
2820 } else {
2821 sleepTime = idleSleepTime;
2822 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002823 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2825 sleepTime = 0;
2826 }
2827 }
2828
2829 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002830 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 }
2832 // sleepTime == 0 means we must write to audio hardware
2833 if (sleepTime == 0) {
2834 if (mixerStatus == MIXER_TRACKS_READY) {
2835 applyVolume(leftVol, rightVol, rampVolume);
2836 }
2837 for (size_t i = 0; i < effectChains.size(); i ++) {
2838 effectChains[i]->process_l();
2839 }
Eric Laurentde070132010-07-13 04:45:46 -07002840 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841
2842 mLastWriteTime = systemTime();
2843 mInWrite = true;
2844 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002845 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002846 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2847 mNumWrites++;
2848 mInWrite = false;
2849 mStandby = false;
2850 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002851 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 usleep(sleepTime);
2853 }
2854
2855 // finally let go of removed track, without the lock held
2856 // since we can't guarantee the destructors won't acquire that
2857 // same lock.
2858 trackToRemove.clear();
2859 activeTrack.clear();
2860
2861 // Effect chains will be actually deleted here if they were removed from
2862 // mEffectChains list during mixing or effects processing
2863 effectChains.clear();
2864 }
2865
2866 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002867 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868 }
2869
Eric Laurentfeb0db62011-07-22 09:04:31 -07002870 releaseWakeLock();
2871
Steve Block3856b092011-10-20 11:56:00 +01002872 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873 return false;
2874}
2875
2876// getTrackName_l() must be called with ThreadBase::mLock held
2877int AudioFlinger::DirectOutputThread::getTrackName_l()
2878{
2879 return 0;
2880}
2881
2882// deleteTrackName_l() must be called with ThreadBase::mLock held
2883void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2884{
2885}
2886
2887// checkForNewParameters_l() must be called with ThreadBase::mLock held
2888bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2889{
2890 bool reconfig = false;
2891
2892 while (!mNewParameters.isEmpty()) {
2893 status_t status = NO_ERROR;
2894 String8 keyValuePair = mNewParameters[0];
2895 AudioParameter param = AudioParameter(keyValuePair);
2896 int value;
2897
2898 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2899 // do not accept frame count changes if tracks are open as the track buffer
2900 // size depends on frame count and correct behavior would not be garantied
2901 // if frame count is changed after track creation
2902 if (!mTracks.isEmpty()) {
2903 status = INVALID_OPERATION;
2904 } else {
2905 reconfig = true;
2906 }
2907 }
2908 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002909 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002910 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002912 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913 mStandby = true;
2914 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002915 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002916 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 }
2918 if (status == NO_ERROR && reconfig) {
2919 readOutputParameters();
2920 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2921 }
2922 }
2923
2924 mNewParameters.removeAt(0);
2925
2926 mParamStatus = status;
2927 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002928 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2929 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002930 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002931 }
2932 return reconfig;
2933}
2934
2935uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2936{
2937 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002938 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002939 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 } else {
2941 time = 10000;
2942 }
2943 return time;
2944}
2945
2946uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2947{
2948 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002949 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002950 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002951 } else {
2952 time = 10000;
2953 }
2954 return time;
2955}
2956
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002957uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2958{
2959 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002960 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002961 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2962 } else {
2963 time = 10000;
2964 }
2965 return time;
2966}
2967
2968
Mathias Agopian65ab4712010-07-14 17:59:35 -07002969// ----------------------------------------------------------------------------
2970
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002971AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
2972 AudioFlinger::MixerThread* mainThread, int id)
2973 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2974 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976 addOutputTrack(mainThread);
2977}
2978
2979AudioFlinger::DuplicatingThread::~DuplicatingThread()
2980{
2981 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2982 mOutputTracks[i]->destroy();
2983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984}
2985
2986bool AudioFlinger::DuplicatingThread::threadLoop()
2987{
2988 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002989 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 nsecs_t standbyTime = systemTime();
2991 size_t mixBufferSize = mFrameCount*mFrameSize;
2992 SortedVector< sp<OutputTrack> > outputTracks;
2993 uint32_t writeFrames = 0;
2994 uint32_t activeSleepTime = activeSleepTimeUs();
2995 uint32_t idleSleepTime = idleSleepTimeUs();
2996 uint32_t sleepTime = idleSleepTime;
2997 Vector< sp<EffectChain> > effectChains;
2998
Eric Laurentfeb0db62011-07-22 09:04:31 -07002999 acquireWakeLock();
3000
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 while (!exitPending())
3002 {
3003 processConfigEvents();
3004
3005 mixerStatus = MIXER_IDLE;
3006 { // scope for the mLock
3007
3008 Mutex::Autolock _l(mLock);
3009
3010 if (checkForNewParameters_l()) {
3011 mixBufferSize = mFrameCount*mFrameSize;
3012 updateWaitTime();
3013 activeSleepTime = activeSleepTimeUs();
3014 idleSleepTime = idleSleepTimeUs();
3015 }
3016
3017 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3018
3019 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3020 outputTracks.add(mOutputTracks[i]);
3021 }
3022
3023 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003024 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3025 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 if (!mStandby) {
3027 for (size_t i = 0; i < outputTracks.size(); i++) {
3028 outputTracks[i]->stop();
3029 }
3030 mStandby = true;
3031 mBytesWritten = 0;
3032 }
3033
3034 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3035 // we're about to wait, flush the binder command buffer
3036 IPCThreadState::self()->flushCommands();
3037 outputTracks.clear();
3038
3039 if (exitPending()) break;
3040
Eric Laurentfeb0db62011-07-22 09:04:31 -07003041 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003042 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003044 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003045 acquireWakeLock_l();
3046
Eric Laurent27741442012-01-17 19:20:12 -08003047 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003048 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 char value[PROPERTY_VALUE_MAX];
3050 property_get("ro.audio.silent", value, "0");
3051 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003052 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 setMasterMute(true);
3054 }
3055 }
3056
3057 standbyTime = systemTime() + kStandbyTimeInNsecs;
3058 sleepTime = idleSleepTime;
3059 continue;
3060 }
3061 }
3062
3063 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3064
3065 // prevent any changes in effect chain list and in each effect chain
3066 // during mixing and effect process as the audio buffers could be deleted
3067 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003068 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 }
3070
Glenn Kastenf6b16782011-12-15 09:51:17 -08003071 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 // mix buffers...
3073 if (outputsReady(outputTracks)) {
3074 mAudioMixer->process();
3075 } else {
3076 memset(mMixBuffer, 0, mixBufferSize);
3077 }
3078 sleepTime = 0;
3079 writeFrames = mFrameCount;
3080 } else {
3081 if (sleepTime == 0) {
3082 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3083 sleepTime = activeSleepTime;
3084 } else {
3085 sleepTime = idleSleepTime;
3086 }
3087 } else if (mBytesWritten != 0) {
3088 // flush remaining overflow buffers in output tracks
3089 for (size_t i = 0; i < outputTracks.size(); i++) {
3090 if (outputTracks[i]->isActive()) {
3091 sleepTime = 0;
3092 writeFrames = 0;
3093 memset(mMixBuffer, 0, mixBufferSize);
3094 break;
3095 }
3096 }
3097 }
3098 }
3099
3100 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003101 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 }
3103 // sleepTime == 0 means we must write to audio hardware
3104 if (sleepTime == 0) {
3105 for (size_t i = 0; i < effectChains.size(); i ++) {
3106 effectChains[i]->process_l();
3107 }
3108 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003109 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003110
3111 standbyTime = systemTime() + kStandbyTimeInNsecs;
3112 for (size_t i = 0; i < outputTracks.size(); i++) {
3113 outputTracks[i]->write(mMixBuffer, writeFrames);
3114 }
3115 mStandby = false;
3116 mBytesWritten += mixBufferSize;
3117 } else {
3118 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003119 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 usleep(sleepTime);
3121 }
3122
3123 // finally let go of all our tracks, without the lock held
3124 // since we can't guarantee the destructors won't acquire that
3125 // same lock.
3126 tracksToRemove.clear();
3127 outputTracks.clear();
3128
3129 // Effect chains will be actually deleted here if they were removed from
3130 // mEffectChains list during mixing or effects processing
3131 effectChains.clear();
3132 }
3133
Eric Laurentfeb0db62011-07-22 09:04:31 -07003134 releaseWakeLock();
3135
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 return false;
3137}
3138
3139void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3140{
3141 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3142 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3143 this,
3144 mSampleRate,
3145 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003146 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 frameCount);
3148 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003149 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003151 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003152 updateWaitTime();
3153 }
3154}
3155
3156void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3157{
3158 Mutex::Autolock _l(mLock);
3159 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3160 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3161 mOutputTracks[i]->destroy();
3162 mOutputTracks.removeAt(i);
3163 updateWaitTime();
3164 return;
3165 }
3166 }
Steve Block3856b092011-10-20 11:56:00 +01003167 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168}
3169
3170void AudioFlinger::DuplicatingThread::updateWaitTime()
3171{
3172 mWaitTimeMs = UINT_MAX;
3173 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3174 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003175 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3177 if (waitTimeMs < mWaitTimeMs) {
3178 mWaitTimeMs = waitTimeMs;
3179 }
3180 }
3181 }
3182}
3183
3184
3185bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3186{
3187 for (size_t i = 0; i < outputTracks.size(); i++) {
3188 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3189 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003190 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 return false;
3192 }
3193 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3194 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003195 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003196 return false;
3197 }
3198 }
3199 return true;
3200}
3201
3202uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3203{
3204 return (mWaitTimeMs * 1000) / 2;
3205}
3206
3207// ----------------------------------------------------------------------------
3208
3209// TrackBase constructor must be called with AudioFlinger::mLock held
3210AudioFlinger::ThreadBase::TrackBase::TrackBase(
3211 const wp<ThreadBase>& thread,
3212 const sp<Client>& client,
3213 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003214 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003215 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 int frameCount,
3217 uint32_t flags,
3218 const sp<IMemory>& sharedBuffer,
3219 int sessionId)
3220 : RefBase(),
3221 mThread(thread),
3222 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003223 mCblk(NULL),
3224 // mBuffer
3225 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 mFrameCount(0),
3227 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 mFormat(format),
3229 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3230 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003231 // mChannelCount
3232 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233{
Steve Block3856b092011-10-20 11:56:00 +01003234 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235
Steve Blockb8a80522011-12-20 16:23:08 +00003236 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003238 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3240 if (sharedBuffer == 0) {
3241 size += bufferSize;
3242 }
3243
3244 if (client != NULL) {
3245 mCblkMemory = client->heap()->allocate(size);
3246 if (mCblkMemory != 0) {
3247 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003248 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 new(mCblk) audio_track_cblk_t();
3250 // clear all buffers
3251 mCblk->frameCount = frameCount;
3252 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003253 mChannelCount = channelCount;
3254 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 if (sharedBuffer == 0) {
3256 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3257 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3258 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003259 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 mCblk->flags = CBLK_UNDERRUN_ON;
3261 } else {
3262 mBuffer = sharedBuffer->pointer();
3263 }
3264 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3265 }
3266 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003267 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 client->heap()->dump("AudioTrack");
3269 return;
3270 }
3271 } else {
3272 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003273 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 new(mCblk) audio_track_cblk_t();
3275 // clear all buffers
3276 mCblk->frameCount = frameCount;
3277 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003278 mChannelCount = channelCount;
3279 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3281 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3282 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003283 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 mCblk->flags = CBLK_UNDERRUN_ON;
3285 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 }
3287}
3288
3289AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3290{
Glenn Kastena0d68332012-01-27 16:47:15 -08003291 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003292 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003294 } else {
3295 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 }
3297 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003298 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003299 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003300 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003302 // If the client's reference count drops to zero, the associated destructor
3303 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3304 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 mClient.clear();
3306 }
3307}
3308
3309void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3310{
Glenn Kastene0feee32011-12-13 11:53:26 -08003311 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 mFrameCount = buffer->frameCount;
3313 step();
3314 buffer->frameCount = 0;
3315}
3316
3317bool AudioFlinger::ThreadBase::TrackBase::step() {
3318 bool result;
3319 audio_track_cblk_t* cblk = this->cblk();
3320
3321 result = cblk->stepServer(mFrameCount);
3322 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003323 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003324 mFlags |= STEPSERVER_FAILED;
3325 }
3326 return result;
3327}
3328
3329void AudioFlinger::ThreadBase::TrackBase::reset() {
3330 audio_track_cblk_t* cblk = this->cblk();
3331
3332 cblk->user = 0;
3333 cblk->server = 0;
3334 cblk->userBase = 0;
3335 cblk->serverBase = 0;
3336 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003337 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338}
3339
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3341 return (int)mCblk->sampleRate;
3342}
3343
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3345 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003346 size_t frameSize = cblk->frameSize;
3347 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3348 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349
3350 // Check validity of returned pointer in case the track control block would have been corrupted.
3351 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003352 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003353 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 -07003354 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003356 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003357 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 }
3359
3360 return bufferStart;
3361}
3362
3363// ----------------------------------------------------------------------------
3364
3365// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3366AudioFlinger::PlaybackThread::Track::Track(
3367 const wp<ThreadBase>& thread,
3368 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003369 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003371 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003372 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 int frameCount,
3374 const sp<IMemory>& sharedBuffer,
3375 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003376 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003377 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3378 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379{
3380 if (mCblk != NULL) {
3381 sp<ThreadBase> baseThread = thread.promote();
3382 if (baseThread != 0) {
3383 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3384 mName = playbackThread->getTrackName_l();
3385 mMainBuffer = playbackThread->mixBuffer();
3386 }
Steve Block3856b092011-10-20 11:56:00 +01003387 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003389 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 mStreamType = streamType;
3392 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3393 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003394 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 }
3396}
3397
3398AudioFlinger::PlaybackThread::Track::~Track()
3399{
Steve Block3856b092011-10-20 11:56:00 +01003400 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 sp<ThreadBase> thread = mThread.promote();
3402 if (thread != 0) {
3403 Mutex::Autolock _l(thread->mLock);
3404 mState = TERMINATED;
3405 }
3406}
3407
3408void AudioFlinger::PlaybackThread::Track::destroy()
3409{
3410 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3411 // by removing it from mTracks vector, so there is a risk that this Tracks's
3412 // desctructor is called. As the destructor needs to lock mLock,
3413 // we must acquire a strong reference on this Track before locking mLock
3414 // here so that the destructor is called only when exiting this function.
3415 // On the other hand, as long as Track::destroy() is only called by
3416 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3417 // this Track with its member mTrack.
3418 sp<Track> keep(this);
3419 { // scope for mLock
3420 sp<ThreadBase> thread = mThread.promote();
3421 if (thread != 0) {
3422 if (!isOutputTrack()) {
3423 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003424 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003425 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003426 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003427
3428 // to track the speaker usage
3429 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 }
3431 AudioSystem::releaseOutput(thread->id());
3432 }
3433 Mutex::Autolock _l(thread->mLock);
3434 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3435 playbackThread->destroyTrack_l(this);
3436 }
3437 }
3438}
3439
3440void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3441{
Glenn Kasten83d86532012-01-17 14:39:34 -08003442 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003443 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 -07003444 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003445 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 mStreamType,
3447 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003448 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 mSessionId,
3450 mFrameCount,
3451 mState,
3452 mMute,
3453 mFillingUpStatus,
3454 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003455 vlr & 0xFFFF,
3456 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003457 mCblk->server,
3458 mCblk->user,
3459 (int)mMainBuffer,
3460 (int)mAuxBuffer);
3461}
3462
3463status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3464{
3465 audio_track_cblk_t* cblk = this->cblk();
3466 uint32_t framesReady;
3467 uint32_t framesReq = buffer->frameCount;
3468
3469 // Check if last stepServer failed, try to step now
3470 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3471 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003472 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3474 }
3475
3476 framesReady = cblk->framesReady();
3477
Glenn Kastenf6b16782011-12-15 09:51:17 -08003478 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 uint32_t s = cblk->server;
3480 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3481
3482 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3483 if (framesReq > framesReady) {
3484 framesReq = framesReady;
3485 }
3486 if (s + framesReq > bufferEnd) {
3487 framesReq = bufferEnd - s;
3488 }
3489
3490 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003491 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492
3493 buffer->frameCount = framesReq;
3494 return NO_ERROR;
3495 }
3496
3497getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003498 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003500 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 return NOT_ENOUGH_DATA;
3502}
3503
3504bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003505 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506
3507 if (mCblk->framesReady() >= mCblk->frameCount ||
3508 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3509 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003510 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 return true;
3512 }
3513 return false;
3514}
3515
3516status_t AudioFlinger::PlaybackThread::Track::start()
3517{
3518 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003519 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003520 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003521 sp<ThreadBase> thread = mThread.promote();
3522 if (thread != 0) {
3523 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003524 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 // here the track could be either new, or restarted
3526 // in both cases "unstop" the track
3527 if (mState == PAUSED) {
3528 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003529 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 } else {
3531 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003532 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 }
3534
3535 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3536 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003537 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003538 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003539 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003541
3542 // to track the speaker usage
3543 if (status == NO_ERROR) {
3544 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 }
3547 if (status == NO_ERROR) {
3548 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3549 playbackThread->addTrack_l(this);
3550 } else {
3551 mState = state;
3552 }
3553 } else {
3554 status = BAD_VALUE;
3555 }
3556 return status;
3557}
3558
3559void AudioFlinger::PlaybackThread::Track::stop()
3560{
Steve Block3856b092011-10-20 11:56:00 +01003561 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 sp<ThreadBase> thread = mThread.promote();
3563 if (thread != 0) {
3564 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003565 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 if (mState > STOPPED) {
3567 mState = STOPPED;
3568 // If the track is not active (PAUSED and buffers full), flush buffers
3569 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3570 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3571 reset();
3572 }
Steve Block3856b092011-10-20 11:56:00 +01003573 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 }
3575 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3576 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003577 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003578 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003579 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003581
3582 // to track the speaker usage
3583 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 }
3585 }
3586}
3587
3588void AudioFlinger::PlaybackThread::Track::pause()
3589{
Steve Block3856b092011-10-20 11:56:00 +01003590 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 sp<ThreadBase> thread = mThread.promote();
3592 if (thread != 0) {
3593 Mutex::Autolock _l(thread->mLock);
3594 if (mState == ACTIVE || mState == RESUMING) {
3595 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003596 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 if (!isOutputTrack()) {
3598 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003599 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003600 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003601 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003603
3604 // to track the speaker usage
3605 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606 }
3607 }
3608 }
3609}
3610
3611void AudioFlinger::PlaybackThread::Track::flush()
3612{
Steve Block3856b092011-10-20 11:56:00 +01003613 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 sp<ThreadBase> thread = mThread.promote();
3615 if (thread != 0) {
3616 Mutex::Autolock _l(thread->mLock);
3617 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3618 return;
3619 }
3620 // No point remaining in PAUSED state after a flush => go to
3621 // STOPPED state
3622 mState = STOPPED;
3623
Eric Laurent38ccae22011-03-28 18:37:07 -07003624 // do not reset the track if it is still in the process of being stopped or paused.
3625 // this will be done by prepareTracks_l() when the track is stopped.
3626 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3627 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3628 reset();
3629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 }
3631}
3632
3633void AudioFlinger::PlaybackThread::Track::reset()
3634{
3635 // Do not reset twice to avoid discarding data written just after a flush and before
3636 // the audioflinger thread detects the track is stopped.
3637 if (!mResetDone) {
3638 TrackBase::reset();
3639 // Force underrun condition to avoid false underrun callback until first data is
3640 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003641 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3642 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 mFillingUpStatus = FS_FILLING;
3644 mResetDone = true;
3645 }
3646}
3647
3648void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3649{
3650 mMute = muted;
3651}
3652
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3654{
3655 status_t status = DEAD_OBJECT;
3656 sp<ThreadBase> thread = mThread.promote();
3657 if (thread != 0) {
3658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3659 status = playbackThread->attachAuxEffect(this, EffectId);
3660 }
3661 return status;
3662}
3663
3664void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3665{
3666 mAuxEffectId = EffectId;
3667 mAuxBuffer = buffer;
3668}
3669
3670// ----------------------------------------------------------------------------
3671
3672// RecordTrack constructor must be called with AudioFlinger::mLock held
3673AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3674 const wp<ThreadBase>& thread,
3675 const sp<Client>& client,
3676 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003677 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003678 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679 int frameCount,
3680 uint32_t flags,
3681 int sessionId)
3682 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003683 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684 mOverflow(false)
3685{
3686 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003687 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003688 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003689 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003690 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003691 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692 } else {
3693 mCblk->frameSize = sizeof(int8_t);
3694 }
3695 }
3696}
3697
3698AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3699{
3700 sp<ThreadBase> thread = mThread.promote();
3701 if (thread != 0) {
3702 AudioSystem::releaseInput(thread->id());
3703 }
3704}
3705
3706status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3707{
3708 audio_track_cblk_t* cblk = this->cblk();
3709 uint32_t framesAvail;
3710 uint32_t framesReq = buffer->frameCount;
3711
3712 // Check if last stepServer failed, try to step now
3713 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3714 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003715 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3717 }
3718
3719 framesAvail = cblk->framesAvailable_l();
3720
Glenn Kastenf6b16782011-12-15 09:51:17 -08003721 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722 uint32_t s = cblk->server;
3723 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3724
3725 if (framesReq > framesAvail) {
3726 framesReq = framesAvail;
3727 }
3728 if (s + framesReq > bufferEnd) {
3729 framesReq = bufferEnd - s;
3730 }
3731
3732 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003733 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734
3735 buffer->frameCount = framesReq;
3736 return NO_ERROR;
3737 }
3738
3739getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003740 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741 buffer->frameCount = 0;
3742 return NOT_ENOUGH_DATA;
3743}
3744
3745status_t AudioFlinger::RecordThread::RecordTrack::start()
3746{
3747 sp<ThreadBase> thread = mThread.promote();
3748 if (thread != 0) {
3749 RecordThread *recordThread = (RecordThread *)thread.get();
3750 return recordThread->start(this);
3751 } else {
3752 return BAD_VALUE;
3753 }
3754}
3755
3756void AudioFlinger::RecordThread::RecordTrack::stop()
3757{
3758 sp<ThreadBase> thread = mThread.promote();
3759 if (thread != 0) {
3760 RecordThread *recordThread = (RecordThread *)thread.get();
3761 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003762 TrackBase::reset();
3763 // Force overerrun condition to avoid false overrun callback until first data is
3764 // read from buffer
3765 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767}
3768
3769void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3770{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003771 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003772 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003774 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 mSessionId,
3776 mFrameCount,
3777 mState,
3778 mCblk->sampleRate,
3779 mCblk->server,
3780 mCblk->user);
3781}
3782
3783
3784// ----------------------------------------------------------------------------
3785
3786AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3787 const wp<ThreadBase>& thread,
3788 DuplicatingThread *sourceThread,
3789 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003790 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003791 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003793 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 mActive(false), mSourceThread(sourceThread)
3795{
3796
3797 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3798 if (mCblk != NULL) {
3799 mCblk->flags |= CBLK_DIRECTION_OUT;
3800 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 mOutBuffer.frameCount = 0;
3802 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003803 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003804 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3805 mCblk, mBuffer, mCblk->buffers,
3806 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003808 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 }
3810}
3811
3812AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3813{
3814 clearBufferQueue();
3815}
3816
3817status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3818{
3819 status_t status = Track::start();
3820 if (status != NO_ERROR) {
3821 return status;
3822 }
3823
3824 mActive = true;
3825 mRetryCount = 127;
3826 return status;
3827}
3828
3829void AudioFlinger::PlaybackThread::OutputTrack::stop()
3830{
3831 Track::stop();
3832 clearBufferQueue();
3833 mOutBuffer.frameCount = 0;
3834 mActive = false;
3835}
3836
3837bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3838{
3839 Buffer *pInBuffer;
3840 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003841 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003842 bool outputBufferFull = false;
3843 inBuffer.frameCount = frames;
3844 inBuffer.i16 = data;
3845
3846 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3847
3848 if (!mActive && frames != 0) {
3849 start();
3850 sp<ThreadBase> thread = mThread.promote();
3851 if (thread != 0) {
3852 MixerThread *mixerThread = (MixerThread *)thread.get();
3853 if (mCblk->frameCount > frames){
3854 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3855 uint32_t startFrames = (mCblk->frameCount - frames);
3856 pInBuffer = new Buffer;
3857 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3858 pInBuffer->frameCount = startFrames;
3859 pInBuffer->i16 = pInBuffer->mBuffer;
3860 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3861 mBufferQueue.add(pInBuffer);
3862 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003863 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 }
3865 }
3866 }
3867 }
3868
3869 while (waitTimeLeftMs) {
3870 // First write pending buffers, then new data
3871 if (mBufferQueue.size()) {
3872 pInBuffer = mBufferQueue.itemAt(0);
3873 } else {
3874 pInBuffer = &inBuffer;
3875 }
3876
3877 if (pInBuffer->frameCount == 0) {
3878 break;
3879 }
3880
3881 if (mOutBuffer.frameCount == 0) {
3882 mOutBuffer.frameCount = pInBuffer->frameCount;
3883 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003884 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003885 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 outputBufferFull = true;
3887 break;
3888 }
3889 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3890 if (waitTimeLeftMs >= waitTimeMs) {
3891 waitTimeLeftMs -= waitTimeMs;
3892 } else {
3893 waitTimeLeftMs = 0;
3894 }
3895 }
3896
3897 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3898 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3899 mCblk->stepUser(outFrames);
3900 pInBuffer->frameCount -= outFrames;
3901 pInBuffer->i16 += outFrames * channelCount;
3902 mOutBuffer.frameCount -= outFrames;
3903 mOutBuffer.i16 += outFrames * channelCount;
3904
3905 if (pInBuffer->frameCount == 0) {
3906 if (mBufferQueue.size()) {
3907 mBufferQueue.removeAt(0);
3908 delete [] pInBuffer->mBuffer;
3909 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003910 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911 } else {
3912 break;
3913 }
3914 }
3915 }
3916
3917 // If we could not write all frames, allocate a buffer and queue it for next time.
3918 if (inBuffer.frameCount) {
3919 sp<ThreadBase> thread = mThread.promote();
3920 if (thread != 0 && !thread->standby()) {
3921 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3922 pInBuffer = new Buffer;
3923 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3924 pInBuffer->frameCount = inBuffer.frameCount;
3925 pInBuffer->i16 = pInBuffer->mBuffer;
3926 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3927 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003928 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003930 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931 }
3932 }
3933 }
3934
3935 // Calling write() with a 0 length buffer, means that no more data will be written:
3936 // If no more buffers are pending, fill output track buffer to make sure it is started
3937 // by output mixer.
3938 if (frames == 0 && mBufferQueue.size() == 0) {
3939 if (mCblk->user < mCblk->frameCount) {
3940 frames = mCblk->frameCount - mCblk->user;
3941 pInBuffer = new Buffer;
3942 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3943 pInBuffer->frameCount = frames;
3944 pInBuffer->i16 = pInBuffer->mBuffer;
3945 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3946 mBufferQueue.add(pInBuffer);
3947 } else if (mActive) {
3948 stop();
3949 }
3950 }
3951
3952 return outputBufferFull;
3953}
3954
3955status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3956{
3957 int active;
3958 status_t result;
3959 audio_track_cblk_t* cblk = mCblk;
3960 uint32_t framesReq = buffer->frameCount;
3961
Steve Block3856b092011-10-20 11:56:00 +01003962// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003963 buffer->frameCount = 0;
3964
3965 uint32_t framesAvail = cblk->framesAvailable();
3966
3967
3968 if (framesAvail == 0) {
3969 Mutex::Autolock _l(cblk->lock);
3970 goto start_loop_here;
3971 while (framesAvail == 0) {
3972 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003973 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003974 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003975 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 }
3977 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3978 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003979 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980 }
3981 // read the server count again
3982 start_loop_here:
3983 framesAvail = cblk->framesAvailable_l();
3984 }
3985 }
3986
3987// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003988// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989// }
3990
3991 if (framesReq > framesAvail) {
3992 framesReq = framesAvail;
3993 }
3994
3995 uint32_t u = cblk->user;
3996 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3997
3998 if (u + framesReq > bufferEnd) {
3999 framesReq = bufferEnd - u;
4000 }
4001
4002 buffer->frameCount = framesReq;
4003 buffer->raw = (void *)cblk->buffer(u);
4004 return NO_ERROR;
4005}
4006
4007
4008void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4009{
4010 size_t size = mBufferQueue.size();
4011 Buffer *pBuffer;
4012
4013 for (size_t i = 0; i < size; i++) {
4014 pBuffer = mBufferQueue.itemAt(i);
4015 delete [] pBuffer->mBuffer;
4016 delete pBuffer;
4017 }
4018 mBufferQueue.clear();
4019}
4020
4021// ----------------------------------------------------------------------------
4022
4023AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4024 : RefBase(),
4025 mAudioFlinger(audioFlinger),
4026 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4027 mPid(pid)
4028{
4029 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4030}
4031
4032// Client destructor must be called with AudioFlinger::mLock held
4033AudioFlinger::Client::~Client()
4034{
4035 mAudioFlinger->removeClient_l(mPid);
4036}
4037
Glenn Kasten435dbe62012-01-30 10:15:48 -08004038sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039{
4040 return mMemoryDealer;
4041}
4042
4043// ----------------------------------------------------------------------------
4044
4045AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4046 const sp<IAudioFlingerClient>& client,
4047 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004048 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004049{
4050}
4051
4052AudioFlinger::NotificationClient::~NotificationClient()
4053{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054}
4055
4056void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4057{
4058 sp<NotificationClient> keep(this);
4059 {
4060 mAudioFlinger->removeNotificationClient(mPid);
4061 }
4062}
4063
4064// ----------------------------------------------------------------------------
4065
4066AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4067 : BnAudioTrack(),
4068 mTrack(track)
4069{
4070}
4071
4072AudioFlinger::TrackHandle::~TrackHandle() {
4073 // just stop the track on deletion, associated resources
4074 // will be freed from the main thread once all pending buffers have
4075 // been played. Unless it's not in the active track list, in which
4076 // case we free everything now...
4077 mTrack->destroy();
4078}
4079
Glenn Kasten90716c52012-01-26 13:40:12 -08004080sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4081 return mTrack->getCblk();
4082}
4083
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084status_t AudioFlinger::TrackHandle::start() {
4085 return mTrack->start();
4086}
4087
4088void AudioFlinger::TrackHandle::stop() {
4089 mTrack->stop();
4090}
4091
4092void AudioFlinger::TrackHandle::flush() {
4093 mTrack->flush();
4094}
4095
4096void AudioFlinger::TrackHandle::mute(bool e) {
4097 mTrack->mute(e);
4098}
4099
4100void AudioFlinger::TrackHandle::pause() {
4101 mTrack->pause();
4102}
4103
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4105{
4106 return mTrack->attachAuxEffect(EffectId);
4107}
4108
4109status_t AudioFlinger::TrackHandle::onTransact(
4110 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4111{
4112 return BnAudioTrack::onTransact(code, data, reply, flags);
4113}
4114
4115// ----------------------------------------------------------------------------
4116
4117sp<IAudioRecord> AudioFlinger::openRecord(
4118 pid_t pid,
4119 int input,
4120 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004121 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004122 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123 int frameCount,
4124 uint32_t flags,
4125 int *sessionId,
4126 status_t *status)
4127{
4128 sp<RecordThread::RecordTrack> recordTrack;
4129 sp<RecordHandle> recordHandle;
4130 sp<Client> client;
4131 wp<Client> wclient;
4132 status_t lStatus;
4133 RecordThread *thread;
4134 size_t inFrameCount;
4135 int lSessionId;
4136
4137 // check calling permissions
4138 if (!recordingAllowed()) {
4139 lStatus = PERMISSION_DENIED;
4140 goto Exit;
4141 }
4142
4143 // add client to list
4144 { // scope for mLock
4145 Mutex::Autolock _l(mLock);
4146 thread = checkRecordThread_l(input);
4147 if (thread == NULL) {
4148 lStatus = BAD_VALUE;
4149 goto Exit;
4150 }
4151
4152 wclient = mClients.valueFor(pid);
4153 if (wclient != NULL) {
4154 client = wclient.promote();
4155 } else {
4156 client = new Client(this, pid);
4157 mClients.add(pid, client);
4158 }
4159
4160 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004161 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 lSessionId = *sessionId;
4163 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004164 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 if (sessionId != NULL) {
4166 *sessionId = lSessionId;
4167 }
4168 }
4169 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004170 recordTrack = thread->createRecordTrack_l(client,
4171 sampleRate,
4172 format,
4173 channelMask,
4174 frameCount,
4175 flags,
4176 lSessionId,
4177 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004179 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4181 // destructor is called by the TrackBase destructor with mLock held
4182 client.clear();
4183 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 goto Exit;
4185 }
4186
4187 // return to handle to client
4188 recordHandle = new RecordHandle(recordTrack);
4189 lStatus = NO_ERROR;
4190
4191Exit:
4192 if (status) {
4193 *status = lStatus;
4194 }
4195 return recordHandle;
4196}
4197
4198// ----------------------------------------------------------------------------
4199
4200AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4201 : BnAudioRecord(),
4202 mRecordTrack(recordTrack)
4203{
4204}
4205
4206AudioFlinger::RecordHandle::~RecordHandle() {
4207 stop();
4208}
4209
Glenn Kasten90716c52012-01-26 13:40:12 -08004210sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4211 return mRecordTrack->getCblk();
4212}
4213
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004215 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 return mRecordTrack->start();
4217}
4218
4219void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004220 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221 mRecordTrack->stop();
4222}
4223
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224status_t AudioFlinger::RecordHandle::onTransact(
4225 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4226{
4227 return BnAudioRecord::onTransact(code, data, reply, flags);
4228}
4229
4230// ----------------------------------------------------------------------------
4231
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004232AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4233 AudioStreamIn *input,
4234 uint32_t sampleRate,
4235 uint32_t channels,
4236 int id,
4237 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004238 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004239 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4240 // mRsmpInIndex and mInputBytes set by readInputParameters()
4241 mReqChannelCount(popcount(channels)),
4242 mReqSampleRate(sampleRate)
4243 // mBytesRead is only meaningful while active, and so is cleared in start()
4244 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004246 snprintf(mName, kNameLength, "AudioIn_%d", id);
4247
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248 readInputParameters();
4249}
4250
4251
4252AudioFlinger::RecordThread::~RecordThread()
4253{
4254 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004255 delete mResampler;
4256 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257}
4258
4259void AudioFlinger::RecordThread::onFirstRef()
4260{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004261 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262}
4263
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004264status_t AudioFlinger::RecordThread::readyToRun()
4265{
4266 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004267 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004268 return status;
4269}
4270
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271bool AudioFlinger::RecordThread::threadLoop()
4272{
4273 AudioBufferProvider::Buffer buffer;
4274 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004275 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276
Eric Laurent44d98482010-09-30 16:12:31 -07004277 nsecs_t lastWarning = 0;
4278
Eric Laurentfeb0db62011-07-22 09:04:31 -07004279 acquireWakeLock();
4280
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 // start recording
4282 while (!exitPending()) {
4283
4284 processConfigEvents();
4285
4286 { // scope for mLock
4287 Mutex::Autolock _l(mLock);
4288 checkForNewParameters_l();
4289 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4290 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004291 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 mStandby = true;
4293 }
4294
4295 if (exitPending()) break;
4296
Eric Laurentfeb0db62011-07-22 09:04:31 -07004297 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004298 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 // go to sleep
4300 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004301 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004302 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 continue;
4304 }
4305 if (mActiveTrack != 0) {
4306 if (mActiveTrack->mState == TrackBase::PAUSING) {
4307 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004308 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 mStandby = true;
4310 }
4311 mActiveTrack.clear();
4312 mStartStopCond.broadcast();
4313 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4314 if (mReqChannelCount != mActiveTrack->channelCount()) {
4315 mActiveTrack.clear();
4316 mStartStopCond.broadcast();
4317 } else if (mBytesRead != 0) {
4318 // record start succeeds only if first read from audio input
4319 // succeeds
4320 if (mBytesRead > 0) {
4321 mActiveTrack->mState = TrackBase::ACTIVE;
4322 } else {
4323 mActiveTrack.clear();
4324 }
4325 mStartStopCond.broadcast();
4326 }
4327 mStandby = false;
4328 }
4329 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004330 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 }
4332
4333 if (mActiveTrack != 0) {
4334 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4335 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004336 unlockEffectChains(effectChains);
4337 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 continue;
4339 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004340 for (size_t i = 0; i < effectChains.size(); i ++) {
4341 effectChains[i]->process_l();
4342 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004343
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004345 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004347 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 // no resampling
4349 while (framesOut) {
4350 size_t framesIn = mFrameCount - mRsmpInIndex;
4351 if (framesIn) {
4352 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4353 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4354 if (framesIn > framesOut)
4355 framesIn = framesOut;
4356 mRsmpInIndex += framesIn;
4357 framesOut -= framesIn;
4358 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004359 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 memcpy(dst, src, framesIn * mFrameSize);
4361 } else {
4362 int16_t *src16 = (int16_t *)src;
4363 int16_t *dst16 = (int16_t *)dst;
4364 if (mChannelCount == 1) {
4365 while (framesIn--) {
4366 *dst16++ = *src16;
4367 *dst16++ = *src16++;
4368 }
4369 } else {
4370 while (framesIn--) {
4371 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4372 src16 += 2;
4373 }
4374 }
4375 }
4376 }
4377 if (framesOut && mFrameCount == mRsmpInIndex) {
4378 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004379 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004380 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 framesOut = 0;
4382 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004383 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 mRsmpInIndex = 0;
4385 }
4386 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004387 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4389 // Force input into standby so that it tries to
4390 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004391 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004392 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 }
4394 mRsmpInIndex = mFrameCount;
4395 framesOut = 0;
4396 buffer.frameCount = 0;
4397 }
4398 }
4399 }
4400 } else {
4401 // resampling
4402
4403 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4404 // alter output frame count as if we were expecting stereo samples
4405 if (mChannelCount == 1 && mReqChannelCount == 1) {
4406 framesOut >>= 1;
4407 }
4408 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4409 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4410 // are 32 bit aligned which should be always true.
4411 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004412 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 // the resampler always outputs stereo samples: do post stereo to mono conversion
4414 int16_t *src = (int16_t *)mRsmpOutBuffer;
4415 int16_t *dst = buffer.i16;
4416 while (framesOut--) {
4417 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4418 src += 2;
4419 }
4420 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004421 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423
4424 }
4425 mActiveTrack->releaseBuffer(&buffer);
4426 mActiveTrack->overflow();
4427 }
4428 // client isn't retrieving buffers fast enough
4429 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004430 if (!mActiveTrack->setOverflow()) {
4431 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004432 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004433 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004434 lastWarning = now;
4435 }
4436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 // Release the processor for a while before asking for a new buffer.
4438 // This will give the application more chance to read from the buffer and
4439 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004440 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 }
4442 }
Eric Laurentec437d82011-07-26 20:54:46 -07004443 // enable changes in effect chain
4444 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004445 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446 }
4447
4448 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004449 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450 }
4451 mActiveTrack.clear();
4452
4453 mStartStopCond.broadcast();
4454
Eric Laurentfeb0db62011-07-22 09:04:31 -07004455 releaseWakeLock();
4456
Steve Block3856b092011-10-20 11:56:00 +01004457 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 return false;
4459}
4460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004461
4462sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4463 const sp<AudioFlinger::Client>& client,
4464 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004465 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004466 int channelMask,
4467 int frameCount,
4468 uint32_t flags,
4469 int sessionId,
4470 status_t *status)
4471{
4472 sp<RecordTrack> track;
4473 status_t lStatus;
4474
4475 lStatus = initCheck();
4476 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004477 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004478 goto Exit;
4479 }
4480
4481 { // scope for mLock
4482 Mutex::Autolock _l(mLock);
4483
4484 track = new RecordTrack(this, client, sampleRate,
4485 format, channelMask, frameCount, flags, sessionId);
4486
Glenn Kasten7378ca52012-01-20 13:44:40 -08004487 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004488 lStatus = NO_MEMORY;
4489 goto Exit;
4490 }
4491
4492 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004493 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4494 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004495 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004496 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4497 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004498 }
4499 lStatus = NO_ERROR;
4500
4501Exit:
4502 if (status) {
4503 *status = lStatus;
4504 }
4505 return track;
4506}
4507
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4509{
Steve Block3856b092011-10-20 11:56:00 +01004510 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 sp <ThreadBase> strongMe = this;
4512 status_t status = NO_ERROR;
4513 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004514 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 if (mActiveTrack != 0) {
4516 if (recordTrack != mActiveTrack.get()) {
4517 status = -EBUSY;
4518 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4519 mActiveTrack->mState = TrackBase::ACTIVE;
4520 }
4521 return status;
4522 }
4523
4524 recordTrack->mState = TrackBase::IDLE;
4525 mActiveTrack = recordTrack;
4526 mLock.unlock();
4527 status_t status = AudioSystem::startInput(mId);
4528 mLock.lock();
4529 if (status != NO_ERROR) {
4530 mActiveTrack.clear();
4531 return status;
4532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mRsmpInIndex = mFrameCount;
4534 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004535 if (mResampler != NULL) {
4536 mResampler->reset();
4537 }
4538 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004540 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 mWaitWorkCV.signal();
4542 // do not wait for mStartStopCond if exiting
4543 if (mExiting) {
4544 mActiveTrack.clear();
4545 status = INVALID_OPERATION;
4546 goto startError;
4547 }
4548 mStartStopCond.wait(mLock);
4549 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 status = BAD_VALUE;
4552 goto startError;
4553 }
Steve Block3856b092011-10-20 11:56:00 +01004554 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 return status;
4556 }
4557startError:
4558 AudioSystem::stopInput(mId);
4559 return status;
4560}
4561
4562void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004563 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 sp <ThreadBase> strongMe = this;
4565 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004566 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4568 mActiveTrack->mState = TrackBase::PAUSING;
4569 // do not wait for mStartStopCond if exiting
4570 if (mExiting) {
4571 return;
4572 }
4573 mStartStopCond.wait(mLock);
4574 // if we have been restarted, recordTrack == mActiveTrack.get() here
4575 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4576 mLock.unlock();
4577 AudioSystem::stopInput(mId);
4578 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004579 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 }
4581 }
4582 }
4583}
4584
4585status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4586{
4587 const size_t SIZE = 256;
4588 char buffer[SIZE];
4589 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590
4591 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4592 result.append(buffer);
4593
4594 if (mActiveTrack != 0) {
4595 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004596 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 mActiveTrack->dump(buffer, SIZE);
4598 result.append(buffer);
4599
4600 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4601 result.append(buffer);
4602 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4603 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004604 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 result.append(buffer);
4606 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4607 result.append(buffer);
4608 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4609 result.append(buffer);
4610
4611
4612 } else {
4613 result.append("No record client\n");
4614 }
4615 write(fd, result.string(), result.size());
4616
4617 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004618 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619
4620 return NO_ERROR;
4621}
4622
4623status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4624{
4625 size_t framesReq = buffer->frameCount;
4626 size_t framesReady = mFrameCount - mRsmpInIndex;
4627 int channelCount;
4628
4629 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004630 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004632 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4634 // Force input into standby so that it tries to
4635 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004636 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004637 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004639 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 buffer->frameCount = 0;
4641 return NOT_ENOUGH_DATA;
4642 }
4643 mRsmpInIndex = 0;
4644 framesReady = mFrameCount;
4645 }
4646
4647 if (framesReq > framesReady) {
4648 framesReq = framesReady;
4649 }
4650
4651 if (mChannelCount == 1 && mReqChannelCount == 2) {
4652 channelCount = 1;
4653 } else {
4654 channelCount = 2;
4655 }
4656 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4657 buffer->frameCount = framesReq;
4658 return NO_ERROR;
4659}
4660
4661void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4662{
4663 mRsmpInIndex += buffer->frameCount;
4664 buffer->frameCount = 0;
4665}
4666
4667bool AudioFlinger::RecordThread::checkForNewParameters_l()
4668{
4669 bool reconfig = false;
4670
4671 while (!mNewParameters.isEmpty()) {
4672 status_t status = NO_ERROR;
4673 String8 keyValuePair = mNewParameters[0];
4674 AudioParameter param = AudioParameter(keyValuePair);
4675 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004676 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 int reqSamplingRate = mReqSampleRate;
4678 int reqChannelCount = mReqChannelCount;
4679
4680 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4681 reqSamplingRate = value;
4682 reconfig = true;
4683 }
4684 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004685 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 reconfig = true;
4687 }
4688 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004689 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690 reconfig = true;
4691 }
4692 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4693 // do not accept frame count changes if tracks are open as the track buffer
4694 // size depends on frame count and correct behavior would not be garantied
4695 // if frame count is changed after track creation
4696 if (mActiveTrack != 0) {
4697 status = INVALID_OPERATION;
4698 } else {
4699 reconfig = true;
4700 }
4701 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004702 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4703 // forward device change to effects that have requested to be
4704 // aware of attached audio device.
4705 for (size_t i = 0; i < mEffectChains.size(); i++) {
4706 mEffectChains[i]->setDevice_l(value);
4707 }
4708 // store input device and output device but do not forward output device to audio HAL.
4709 // Note that status is ignored by the caller for output device
4710 // (see AudioFlinger::setParameters()
4711 if (value & AUDIO_DEVICE_OUT_ALL) {
4712 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4713 status = BAD_VALUE;
4714 } else {
4715 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004716 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4717 if (mTrack != NULL) {
4718 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004719 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004720 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4721 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4722 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004723 }
4724 mDevice |= (uint32_t)value;
4725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004727 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004729 mInput->stream->common.standby(&mInput->stream->common);
4730 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004731 }
4732 if (reconfig) {
4733 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004734 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004735 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004736 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4737 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004738 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739 status = NO_ERROR;
4740 }
4741 if (status == NO_ERROR) {
4742 readInputParameters();
4743 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4744 }
4745 }
4746 }
4747
4748 mNewParameters.removeAt(0);
4749
4750 mParamStatus = status;
4751 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004752 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4753 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004754 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 }
4756 return reconfig;
4757}
4758
4759String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4760{
Dima Zavinfce7a472011-04-19 22:30:36 -07004761 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004762 String8 out_s8 = String8();
4763
4764 Mutex::Autolock _l(mLock);
4765 if (initCheck() != NO_ERROR) {
4766 return out_s8;
4767 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004768
Dima Zavin799a70e2011-04-18 16:57:27 -07004769 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004770 out_s8 = String8(s);
4771 free(s);
4772 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773}
4774
4775void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4776 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004777 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004778
4779 switch (event) {
4780 case AudioSystem::INPUT_OPENED:
4781 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004782 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783 desc.samplingRate = mSampleRate;
4784 desc.format = mFormat;
4785 desc.frameCount = mFrameCount;
4786 desc.latency = 0;
4787 param2 = &desc;
4788 break;
4789
4790 case AudioSystem::INPUT_CLOSED:
4791 default:
4792 break;
4793 }
4794 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4795}
4796
4797void AudioFlinger::RecordThread::readInputParameters()
4798{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004799 delete mRsmpInBuffer;
4800 // mRsmpInBuffer is always assigned a new[] below
4801 delete mRsmpOutBuffer;
4802 mRsmpOutBuffer = NULL;
4803 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004804 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805
Dima Zavin799a70e2011-04-18 16:57:27 -07004806 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004807 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4808 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004809 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004810 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004811 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812 mFrameCount = mInputBytes / mFrameSize;
4813 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4814
4815 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4816 {
4817 int channelCount;
4818 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4819 // stereo to mono post process as the resampler always outputs stereo.
4820 if (mChannelCount == 1 && mReqChannelCount == 2) {
4821 channelCount = 1;
4822 } else {
4823 channelCount = 2;
4824 }
4825 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4826 mResampler->setSampleRate(mSampleRate);
4827 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4828 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4829
4830 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4831 if (mChannelCount == 1 && mReqChannelCount == 1) {
4832 mFrameCount >>= 1;
4833 }
4834
4835 }
4836 mRsmpInIndex = mFrameCount;
4837}
4838
4839unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4840{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004841 Mutex::Autolock _l(mLock);
4842 if (initCheck() != NO_ERROR) {
4843 return 0;
4844 }
4845
Dima Zavin799a70e2011-04-18 16:57:27 -07004846 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004847}
4848
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004849uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4850{
4851 Mutex::Autolock _l(mLock);
4852 uint32_t result = 0;
4853 if (getEffectChain_l(sessionId) != 0) {
4854 result = EFFECT_SESSION;
4855 }
4856
4857 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4858 result |= TRACK_SESSION;
4859 }
4860
4861 return result;
4862}
4863
Eric Laurent59bd0da2011-08-01 09:52:20 -07004864AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4865{
4866 Mutex::Autolock _l(mLock);
4867 return mTrack;
4868}
4869
Glenn Kastenaed850d2012-01-26 09:46:34 -08004870AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004871{
4872 Mutex::Autolock _l(mLock);
4873 return mInput;
4874}
4875
4876AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4877{
4878 Mutex::Autolock _l(mLock);
4879 AudioStreamIn *input = mInput;
4880 mInput = NULL;
4881 return input;
4882}
4883
4884// this method must always be called either with ThreadBase mLock held or inside the thread loop
4885audio_stream_t* AudioFlinger::RecordThread::stream()
4886{
4887 if (mInput == NULL) {
4888 return NULL;
4889 }
4890 return &mInput->stream->common;
4891}
4892
4893
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894// ----------------------------------------------------------------------------
4895
4896int AudioFlinger::openOutput(uint32_t *pDevices,
4897 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004898 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899 uint32_t *pChannels,
4900 uint32_t *pLatencyMs,
4901 uint32_t flags)
4902{
4903 status_t status;
4904 PlaybackThread *thread = NULL;
4905 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4906 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004907 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 uint32_t channels = pChannels ? *pChannels : 0;
4909 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004910 audio_stream_out_t *outStream;
4911 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912
Steve Block3856b092011-10-20 11:56:00 +01004913 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 pDevices ? *pDevices : 0,
4915 samplingRate,
4916 format,
4917 channels,
4918 flags);
4919
4920 if (pDevices == NULL || *pDevices == 0) {
4921 return 0;
4922 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004923
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924 Mutex::Autolock _l(mLock);
4925
Dima Zavin799a70e2011-04-18 16:57:27 -07004926 outHwDev = findSuitableHwDev_l(*pDevices);
4927 if (outHwDev == NULL)
4928 return 0;
4929
Glenn Kasten58f30212012-01-12 12:27:51 -08004930 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004931 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004932 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004933 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 samplingRate,
4935 format,
4936 channels,
4937 status);
4938
4939 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004940 if (outStream != NULL) {
4941 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004942 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004943
Dima Zavinfce7a472011-04-19 22:30:36 -07004944 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4945 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4946 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004948 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 } else {
4950 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004951 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952 }
4953 mPlaybackThreads.add(id, thread);
4954
Glenn Kastena0d68332012-01-27 16:47:15 -08004955 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4956 if (pFormat != NULL) *pFormat = format;
4957 if (pChannels != NULL) *pChannels = channels;
4958 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959
4960 // notify client processes of the new output creation
4961 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4962 return id;
4963 }
4964
4965 return 0;
4966}
4967
4968int AudioFlinger::openDuplicateOutput(int output1, int output2)
4969{
4970 Mutex::Autolock _l(mLock);
4971 MixerThread *thread1 = checkMixerThread_l(output1);
4972 MixerThread *thread2 = checkMixerThread_l(output2);
4973
4974 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004975 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 return 0;
4977 }
4978
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004979 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4981 thread->addOutputTrack(thread2);
4982 mPlaybackThreads.add(id, thread);
4983 // notify client processes of the new output creation
4984 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4985 return id;
4986}
4987
4988status_t AudioFlinger::closeOutput(int output)
4989{
4990 // keep strong reference on the playback thread so that
4991 // it is not destroyed while exit() is executed
4992 sp <PlaybackThread> thread;
4993 {
4994 Mutex::Autolock _l(mLock);
4995 thread = checkPlaybackThread_l(output);
4996 if (thread == NULL) {
4997 return BAD_VALUE;
4998 }
4999
Steve Block3856b092011-10-20 11:56:00 +01005000 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005002 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005004 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5006 dupThread->removeOutputTrack((MixerThread *)thread.get());
5007 }
5008 }
5009 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005010 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5012 mPlaybackThreads.removeItem(output);
5013 }
5014 thread->exit();
5015
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005016 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005017 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005018 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005019 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005020 out->hwDev->close_output_stream(out->hwDev, out->stream);
5021 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005022 }
5023 return NO_ERROR;
5024}
5025
5026status_t AudioFlinger::suspendOutput(int output)
5027{
5028 Mutex::Autolock _l(mLock);
5029 PlaybackThread *thread = checkPlaybackThread_l(output);
5030
5031 if (thread == NULL) {
5032 return BAD_VALUE;
5033 }
5034
Steve Block3856b092011-10-20 11:56:00 +01005035 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 thread->suspend();
5037
5038 return NO_ERROR;
5039}
5040
5041status_t AudioFlinger::restoreOutput(int output)
5042{
5043 Mutex::Autolock _l(mLock);
5044 PlaybackThread *thread = checkPlaybackThread_l(output);
5045
5046 if (thread == NULL) {
5047 return BAD_VALUE;
5048 }
5049
Steve Block3856b092011-10-20 11:56:00 +01005050 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051
5052 thread->restore();
5053
5054 return NO_ERROR;
5055}
5056
5057int AudioFlinger::openInput(uint32_t *pDevices,
5058 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005059 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005060 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005061 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062{
5063 status_t status;
5064 RecordThread *thread = NULL;
5065 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005066 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 uint32_t channels = pChannels ? *pChannels : 0;
5068 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005069 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005071 audio_stream_in_t *inStream;
5072 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073
5074 if (pDevices == NULL || *pDevices == 0) {
5075 return 0;
5076 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005077
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 Mutex::Autolock _l(mLock);
5079
Dima Zavin799a70e2011-04-18 16:57:27 -07005080 inHwDev = findSuitableHwDev_l(*pDevices);
5081 if (inHwDev == NULL)
5082 return 0;
5083
Glenn Kasten58f30212012-01-12 12:27:51 -08005084 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005085 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005086 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005087 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005088 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 samplingRate,
5091 format,
5092 channels,
5093 acoustics,
5094 status);
5095
5096 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5097 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5098 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005099 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005100 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005101 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005102 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005103 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005104 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005105 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005106 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005107 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 }
5109
Dima Zavin799a70e2011-04-18 16:57:27 -07005110 if (inStream != NULL) {
5111 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5112
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005113 int id = nextUniqueId();
5114 // Start record thread
5115 // RecorThread require both input and output device indication to forward to audio
5116 // pre processing modules
5117 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5118 thread = new RecordThread(this,
5119 input,
5120 reqSamplingRate,
5121 reqChannels,
5122 id,
5123 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005124 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005125 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005126 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5127 if (pFormat != NULL) *pFormat = format;
5128 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129
Dima Zavin799a70e2011-04-18 16:57:27 -07005130 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131
5132 // notify client processes of the new input creation
5133 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5134 return id;
5135 }
5136
5137 return 0;
5138}
5139
5140status_t AudioFlinger::closeInput(int input)
5141{
5142 // keep strong reference on the record thread so that
5143 // it is not destroyed while exit() is executed
5144 sp <RecordThread> thread;
5145 {
5146 Mutex::Autolock _l(mLock);
5147 thread = checkRecordThread_l(input);
5148 if (thread == NULL) {
5149 return BAD_VALUE;
5150 }
5151
Steve Block3856b092011-10-20 11:56:00 +01005152 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005153 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5155 mRecordThreads.removeItem(input);
5156 }
5157 thread->exit();
5158
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005159 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005160 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005161 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005162 in->hwDev->close_input_stream(in->hwDev, in->stream);
5163 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164
5165 return NO_ERROR;
5166}
5167
Glenn Kastenfff6d712012-01-12 16:38:12 -08005168status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169{
5170 Mutex::Autolock _l(mLock);
5171 MixerThread *dstThread = checkMixerThread_l(output);
5172 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005173 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 return BAD_VALUE;
5175 }
5176
Steve Block3856b092011-10-20 11:56:00 +01005177 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5179
Eric Laurent9f6530f2011-08-30 10:18:54 -07005180 dstThread->setStreamValid(stream, true);
5181
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5183 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5184 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005185 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005187 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189 }
Eric Laurentde070132010-07-13 04:45:46 -07005190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191
5192 return NO_ERROR;
5193}
5194
5195
5196int AudioFlinger::newAudioSessionId()
5197{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005198 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199}
5200
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005201void AudioFlinger::acquireAudioSessionId(int audioSession)
5202{
5203 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005204 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005205 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005206 int num = mAudioSessionRefs.size();
5207 for (int i = 0; i< num; i++) {
5208 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5209 if (ref->sessionid == audioSession && ref->pid == caller) {
5210 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005211 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005212 return;
5213 }
5214 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005215 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5216 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005217}
5218
5219void AudioFlinger::releaseAudioSessionId(int audioSession)
5220{
5221 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005222 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005223 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005224 int num = mAudioSessionRefs.size();
5225 for (int i = 0; i< num; i++) {
5226 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5227 if (ref->sessionid == audioSession && ref->pid == caller) {
5228 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005229 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005230 if (ref->cnt == 0) {
5231 mAudioSessionRefs.removeAt(i);
5232 delete ref;
5233 purgeStaleEffects_l();
5234 }
5235 return;
5236 }
5237 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005238 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005239}
5240
5241void AudioFlinger::purgeStaleEffects_l() {
5242
Steve Block3856b092011-10-20 11:56:00 +01005243 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005244
5245 Vector< sp<EffectChain> > chains;
5246
5247 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5248 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5249 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5250 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005251 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5252 chains.push(ec);
5253 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005254 }
5255 }
5256 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5257 sp<RecordThread> t = mRecordThreads.valueAt(i);
5258 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5259 sp<EffectChain> ec = t->mEffectChains[j];
5260 chains.push(ec);
5261 }
5262 }
5263
5264 for (size_t i = 0; i < chains.size(); i++) {
5265 sp<EffectChain> ec = chains[i];
5266 int sessionid = ec->sessionId();
5267 sp<ThreadBase> t = ec->mThread.promote();
5268 if (t == 0) {
5269 continue;
5270 }
5271 size_t numsessionrefs = mAudioSessionRefs.size();
5272 bool found = false;
5273 for (size_t k = 0; k < numsessionrefs; k++) {
5274 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5275 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005276 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005277 sessionid, ref->pid, ref->cnt);
5278 found = true;
5279 break;
5280 }
5281 }
5282 if (!found) {
5283 // remove all effects from the chain
5284 while (ec->mEffects.size()) {
5285 sp<EffectModule> effect = ec->mEffects[0];
5286 effect->unPin();
5287 Mutex::Autolock _l (t->mLock);
5288 t->removeEffect_l(effect);
5289 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5290 sp<EffectHandle> handle = effect->mHandles[j].promote();
5291 if (handle != 0) {
5292 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005293 if (handle->mHasControl && handle->mEnabled) {
5294 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5295 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005296 }
5297 }
5298 AudioSystem::unregisterEffect(effect->id());
5299 }
5300 }
5301 }
5302 return;
5303}
5304
Mathias Agopian65ab4712010-07-14 17:59:35 -07005305// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5306AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5307{
5308 PlaybackThread *thread = NULL;
5309 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5310 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5311 }
5312 return thread;
5313}
5314
5315// checkMixerThread_l() must be called with AudioFlinger::mLock held
5316AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5317{
5318 PlaybackThread *thread = checkPlaybackThread_l(output);
5319 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005320 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 thread = NULL;
5322 }
5323 }
5324 return (MixerThread *)thread;
5325}
5326
5327// checkRecordThread_l() must be called with AudioFlinger::mLock held
5328AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5329{
5330 RecordThread *thread = NULL;
5331 if (mRecordThreads.indexOfKey(input) >= 0) {
5332 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5333 }
5334 return thread;
5335}
5336
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005337uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005339 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340}
5341
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005342AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5343{
5344 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5345 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005346 AudioStreamOut *output = thread->getOutput();
5347 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005348 return thread;
5349 }
5350 }
5351 return NULL;
5352}
5353
5354uint32_t AudioFlinger::primaryOutputDevice_l()
5355{
5356 PlaybackThread *thread = primaryPlaybackThread_l();
5357
5358 if (thread == NULL) {
5359 return 0;
5360 }
5361
5362 return thread->device();
5363}
5364
5365
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366// ----------------------------------------------------------------------------
5367// Effect management
5368// ----------------------------------------------------------------------------
5369
5370
Glenn Kastenf587ba52012-01-26 16:25:10 -08005371status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372{
5373 Mutex::Autolock _l(mLock);
5374 return EffectQueryNumberEffects(numEffects);
5375}
5376
Glenn Kastenf587ba52012-01-26 16:25:10 -08005377status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378{
5379 Mutex::Autolock _l(mLock);
5380 return EffectQueryEffect(index, descriptor);
5381}
5382
Glenn Kasten5e92a782012-01-30 07:40:52 -08005383status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005384 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385{
5386 Mutex::Autolock _l(mLock);
5387 return EffectGetDescriptor(pUuid, descriptor);
5388}
5389
5390
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5392 effect_descriptor_t *pDesc,
5393 const sp<IEffectClient>& effectClient,
5394 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005395 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 int sessionId,
5397 status_t *status,
5398 int *id,
5399 int *enabled)
5400{
5401 status_t lStatus = NO_ERROR;
5402 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 effect_descriptor_t desc;
5404 sp<Client> client;
5405 wp<Client> wclient;
5406
Steve Block3856b092011-10-20 11:56:00 +01005407 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005408 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409
5410 if (pDesc == NULL) {
5411 lStatus = BAD_VALUE;
5412 goto Exit;
5413 }
5414
Eric Laurent84e9a102010-09-23 16:10:16 -07005415 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005416 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005417 lStatus = PERMISSION_DENIED;
5418 goto Exit;
5419 }
5420
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005423 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 lStatus = PERMISSION_DENIED;
5425 goto Exit;
5426 }
5427
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005428 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005429 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005430 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005431 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005432 lStatus = BAD_VALUE;
5433 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005434 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005435 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005436 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005437 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005438 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005439 }
5440 }
5441
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 {
5443 Mutex::Autolock _l(mLock);
5444
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445
5446 if (!EffectIsNullUuid(&pDesc->uuid)) {
5447 // if uuid is specified, request effect descriptor
5448 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5449 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005450 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 goto Exit;
5452 }
5453 } else {
5454 // if uuid is not specified, look for an available implementation
5455 // of the required type in effect factory
5456 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005457 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 lStatus = BAD_VALUE;
5459 goto Exit;
5460 }
5461 uint32_t numEffects = 0;
5462 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005463 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 bool found = false;
5465
5466 lStatus = EffectQueryNumberEffects(&numEffects);
5467 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005468 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 goto Exit;
5470 }
5471 for (uint32_t i = 0; i < numEffects; i++) {
5472 lStatus = EffectQueryEffect(i, &desc);
5473 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005474 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 continue;
5476 }
5477 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5478 // If matching type found save effect descriptor. If the session is
5479 // 0 and the effect is not auxiliary, continue enumeration in case
5480 // an auxiliary version of this effect type is available
5481 found = true;
5482 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005483 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5485 break;
5486 }
5487 }
5488 }
5489 if (!found) {
5490 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005491 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 goto Exit;
5493 }
5494 // For same effect type, chose auxiliary version over insert version if
5495 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005496 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5498 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5499 }
5500 }
5501
5502 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005503 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5505 lStatus = INVALID_OPERATION;
5506 goto Exit;
5507 }
5508
Eric Laurent59255e42011-07-27 19:49:51 -07005509 // check recording permission for visualizer
5510 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5511 !recordingAllowed()) {
5512 lStatus = PERMISSION_DENIED;
5513 goto Exit;
5514 }
5515
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 // return effect descriptor
5517 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5518
5519 // If output is not specified try to find a matching audio session ID in one of the
5520 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005521 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5522 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005523 // Note: io is never 0 when creating an effect on an input
5524 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005525 // look for the thread where the specified audio session is present
5526 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5527 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005528 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005529 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005530 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005532 if (io == 0) {
5533 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5534 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5535 io = mRecordThreads.keyAt(i);
5536 break;
5537 }
5538 }
5539 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005540 // If no output thread contains the requested session ID, default to
5541 // first output. The effect chain will be moved to the correct output
5542 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005543 if (io == 0 && mPlaybackThreads.size()) {
5544 io = mPlaybackThreads.keyAt(0);
5545 }
Steve Block3856b092011-10-20 11:56:00 +01005546 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005547 }
5548 ThreadBase *thread = checkRecordThread_l(io);
5549 if (thread == NULL) {
5550 thread = checkPlaybackThread_l(io);
5551 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005552 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005553 lStatus = BAD_VALUE;
5554 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005557
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 wclient = mClients.valueFor(pid);
5559
5560 if (wclient != NULL) {
5561 client = wclient.promote();
5562 } else {
5563 client = new Client(this, pid);
5564 mClients.add(pid, client);
5565 }
5566
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005567 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005568 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5569 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570 if (handle != 0 && id != NULL) {
5571 *id = handle->id();
5572 }
5573 }
5574
5575Exit:
5576 if(status) {
5577 *status = lStatus;
5578 }
5579 return handle;
5580}
5581
Eric Laurent59255e42011-07-27 19:49:51 -07005582status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005583{
Steve Block3856b092011-10-20 11:56:00 +01005584 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005585 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005586 Mutex::Autolock _l(mLock);
5587 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005588 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005589 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 }
Eric Laurentde070132010-07-13 04:45:46 -07005591 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5592 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005593 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005594 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
Eric Laurentde070132010-07-13 04:45:46 -07005596 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5597 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005598 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005599 return BAD_VALUE;
5600 }
5601
5602 Mutex::Autolock _dl(dstThread->mLock);
5603 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005604 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005605
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 return NO_ERROR;
5607}
5608
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005609// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005610status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005611 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005612 AudioFlinger::PlaybackThread *dstThread,
5613 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005614{
Steve Block3856b092011-10-20 11:56:00 +01005615 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005616 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005617
Eric Laurent59255e42011-07-27 19:49:51 -07005618 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005619 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005620 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005621 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005622 return INVALID_OPERATION;
5623 }
5624
Eric Laurent39e94f82010-07-28 01:32:47 -07005625 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005626 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005627 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005628 // removed.
5629 srcThread->removeEffectChain_l(chain);
5630
5631 // transfer all effects one by one so that new effect chain is created on new thread with
5632 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005633 int dstOutput = dstThread->id();
5634 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005635 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005636 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5637 while (effect != 0) {
5638 srcThread->removeEffect_l(effect);
5639 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005640 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5641 if (effect->state() == EffectModule::ACTIVE ||
5642 effect->state() == EffectModule::STOPPING) {
5643 effect->start();
5644 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005645 // if the move request is not received from audio policy manager, the effect must be
5646 // re-registered with the new strategy and output
5647 if (dstChain == 0) {
5648 dstChain = effect->chain().promote();
5649 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005650 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005651 srcThread->addEffect_l(effect);
5652 return NO_INIT;
5653 }
5654 strategy = dstChain->strategy();
5655 }
5656 if (reRegister) {
5657 AudioSystem::unregisterEffect(effect->id());
5658 AudioSystem::registerEffect(&effect->desc(),
5659 dstOutput,
5660 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005661 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005662 effect->id());
5663 }
Eric Laurentde070132010-07-13 04:45:46 -07005664 effect = chain->getEffectFromId_l(0);
5665 }
5666
5667 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668}
5669
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005670
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005672sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673 const sp<AudioFlinger::Client>& client,
5674 const sp<IEffectClient>& effectClient,
5675 int32_t priority,
5676 int sessionId,
5677 effect_descriptor_t *desc,
5678 int *enabled,
5679 status_t *status
5680 )
5681{
5682 sp<EffectModule> effect;
5683 sp<EffectHandle> handle;
5684 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005686 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687 bool effectCreated = false;
5688 bool effectRegistered = false;
5689
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005690 lStatus = initCheck();
5691 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005692 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 goto Exit;
5694 }
5695
5696 // Do not allow effects with session ID 0 on direct output or duplicating threads
5697 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005698 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005699 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005700 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 lStatus = BAD_VALUE;
5702 goto Exit;
5703 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005704 // Only Pre processor effects are allowed on input threads and only on input threads
5705 if ((mType == RECORD &&
5706 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5707 (mType != RECORD &&
5708 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005709 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005710 desc->name, desc->flags, mType);
5711 lStatus = BAD_VALUE;
5712 goto Exit;
5713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714
Steve Block3856b092011-10-20 11:56:00 +01005715 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 { // scope for mLock
5718 Mutex::Autolock _l(mLock);
5719
5720 // check for existing effect chain with the requested audio session
5721 chain = getEffectChain_l(sessionId);
5722 if (chain == 0) {
5723 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005724 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725 chain = new EffectChain(this, sessionId);
5726 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005727 chain->setStrategy(getStrategyForSession_l(sessionId));
5728 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005730 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731 }
5732
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005733 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734
5735 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005736 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005738 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 if (lStatus != NO_ERROR) {
5740 goto Exit;
5741 }
5742 effectRegistered = true;
5743 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005744 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 lStatus = effect->status();
5746 if (lStatus != NO_ERROR) {
5747 goto Exit;
5748 }
Eric Laurentcab11242010-07-15 12:50:15 -07005749 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 if (lStatus != NO_ERROR) {
5751 goto Exit;
5752 }
5753 effectCreated = true;
5754
5755 effect->setDevice(mDevice);
5756 effect->setMode(mAudioFlinger->getMode());
5757 }
5758 // create effect handle and connect it to effect module
5759 handle = new EffectHandle(effect, client, effectClient, priority);
5760 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005761 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 *enabled = (int)effect->isEnabled();
5763 }
5764 }
5765
5766Exit:
5767 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005768 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005770 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 }
5772 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005773 AudioSystem::unregisterEffect(effect->id());
5774 }
5775 if (chainCreated) {
5776 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 }
5778 handle.clear();
5779 }
5780
5781 if(status) {
5782 *status = lStatus;
5783 }
5784 return handle;
5785}
5786
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005787sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5788{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005789 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005790 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005791}
5792
Eric Laurentde070132010-07-13 04:45:46 -07005793// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5794// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005795status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005796{
5797 // check for existing effect chain with the requested audio session
5798 int sessionId = effect->sessionId();
5799 sp<EffectChain> chain = getEffectChain_l(sessionId);
5800 bool chainCreated = false;
5801
5802 if (chain == 0) {
5803 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005804 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005805 chain = new EffectChain(this, sessionId);
5806 addEffectChain_l(chain);
5807 chain->setStrategy(getStrategyForSession_l(sessionId));
5808 chainCreated = true;
5809 }
Steve Block3856b092011-10-20 11:56:00 +01005810 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005811
5812 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005813 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005814 this, effect->desc().name, chain.get());
5815 return BAD_VALUE;
5816 }
5817
5818 status_t status = chain->addEffect_l(effect);
5819 if (status != NO_ERROR) {
5820 if (chainCreated) {
5821 removeEffectChain_l(chain);
5822 }
5823 return status;
5824 }
5825
5826 effect->setDevice(mDevice);
5827 effect->setMode(mAudioFlinger->getMode());
5828 return NO_ERROR;
5829}
5830
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005831void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005832
Steve Block3856b092011-10-20 11:56:00 +01005833 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005835 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5836 detachAuxEffect_l(effect->id());
5837 }
5838
5839 sp<EffectChain> chain = effect->chain().promote();
5840 if (chain != 0) {
5841 // remove effect chain if removing last effect
5842 if (chain->removeEffect_l(effect) == 0) {
5843 removeEffectChain_l(chain);
5844 }
5845 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005846 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005847 }
5848}
5849
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005850void AudioFlinger::ThreadBase::lockEffectChains_l(
5851 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5852{
5853 effectChains = mEffectChains;
5854 for (size_t i = 0; i < mEffectChains.size(); i++) {
5855 mEffectChains[i]->lock();
5856 }
5857}
5858
5859void AudioFlinger::ThreadBase::unlockEffectChains(
5860 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5861{
5862 for (size_t i = 0; i < effectChains.size(); i++) {
5863 effectChains[i]->unlock();
5864 }
5865}
5866
5867sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5868{
5869 Mutex::Autolock _l(mLock);
5870 return getEffectChain_l(sessionId);
5871}
5872
5873sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5874{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005875 size_t size = mEffectChains.size();
5876 for (size_t i = 0; i < size; i++) {
5877 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005878 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005879 }
5880 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005881 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005882}
5883
Glenn Kastenf78aee72012-01-04 11:00:47 -08005884void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005885{
5886 Mutex::Autolock _l(mLock);
5887 size_t size = mEffectChains.size();
5888 for (size_t i = 0; i < size; i++) {
5889 mEffectChains[i]->setMode_l(mode);
5890 }
5891}
5892
5893void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005894 const wp<EffectHandle>& handle,
5895 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005896
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005898 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 // delete the effect module if removing last handle on it
5900 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005901 if (!effect->isPinned() || unpiniflast) {
5902 removeEffect_l(effect);
5903 AudioSystem::unregisterEffect(effect->id());
5904 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905 }
5906}
5907
5908status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5909{
5910 int session = chain->sessionId();
5911 int16_t *buffer = mMixBuffer;
5912 bool ownsBuffer = false;
5913
Steve Block3856b092011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 if (session > 0) {
5916 // Only one effect chain can be present in direct output thread and it uses
5917 // the mix buffer as input
5918 if (mType != DIRECT) {
5919 size_t numSamples = mFrameCount * mChannelCount;
5920 buffer = new int16_t[numSamples];
5921 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005922 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 ownsBuffer = true;
5924 }
5925
5926 // Attach all tracks with same session ID to this chain.
5927 for (size_t i = 0; i < mTracks.size(); ++i) {
5928 sp<Track> track = mTracks[i];
5929 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005930 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005932 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 }
5934 }
5935
5936 // indicate all active tracks in the chain
5937 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5938 sp<Track> track = mActiveTracks[i].promote();
5939 if (track == 0) continue;
5940 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005941 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005942 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 }
5944 }
5945 }
5946
5947 chain->setInBuffer(buffer, ownsBuffer);
5948 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005949 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005950 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005951 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5952 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005954 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5955 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005956 // Effect chain for other sessions are inserted at beginning of effect
5957 // chains list to be processed before output mix effects. Relative order between other
5958 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 size_t size = mEffectChains.size();
5960 size_t i = 0;
5961 for (i = 0; i < size; i++) {
5962 if (mEffectChains[i]->sessionId() < session) break;
5963 }
5964 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005965 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966
5967 return NO_ERROR;
5968}
5969
5970size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5971{
5972 int session = chain->sessionId();
5973
Steve Block3856b092011-10-20 11:56:00 +01005974 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975
5976 for (size_t i = 0; i < mEffectChains.size(); i++) {
5977 if (chain == mEffectChains[i]) {
5978 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005979 // detach all active tracks from the chain
5980 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5981 sp<Track> track = mActiveTracks[i].promote();
5982 if (track == 0) continue;
5983 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005984 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005985 chain.get(), session);
5986 chain->decActiveTrackCnt();
5987 }
5988 }
5989
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990 // detach all tracks with same session ID from this chain
5991 for (size_t i = 0; i < mTracks.size(); ++i) {
5992 sp<Track> track = mTracks[i];
5993 if (session == track->sessionId()) {
5994 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005995 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 }
5997 }
Eric Laurentde070132010-07-13 04:45:46 -07005998 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 }
6000 }
6001 return mEffectChains.size();
6002}
6003
Eric Laurentde070132010-07-13 04:45:46 -07006004status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6005 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006{
6007 Mutex::Autolock _l(mLock);
6008 return attachAuxEffect_l(track, EffectId);
6009}
6010
Eric Laurentde070132010-07-13 04:45:46 -07006011status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6012 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013{
6014 status_t status = NO_ERROR;
6015
6016 if (EffectId == 0) {
6017 track->setAuxBuffer(0, NULL);
6018 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006019 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6020 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 if (effect != 0) {
6022 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6023 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6024 } else {
6025 status = INVALID_OPERATION;
6026 }
6027 } else {
6028 status = BAD_VALUE;
6029 }
6030 }
6031 return status;
6032}
6033
6034void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6035{
6036 for (size_t i = 0; i < mTracks.size(); ++i) {
6037 sp<Track> track = mTracks[i];
6038 if (track->auxEffectId() == effectId) {
6039 attachAuxEffect_l(track, 0);
6040 }
6041 }
6042}
6043
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006044status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6045{
6046 // only one chain per input thread
6047 if (mEffectChains.size() != 0) {
6048 return INVALID_OPERATION;
6049 }
Steve Block3856b092011-10-20 11:56:00 +01006050 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006051
6052 chain->setInBuffer(NULL);
6053 chain->setOutBuffer(NULL);
6054
Eric Laurent59255e42011-07-27 19:49:51 -07006055 checkSuspendOnAddEffectChain_l(chain);
6056
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 mEffectChains.add(chain);
6058
6059 return NO_ERROR;
6060}
6061
6062size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6063{
Steve Block3856b092011-10-20 11:56:00 +01006064 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006065 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006066 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6067 chain.get(), mEffectChains.size(), this);
6068 if (mEffectChains.size() == 1) {
6069 mEffectChains.removeAt(0);
6070 }
6071 return 0;
6072}
6073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074// ----------------------------------------------------------------------------
6075// EffectModule implementation
6076// ----------------------------------------------------------------------------
6077
6078#undef LOG_TAG
6079#define LOG_TAG "AudioFlinger::EffectModule"
6080
6081AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6082 const wp<AudioFlinger::EffectChain>& chain,
6083 effect_descriptor_t *desc,
6084 int id,
6085 int sessionId)
6086 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006087 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088{
Steve Block3856b092011-10-20 11:56:00 +01006089 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090 int lStatus;
6091 sp<ThreadBase> thread = mThread.promote();
6092 if (thread == 0) {
6093 return;
6094 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095
6096 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6097
6098 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006099 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100
6101 if (mStatus != NO_ERROR) {
6102 return;
6103 }
6104 lStatus = init();
6105 if (lStatus < 0) {
6106 mStatus = lStatus;
6107 goto Error;
6108 }
6109
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006110 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6111 mPinned = true;
6112 }
Steve Block3856b092011-10-20 11:56:00 +01006113 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 return;
6115Error:
6116 EffectRelease(mEffectInterface);
6117 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006118 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119}
6120
6121AudioFlinger::EffectModule::~EffectModule()
6122{
Steve Block3856b092011-10-20 11:56:00 +01006123 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006125 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6126 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6127 sp<ThreadBase> thread = mThread.promote();
6128 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006129 audio_stream_t *stream = thread->stream();
6130 if (stream != NULL) {
6131 stream->remove_audio_effect(stream, mEffectInterface);
6132 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133 }
6134 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006135 // release effect engine
6136 EffectRelease(mEffectInterface);
6137 }
6138}
6139
Glenn Kasten435dbe62012-01-30 10:15:48 -08006140status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141{
6142 status_t status;
6143
6144 Mutex::Autolock _l(mLock);
6145 // First handle in mHandles has highest priority and controls the effect module
6146 int priority = handle->priority();
6147 size_t size = mHandles.size();
6148 sp<EffectHandle> h;
6149 size_t i;
6150 for (i = 0; i < size; i++) {
6151 h = mHandles[i].promote();
6152 if (h == 0) continue;
6153 if (h->priority() <= priority) break;
6154 }
6155 // if inserted in first place, move effect control from previous owner to this handle
6156 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006157 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006159 enabled = h->enabled();
6160 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 }
Eric Laurent59255e42011-07-27 19:49:51 -07006162 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 status = NO_ERROR;
6164 } else {
6165 status = ALREADY_EXISTS;
6166 }
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 mHandles.insertAt(handle, i);
6169 return status;
6170}
6171
6172size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6173{
6174 Mutex::Autolock _l(mLock);
6175 size_t size = mHandles.size();
6176 size_t i;
6177 for (i = 0; i < size; i++) {
6178 if (mHandles[i] == handle) break;
6179 }
6180 if (i == size) {
6181 return size;
6182 }
Steve Block3856b092011-10-20 11:56:00 +01006183 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006184
6185 bool enabled = false;
6186 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006187 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006188 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006189 enabled = hdl->enabled();
6190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191 mHandles.removeAt(i);
6192 size = mHandles.size();
6193 // if removed from first place, move effect control from this handle to next in line
6194 if (i == 0 && size != 0) {
6195 sp<EffectHandle> h = mHandles[0].promote();
6196 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006197 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006198 }
6199 }
6200
Eric Laurentec437d82011-07-26 20:54:46 -07006201 // Prevent calls to process() and other functions on effect interface from now on.
6202 // The effect engine will be released by the destructor when the last strong reference on
6203 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006204 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006205 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006206 }
6207
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 return size;
6209}
6210
Eric Laurent59255e42011-07-27 19:49:51 -07006211sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6212{
6213 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006214 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006215}
6216
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006217void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218{
Steve Block3856b092011-10-20 11:56:00 +01006219 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 // keep a strong reference on this EffectModule to avoid calling the
6221 // destructor before we exit
6222 sp<EffectModule> keep(this);
6223 {
6224 sp<ThreadBase> thread = mThread.promote();
6225 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006226 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 }
6228 }
6229}
6230
6231void AudioFlinger::EffectModule::updateState() {
6232 Mutex::Autolock _l(mLock);
6233
6234 switch (mState) {
6235 case RESTART:
6236 reset_l();
6237 // FALL THROUGH
6238
6239 case STARTING:
6240 // clear auxiliary effect input buffer for next accumulation
6241 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6242 memset(mConfig.inputCfg.buffer.raw,
6243 0,
6244 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6245 }
6246 start_l();
6247 mState = ACTIVE;
6248 break;
6249 case STOPPING:
6250 stop_l();
6251 mDisableWaitCnt = mMaxDisableWaitCnt;
6252 mState = STOPPED;
6253 break;
6254 case STOPPED:
6255 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6256 // turn off sequence.
6257 if (--mDisableWaitCnt == 0) {
6258 reset_l();
6259 mState = IDLE;
6260 }
6261 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006262 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006263 break;
6264 }
6265}
6266
6267void AudioFlinger::EffectModule::process()
6268{
6269 Mutex::Autolock _l(mLock);
6270
Eric Laurentec437d82011-07-26 20:54:46 -07006271 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 mConfig.inputCfg.buffer.raw == NULL ||
6273 mConfig.outputCfg.buffer.raw == NULL) {
6274 return;
6275 }
6276
Eric Laurent8f45bd72010-08-31 13:50:07 -07006277 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6279 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006280 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006282 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 }
6284
6285 // do the actual processing in the effect engine
6286 int ret = (*mEffectInterface)->process(mEffectInterface,
6287 &mConfig.inputCfg.buffer,
6288 &mConfig.outputCfg.buffer);
6289
6290 // force transition to IDLE state when engine is ready
6291 if (mState == STOPPED && ret == -ENODATA) {
6292 mDisableWaitCnt = 1;
6293 }
6294
6295 // clear auxiliary effect input buffer for next accumulation
6296 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006297 memset(mConfig.inputCfg.buffer.raw, 0,
6298 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 }
6300 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006301 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6302 // If an insert effect is idle and input buffer is different from output buffer,
6303 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006305 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006306 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6307 int16_t *in = mConfig.inputCfg.buffer.s16;
6308 int16_t *out = mConfig.outputCfg.buffer.s16;
6309 for (size_t i = 0; i < frameCnt; i++) {
6310 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 }
6313 }
6314}
6315
6316void AudioFlinger::EffectModule::reset_l()
6317{
6318 if (mEffectInterface == NULL) {
6319 return;
6320 }
6321 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6322}
6323
6324status_t AudioFlinger::EffectModule::configure()
6325{
6326 uint32_t channels;
6327 if (mEffectInterface == NULL) {
6328 return NO_INIT;
6329 }
6330
6331 sp<ThreadBase> thread = mThread.promote();
6332 if (thread == 0) {
6333 return DEAD_OBJECT;
6334 }
6335
6336 // TODO: handle configuration of effects replacing track process
6337 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006338 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006340 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 }
6342
6343 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006344 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345 } else {
6346 mConfig.inputCfg.channels = channels;
6347 }
6348 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006349 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6350 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351 mConfig.inputCfg.samplingRate = thread->sampleRate();
6352 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6353 mConfig.inputCfg.bufferProvider.cookie = NULL;
6354 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6355 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6356 mConfig.outputCfg.bufferProvider.cookie = NULL;
6357 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6358 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6359 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6360 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006361 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006362 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 // - in other sessions:
6364 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6365 // other effect: overwrites output buffer: input buffer == output buffer
6366 // Auxiliary effect:
6367 // accumulates in output buffer: input buffer != output buffer
6368 // Therefore: accumulate <=> input buffer != output buffer
6369 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6370 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6371 } else {
6372 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6373 }
6374 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6375 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6376 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6377 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6378
Steve Block3856b092011-10-20 11:56:00 +01006379 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006380 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6381
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006383 uint32_t size = sizeof(int);
6384 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006385 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006386 sizeof(effect_config_t),
6387 &mConfig,
6388 &size,
6389 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390 if (status == 0) {
6391 status = cmdStatus;
6392 }
6393
6394 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6395 (1000 * mConfig.outputCfg.buffer.frameCount);
6396
6397 return status;
6398}
6399
6400status_t AudioFlinger::EffectModule::init()
6401{
6402 Mutex::Autolock _l(mLock);
6403 if (mEffectInterface == NULL) {
6404 return NO_INIT;
6405 }
6406 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006407 uint32_t size = sizeof(status_t);
6408 status_t status = (*mEffectInterface)->command(mEffectInterface,
6409 EFFECT_CMD_INIT,
6410 0,
6411 NULL,
6412 &size,
6413 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414 if (status == 0) {
6415 status = cmdStatus;
6416 }
6417 return status;
6418}
6419
Eric Laurentec35a142011-10-05 17:42:25 -07006420status_t AudioFlinger::EffectModule::start()
6421{
6422 Mutex::Autolock _l(mLock);
6423 return start_l();
6424}
6425
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426status_t AudioFlinger::EffectModule::start_l()
6427{
6428 if (mEffectInterface == NULL) {
6429 return NO_INIT;
6430 }
6431 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006432 uint32_t size = sizeof(status_t);
6433 status_t status = (*mEffectInterface)->command(mEffectInterface,
6434 EFFECT_CMD_ENABLE,
6435 0,
6436 NULL,
6437 &size,
6438 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 if (status == 0) {
6440 status = cmdStatus;
6441 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006442 if (status == 0 &&
6443 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6444 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6445 sp<ThreadBase> thread = mThread.promote();
6446 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006447 audio_stream_t *stream = thread->stream();
6448 if (stream != NULL) {
6449 stream->add_audio_effect(stream, mEffectInterface);
6450 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006451 }
6452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 return status;
6454}
6455
Eric Laurentec437d82011-07-26 20:54:46 -07006456status_t AudioFlinger::EffectModule::stop()
6457{
6458 Mutex::Autolock _l(mLock);
6459 return stop_l();
6460}
6461
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462status_t AudioFlinger::EffectModule::stop_l()
6463{
6464 if (mEffectInterface == NULL) {
6465 return NO_INIT;
6466 }
6467 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006468 uint32_t size = sizeof(status_t);
6469 status_t status = (*mEffectInterface)->command(mEffectInterface,
6470 EFFECT_CMD_DISABLE,
6471 0,
6472 NULL,
6473 &size,
6474 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475 if (status == 0) {
6476 status = cmdStatus;
6477 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006478 if (status == 0 &&
6479 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6480 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6481 sp<ThreadBase> thread = mThread.promote();
6482 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006483 audio_stream_t *stream = thread->stream();
6484 if (stream != NULL) {
6485 stream->remove_audio_effect(stream, mEffectInterface);
6486 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006487 }
6488 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489 return status;
6490}
6491
Eric Laurent25f43952010-07-28 05:40:18 -07006492status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6493 uint32_t cmdSize,
6494 void *pCmdData,
6495 uint32_t *replySize,
6496 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497{
6498 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006499// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500
Eric Laurentec437d82011-07-26 20:54:46 -07006501 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 return NO_INIT;
6503 }
Eric Laurent25f43952010-07-28 05:40:18 -07006504 status_t status = (*mEffectInterface)->command(mEffectInterface,
6505 cmdCode,
6506 cmdSize,
6507 pCmdData,
6508 replySize,
6509 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006511 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512 for (size_t i = 1; i < mHandles.size(); i++) {
6513 sp<EffectHandle> h = mHandles[i].promote();
6514 if (h != 0) {
6515 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6516 }
6517 }
6518 }
6519 return status;
6520}
6521
6522status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6523{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006524
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006526 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527
6528 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006529 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6530 if (enabled && status != NO_ERROR) {
6531 return status;
6532 }
6533
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534 switch (mState) {
6535 // going from disabled to enabled
6536 case IDLE:
6537 mState = STARTING;
6538 break;
6539 case STOPPED:
6540 mState = RESTART;
6541 break;
6542 case STOPPING:
6543 mState = ACTIVE;
6544 break;
6545
6546 // going from enabled to disabled
6547 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006548 mState = STOPPED;
6549 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 case STARTING:
6551 mState = IDLE;
6552 break;
6553 case ACTIVE:
6554 mState = STOPPING;
6555 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006556 case DESTROYED:
6557 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 }
6559 for (size_t i = 1; i < mHandles.size(); i++) {
6560 sp<EffectHandle> h = mHandles[i].promote();
6561 if (h != 0) {
6562 h->setEnabled(enabled);
6563 }
6564 }
6565 }
6566 return NO_ERROR;
6567}
6568
Glenn Kastenc59c0042012-02-02 14:06:11 -08006569bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570{
6571 switch (mState) {
6572 case RESTART:
6573 case STARTING:
6574 case ACTIVE:
6575 return true;
6576 case IDLE:
6577 case STOPPING:
6578 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006579 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 default:
6581 return false;
6582 }
6583}
6584
Glenn Kastenc59c0042012-02-02 14:06:11 -08006585bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006586{
6587 switch (mState) {
6588 case RESTART:
6589 case ACTIVE:
6590 case STOPPING:
6591 case STOPPED:
6592 return true;
6593 case IDLE:
6594 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006595 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006596 default:
6597 return false;
6598 }
6599}
6600
Mathias Agopian65ab4712010-07-14 17:59:35 -07006601status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6602{
6603 Mutex::Autolock _l(mLock);
6604 status_t status = NO_ERROR;
6605
6606 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6607 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006608 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006609 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6610 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 status_t cmdStatus;
6612 uint32_t volume[2];
6613 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006614 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 volume[0] = *left;
6616 volume[1] = *right;
6617 if (controller) {
6618 pVolume = volume;
6619 }
Eric Laurent25f43952010-07-28 05:40:18 -07006620 status = (*mEffectInterface)->command(mEffectInterface,
6621 EFFECT_CMD_SET_VOLUME,
6622 size,
6623 volume,
6624 &size,
6625 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6627 *left = volume[0];
6628 *right = volume[1];
6629 }
6630 }
6631 return status;
6632}
6633
6634status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6635{
6636 Mutex::Autolock _l(mLock);
6637 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006638 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6639 // audio pre processing modules on RecordThread can receive both output and
6640 // input device indication in the same call
6641 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6642 if (dev) {
6643 status_t cmdStatus;
6644 uint32_t size = sizeof(status_t);
6645
6646 status = (*mEffectInterface)->command(mEffectInterface,
6647 EFFECT_CMD_SET_DEVICE,
6648 sizeof(uint32_t),
6649 &dev,
6650 &size,
6651 &cmdStatus);
6652 if (status == NO_ERROR) {
6653 status = cmdStatus;
6654 }
6655 }
6656 dev = device & AUDIO_DEVICE_IN_ALL;
6657 if (dev) {
6658 status_t cmdStatus;
6659 uint32_t size = sizeof(status_t);
6660
6661 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6662 EFFECT_CMD_SET_INPUT_DEVICE,
6663 sizeof(uint32_t),
6664 &dev,
6665 &size,
6666 &cmdStatus);
6667 if (status2 == NO_ERROR) {
6668 status2 = cmdStatus;
6669 }
6670 if (status == NO_ERROR) {
6671 status = status2;
6672 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 }
6674 }
6675 return status;
6676}
6677
Glenn Kastenf78aee72012-01-04 11:00:47 -08006678status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679{
6680 Mutex::Autolock _l(mLock);
6681 status_t status = NO_ERROR;
6682 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006684 uint32_t size = sizeof(status_t);
6685 status = (*mEffectInterface)->command(mEffectInterface,
6686 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006687 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006688 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006689 &size,
6690 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006691 if (status == NO_ERROR) {
6692 status = cmdStatus;
6693 }
6694 }
6695 return status;
6696}
6697
Eric Laurent59255e42011-07-27 19:49:51 -07006698void AudioFlinger::EffectModule::setSuspended(bool suspended)
6699{
6700 Mutex::Autolock _l(mLock);
6701 mSuspended = suspended;
6702}
Glenn Kastena3a85482012-01-04 11:01:11 -08006703
6704bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006705{
6706 Mutex::Autolock _l(mLock);
6707 return mSuspended;
6708}
6709
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6711{
6712 const size_t SIZE = 256;
6713 char buffer[SIZE];
6714 String8 result;
6715
6716 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6717 result.append(buffer);
6718
6719 bool locked = tryLock(mLock);
6720 // failed to lock - AudioFlinger is probably deadlocked
6721 if (!locked) {
6722 result.append("\t\tCould not lock Fx mutex:\n");
6723 }
6724
6725 result.append("\t\tSession Status State Engine:\n");
6726 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6727 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6728 result.append(buffer);
6729
6730 result.append("\t\tDescriptor:\n");
6731 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6732 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6733 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6734 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6735 result.append(buffer);
6736 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6737 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6738 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6739 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6740 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006741 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742 mDescriptor.apiVersion,
6743 mDescriptor.flags);
6744 result.append(buffer);
6745 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6746 mDescriptor.name);
6747 result.append(buffer);
6748 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6749 mDescriptor.implementor);
6750 result.append(buffer);
6751
6752 result.append("\t\t- Input configuration:\n");
6753 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6754 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6755 (uint32_t)mConfig.inputCfg.buffer.raw,
6756 mConfig.inputCfg.buffer.frameCount,
6757 mConfig.inputCfg.samplingRate,
6758 mConfig.inputCfg.channels,
6759 mConfig.inputCfg.format);
6760 result.append(buffer);
6761
6762 result.append("\t\t- Output configuration:\n");
6763 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6764 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6765 (uint32_t)mConfig.outputCfg.buffer.raw,
6766 mConfig.outputCfg.buffer.frameCount,
6767 mConfig.outputCfg.samplingRate,
6768 mConfig.outputCfg.channels,
6769 mConfig.outputCfg.format);
6770 result.append(buffer);
6771
6772 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6773 result.append(buffer);
6774 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6775 for (size_t i = 0; i < mHandles.size(); ++i) {
6776 sp<EffectHandle> handle = mHandles[i].promote();
6777 if (handle != 0) {
6778 handle->dump(buffer, SIZE);
6779 result.append(buffer);
6780 }
6781 }
6782
6783 result.append("\n");
6784
6785 write(fd, result.string(), result.length());
6786
6787 if (locked) {
6788 mLock.unlock();
6789 }
6790
6791 return NO_ERROR;
6792}
6793
6794// ----------------------------------------------------------------------------
6795// EffectHandle implementation
6796// ----------------------------------------------------------------------------
6797
6798#undef LOG_TAG
6799#define LOG_TAG "AudioFlinger::EffectHandle"
6800
6801AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6802 const sp<AudioFlinger::Client>& client,
6803 const sp<IEffectClient>& effectClient,
6804 int32_t priority)
6805 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006806 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006807 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808{
Steve Block3856b092011-10-20 11:56:00 +01006809 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006811 if (client == 0) {
6812 return;
6813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6815 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6816 if (mCblkMemory != 0) {
6817 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6818
Glenn Kastena0d68332012-01-27 16:47:15 -08006819 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820 new(mCblk) effect_param_cblk_t();
6821 mBuffer = (uint8_t *)mCblk + bufOffset;
6822 }
6823 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006824 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006825 return;
6826 }
6827}
6828
6829AudioFlinger::EffectHandle::~EffectHandle()
6830{
Steve Block3856b092011-10-20 11:56:00 +01006831 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006832 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006833 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834}
6835
6836status_t AudioFlinger::EffectHandle::enable()
6837{
Steve Block3856b092011-10-20 11:56:00 +01006838 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839 if (!mHasControl) return INVALID_OPERATION;
6840 if (mEffect == 0) return DEAD_OBJECT;
6841
Eric Laurentdb7c0792011-08-10 10:37:50 -07006842 if (mEnabled) {
6843 return NO_ERROR;
6844 }
6845
Eric Laurent59255e42011-07-27 19:49:51 -07006846 mEnabled = true;
6847
6848 sp<ThreadBase> thread = mEffect->thread().promote();
6849 if (thread != 0) {
6850 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6851 }
6852
6853 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6854 if (mEffect->suspended()) {
6855 return NO_ERROR;
6856 }
6857
Eric Laurentdb7c0792011-08-10 10:37:50 -07006858 status_t status = mEffect->setEnabled(true);
6859 if (status != NO_ERROR) {
6860 if (thread != 0) {
6861 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6862 }
6863 mEnabled = false;
6864 }
6865 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866}
6867
6868status_t AudioFlinger::EffectHandle::disable()
6869{
Steve Block3856b092011-10-20 11:56:00 +01006870 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006872 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873
Eric Laurentdb7c0792011-08-10 10:37:50 -07006874 if (!mEnabled) {
6875 return NO_ERROR;
6876 }
Eric Laurent59255e42011-07-27 19:49:51 -07006877 mEnabled = false;
6878
6879 if (mEffect->suspended()) {
6880 return NO_ERROR;
6881 }
6882
6883 status_t status = mEffect->setEnabled(false);
6884
6885 sp<ThreadBase> thread = mEffect->thread().promote();
6886 if (thread != 0) {
6887 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6888 }
6889
6890 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891}
6892
6893void AudioFlinger::EffectHandle::disconnect()
6894{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006895 disconnect(true);
6896}
6897
6898void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6899{
Steve Block3856b092011-10-20 11:56:00 +01006900 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901 if (mEffect == 0) {
6902 return;
6903 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006904 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006905
Eric Laurenta85a74a2011-10-19 11:44:54 -07006906 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006907 sp<ThreadBase> thread = mEffect->thread().promote();
6908 if (thread != 0) {
6909 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6910 }
Eric Laurent59255e42011-07-27 19:49:51 -07006911 }
6912
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 // release sp on module => module destructor can be called now
6914 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006916 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006917 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006918 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6919 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006920 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6922 mClient.clear();
6923 }
6924}
6925
Eric Laurent25f43952010-07-28 05:40:18 -07006926status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6927 uint32_t cmdSize,
6928 void *pCmdData,
6929 uint32_t *replySize,
6930 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931{
Steve Block3856b092011-10-20 11:56:00 +01006932// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006933// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934
6935 // only get parameter command is permitted for applications not controlling the effect
6936 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6937 return INVALID_OPERATION;
6938 }
6939 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006940 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941
6942 // handle commands that are not forwarded transparently to effect engine
6943 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6944 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6945 // no risk to block the whole media server process or mixer threads is we are stuck here
6946 Mutex::Autolock _l(mCblk->lock);
6947 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6948 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6949 mCblk->serverIndex = 0;
6950 mCblk->clientIndex = 0;
6951 return BAD_VALUE;
6952 }
6953 status_t status = NO_ERROR;
6954 while (mCblk->serverIndex < mCblk->clientIndex) {
6955 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006956 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006957 int *p = (int *)(mBuffer + mCblk->serverIndex);
6958 int size = *p++;
6959 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006960 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961 break;
6962 }
6963 effect_param_t *param = (effect_param_t *)p;
6964 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006965 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966 mCblk->serverIndex += size;
6967 continue;
6968 }
Eric Laurent25f43952010-07-28 05:40:18 -07006969 uint32_t psize = sizeof(effect_param_t) +
6970 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6971 param->vsize;
6972 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6973 psize,
6974 p,
6975 &rsize,
6976 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006977 // stop at first error encountered
6978 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006980 *(int *)pReplyData = reply;
6981 break;
6982 } else if (reply != NO_ERROR) {
6983 *(int *)pReplyData = reply;
6984 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985 }
6986 mCblk->serverIndex += size;
6987 }
6988 mCblk->serverIndex = 0;
6989 mCblk->clientIndex = 0;
6990 return status;
6991 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006992 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 return enable();
6994 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006995 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 return disable();
6997 }
6998
6999 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7000}
7001
Eric Laurent59255e42011-07-27 19:49:51 -07007002void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003{
Steve Block3856b092011-10-20 11:56:00 +01007004 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005
7006 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007007 mEnabled = enabled;
7008
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 if (signal && mEffectClient != 0) {
7010 mEffectClient->controlStatusChanged(hasControl);
7011 }
7012}
7013
Eric Laurent25f43952010-07-28 05:40:18 -07007014void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7015 uint32_t cmdSize,
7016 void *pCmdData,
7017 uint32_t replySize,
7018 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019{
7020 if (mEffectClient != 0) {
7021 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7022 }
7023}
7024
7025
7026
7027void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7028{
7029 if (mEffectClient != 0) {
7030 mEffectClient->enableStatusChanged(enabled);
7031 }
7032}
7033
7034status_t AudioFlinger::EffectHandle::onTransact(
7035 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7036{
7037 return BnEffect::onTransact(code, data, reply, flags);
7038}
7039
7040
7041void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7042{
Glenn Kastena0d68332012-01-27 16:47:15 -08007043 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007044
7045 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007046 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047 mPriority,
7048 mHasControl,
7049 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007050 mCblk ? mCblk->clientIndex : 0,
7051 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 );
7053
7054 if (locked) {
7055 mCblk->lock.unlock();
7056 }
7057}
7058
7059#undef LOG_TAG
7060#define LOG_TAG "AudioFlinger::EffectChain"
7061
7062AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7063 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007064 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007065 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7066 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067{
Dima Zavinfce7a472011-04-19 22:30:36 -07007068 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007069 sp<ThreadBase> thread = mThread.promote();
7070 if (thread == 0) {
7071 return;
7072 }
7073 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7074 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007075}
7076
7077AudioFlinger::EffectChain::~EffectChain()
7078{
7079 if (mOwnInBuffer) {
7080 delete mInBuffer;
7081 }
7082
7083}
7084
Eric Laurent59255e42011-07-27 19:49:51 -07007085// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007086sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007087{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088 size_t size = mEffects.size();
7089
7090 for (size_t i = 0; i < size; i++) {
7091 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007092 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 }
7094 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007095 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007096}
7097
Eric Laurent59255e42011-07-27 19:49:51 -07007098// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007099sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 size_t size = mEffects.size();
7102
7103 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007104 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7105 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007106 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 }
7108 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007109 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110}
7111
Eric Laurent59255e42011-07-27 19:49:51 -07007112// getEffectFromType_l() must be called with ThreadBase::mLock held
7113sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7114 const effect_uuid_t *type)
7115{
Eric Laurent59255e42011-07-27 19:49:51 -07007116 size_t size = mEffects.size();
7117
7118 for (size_t i = 0; i < size; i++) {
7119 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007120 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007121 }
7122 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007123 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007124}
7125
Mathias Agopian65ab4712010-07-14 17:59:35 -07007126// Must be called with EffectChain::mLock locked
7127void AudioFlinger::EffectChain::process_l()
7128{
Eric Laurentdac69112010-09-28 14:09:57 -07007129 sp<ThreadBase> thread = mThread.promote();
7130 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007131 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007132 return;
7133 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007134 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7135 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007136 // always process effects unless no more tracks are on the session and the effect tail
7137 // has been rendered
7138 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007139 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007140 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007141
Eric Laurent544fe9b2011-11-11 15:42:52 -08007142 if (!tracksOnSession && mTailBufferCount == 0) {
7143 doProcess = false;
7144 }
7145
7146 if (activeTrackCnt() == 0) {
7147 // if no track is active and the effect tail has not been rendered,
7148 // the input buffer must be cleared here as the mixer process will not do it
7149 if (tracksOnSession || mTailBufferCount > 0) {
7150 size_t numSamples = thread->frameCount() * thread->channelCount();
7151 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7152 if (mTailBufferCount > 0) {
7153 mTailBufferCount--;
7154 }
7155 }
7156 }
Eric Laurentdac69112010-09-28 14:09:57 -07007157 }
7158
Mathias Agopian65ab4712010-07-14 17:59:35 -07007159 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007160 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007161 for (size_t i = 0; i < size; i++) {
7162 mEffects[i]->process();
7163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164 }
7165 for (size_t i = 0; i < size; i++) {
7166 mEffects[i]->updateState();
7167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168}
7169
Eric Laurentcab11242010-07-15 12:50:15 -07007170// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007171status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172{
7173 effect_descriptor_t desc = effect->desc();
7174 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7175
7176 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007177 effect->setChain(this);
7178 sp<ThreadBase> thread = mThread.promote();
7179 if (thread == 0) {
7180 return NO_INIT;
7181 }
7182 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183
7184 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7185 // Auxiliary effects are inserted at the beginning of mEffects vector as
7186 // they are processed first and accumulated in chain input buffer
7187 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007188
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189 // the input buffer for auxiliary effect contains mono samples in
7190 // 32 bit format. This is to avoid saturation in AudoMixer
7191 // accumulation stage. Saturation is done in EffectModule::process() before
7192 // calling the process in effect engine
7193 size_t numSamples = thread->frameCount();
7194 int32_t *buffer = new int32_t[numSamples];
7195 memset(buffer, 0, numSamples * sizeof(int32_t));
7196 effect->setInBuffer((int16_t *)buffer);
7197 // auxiliary effects output samples to chain input buffer for further processing
7198 // by insert effects
7199 effect->setOutBuffer(mInBuffer);
7200 } else {
7201 // Insert effects are inserted at the end of mEffects vector as they are processed
7202 // after track and auxiliary effects.
7203 // Insert effect order as a function of indicated preference:
7204 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7205 // another effect is present
7206 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7207 // last effect claiming first position
7208 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7209 // first effect claiming last position
7210 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7211 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7212 // already present
7213
7214 int size = (int)mEffects.size();
7215 int idx_insert = size;
7216 int idx_insert_first = -1;
7217 int idx_insert_last = -1;
7218
7219 for (int i = 0; i < size; i++) {
7220 effect_descriptor_t d = mEffects[i]->desc();
7221 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7222 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7223 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7224 // check invalid effect chaining combinations
7225 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7226 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007227 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228 return INVALID_OPERATION;
7229 }
7230 // remember position of first insert effect and by default
7231 // select this as insert position for new effect
7232 if (idx_insert == size) {
7233 idx_insert = i;
7234 }
7235 // remember position of last insert effect claiming
7236 // first position
7237 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7238 idx_insert_first = i;
7239 }
7240 // remember position of first insert effect claiming
7241 // last position
7242 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7243 idx_insert_last == -1) {
7244 idx_insert_last = i;
7245 }
7246 }
7247 }
7248
7249 // modify idx_insert from first position if needed
7250 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7251 if (idx_insert_last != -1) {
7252 idx_insert = idx_insert_last;
7253 } else {
7254 idx_insert = size;
7255 }
7256 } else {
7257 if (idx_insert_first != -1) {
7258 idx_insert = idx_insert_first + 1;
7259 }
7260 }
7261
7262 // always read samples from chain input buffer
7263 effect->setInBuffer(mInBuffer);
7264
7265 // if last effect in the chain, output samples to chain
7266 // output buffer, otherwise to chain input buffer
7267 if (idx_insert == size) {
7268 if (idx_insert != 0) {
7269 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7270 mEffects[idx_insert-1]->configure();
7271 }
7272 effect->setOutBuffer(mOutBuffer);
7273 } else {
7274 effect->setOutBuffer(mInBuffer);
7275 }
7276 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277
Steve Block3856b092011-10-20 11:56:00 +01007278 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279 }
7280 effect->configure();
7281 return NO_ERROR;
7282}
7283
Eric Laurentcab11242010-07-15 12:50:15 -07007284// removeEffect_l() must be called with PlaybackThread::mLock held
7285size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286{
7287 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 int size = (int)mEffects.size();
7289 int i;
7290 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7291
7292 for (i = 0; i < size; i++) {
7293 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007294 // calling stop here will remove pre-processing effect from the audio HAL.
7295 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7296 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007297 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7298 mEffects[i]->state() == EffectModule::STOPPING) {
7299 mEffects[i]->stop();
7300 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007301 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7302 delete[] effect->inBuffer();
7303 } else {
7304 if (i == size - 1 && i != 0) {
7305 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7306 mEffects[i - 1]->configure();
7307 }
7308 }
7309 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007310 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311 break;
7312 }
7313 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314
7315 return mEffects.size();
7316}
7317
Eric Laurentcab11242010-07-15 12:50:15 -07007318// setDevice_l() must be called with PlaybackThread::mLock held
7319void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320{
7321 size_t size = mEffects.size();
7322 for (size_t i = 0; i < size; i++) {
7323 mEffects[i]->setDevice(device);
7324 }
7325}
7326
Eric Laurentcab11242010-07-15 12:50:15 -07007327// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007328void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329{
7330 size_t size = mEffects.size();
7331 for (size_t i = 0; i < size; i++) {
7332 mEffects[i]->setMode(mode);
7333 }
7334}
7335
Eric Laurentcab11242010-07-15 12:50:15 -07007336// setVolume_l() must be called with PlaybackThread::mLock held
7337bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338{
7339 uint32_t newLeft = *left;
7340 uint32_t newRight = *right;
7341 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007342 int ctrlIdx = -1;
7343 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344
Eric Laurentcab11242010-07-15 12:50:15 -07007345 // first update volume controller
7346 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007347 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007348 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7349 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007350 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007351 break;
7352 }
7353 }
7354
7355 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007356 if (hasControl) {
7357 *left = mNewLeftVolume;
7358 *right = mNewRightVolume;
7359 }
7360 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007361 }
7362
7363 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007364 mLeftVolume = newLeft;
7365 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007366
7367 // second get volume update from volume controller
7368 if (ctrlIdx >= 0) {
7369 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007370 mNewLeftVolume = newLeft;
7371 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 }
7373 // then indicate volume to all other effects in chain.
7374 // Pass altered volume to effects before volume controller
7375 // and requested volume to effects after controller
7376 uint32_t lVol = newLeft;
7377 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007378
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007380 if ((int)i == ctrlIdx) continue;
7381 // this also works for ctrlIdx == -1 when there is no volume controller
7382 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383 lVol = *left;
7384 rVol = *right;
7385 }
7386 mEffects[i]->setVolume(&lVol, &rVol, false);
7387 }
7388 *left = newLeft;
7389 *right = newRight;
7390
7391 return hasControl;
7392}
7393
Mathias Agopian65ab4712010-07-14 17:59:35 -07007394status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7395{
7396 const size_t SIZE = 256;
7397 char buffer[SIZE];
7398 String8 result;
7399
7400 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7401 result.append(buffer);
7402
7403 bool locked = tryLock(mLock);
7404 // failed to lock - AudioFlinger is probably deadlocked
7405 if (!locked) {
7406 result.append("\tCould not lock mutex:\n");
7407 }
7408
Eric Laurentcab11242010-07-15 12:50:15 -07007409 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7410 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 mEffects.size(),
7412 (uint32_t)mInBuffer,
7413 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007414 mActiveTrackCnt);
7415 result.append(buffer);
7416 write(fd, result.string(), result.size());
7417
7418 for (size_t i = 0; i < mEffects.size(); ++i) {
7419 sp<EffectModule> effect = mEffects[i];
7420 if (effect != 0) {
7421 effect->dump(fd, args);
7422 }
7423 }
7424
7425 if (locked) {
7426 mLock.unlock();
7427 }
7428
7429 return NO_ERROR;
7430}
7431
Eric Laurent59255e42011-07-27 19:49:51 -07007432// must be called with ThreadBase::mLock held
7433void AudioFlinger::EffectChain::setEffectSuspended_l(
7434 const effect_uuid_t *type, bool suspend)
7435{
7436 sp<SuspendedEffectDesc> desc;
7437 // use effect type UUID timelow as key as there is no real risk of identical
7438 // timeLow fields among effect type UUIDs.
7439 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7440 if (suspend) {
7441 if (index >= 0) {
7442 desc = mSuspendedEffects.valueAt(index);
7443 } else {
7444 desc = new SuspendedEffectDesc();
7445 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7446 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007447 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007448 }
7449 if (desc->mRefCount++ == 0) {
7450 sp<EffectModule> effect = getEffectIfEnabled(type);
7451 if (effect != 0) {
7452 desc->mEffect = effect;
7453 effect->setSuspended(true);
7454 effect->setEnabled(false);
7455 }
7456 }
7457 } else {
7458 if (index < 0) {
7459 return;
7460 }
7461 desc = mSuspendedEffects.valueAt(index);
7462 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007463 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007464 desc->mRefCount = 1;
7465 }
7466 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007467 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007468 if (desc->mEffect != 0) {
7469 sp<EffectModule> effect = desc->mEffect.promote();
7470 if (effect != 0) {
7471 effect->setSuspended(false);
7472 sp<EffectHandle> handle = effect->controlHandle();
7473 if (handle != 0) {
7474 effect->setEnabled(handle->enabled());
7475 }
7476 }
7477 desc->mEffect.clear();
7478 }
7479 mSuspendedEffects.removeItemsAt(index);
7480 }
7481 }
7482}
7483
7484// must be called with ThreadBase::mLock held
7485void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7486{
7487 sp<SuspendedEffectDesc> desc;
7488
7489 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7490 if (suspend) {
7491 if (index >= 0) {
7492 desc = mSuspendedEffects.valueAt(index);
7493 } else {
7494 desc = new SuspendedEffectDesc();
7495 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007496 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007497 }
7498 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007499 Vector< sp<EffectModule> > effects;
7500 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007501 for (size_t i = 0; i < effects.size(); i++) {
7502 setEffectSuspended_l(&effects[i]->desc().type, true);
7503 }
7504 }
7505 } else {
7506 if (index < 0) {
7507 return;
7508 }
7509 desc = mSuspendedEffects.valueAt(index);
7510 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007511 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007512 desc->mRefCount = 1;
7513 }
7514 if (--desc->mRefCount == 0) {
7515 Vector<const effect_uuid_t *> types;
7516 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7517 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7518 continue;
7519 }
7520 types.add(&mSuspendedEffects.valueAt(i)->mType);
7521 }
7522 for (size_t i = 0; i < types.size(); i++) {
7523 setEffectSuspended_l(types[i], false);
7524 }
Steve Block3856b092011-10-20 11:56:00 +01007525 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007526 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7527 }
7528 }
7529}
7530
Eric Laurent6bffdb82011-09-23 08:40:41 -07007531
7532// The volume effect is used for automated tests only
7533#ifndef OPENSL_ES_H_
7534static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7535 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7536const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7537#endif //OPENSL_ES_H_
7538
Eric Laurentdb7c0792011-08-10 10:37:50 -07007539bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7540{
7541 // auxiliary effects and visualizer are never suspended on output mix
7542 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7543 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007544 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7545 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007546 return false;
7547 }
7548 return true;
7549}
7550
Glenn Kastend0539712012-01-30 12:56:03 -08007551void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007552{
Glenn Kastend0539712012-01-30 12:56:03 -08007553 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007554 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007555 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7556 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007557 }
Eric Laurent59255e42011-07-27 19:49:51 -07007558 }
Eric Laurent59255e42011-07-27 19:49:51 -07007559}
7560
7561sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7562 const effect_uuid_t *type)
7563{
Glenn Kasten090f0192012-01-30 13:00:02 -08007564 sp<EffectModule> effect = getEffectFromType_l(type);
7565 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007566}
7567
7568void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7569 bool enabled)
7570{
7571 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7572 if (enabled) {
7573 if (index < 0) {
7574 // if the effect is not suspend check if all effects are suspended
7575 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7576 if (index < 0) {
7577 return;
7578 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007579 if (!isEffectEligibleForSuspend(effect->desc())) {
7580 return;
7581 }
Eric Laurent59255e42011-07-27 19:49:51 -07007582 setEffectSuspended_l(&effect->desc().type, enabled);
7583 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007584 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007585 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007586 return;
7587 }
Eric Laurent59255e42011-07-27 19:49:51 -07007588 }
Steve Block3856b092011-10-20 11:56:00 +01007589 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007590 effect->desc().type.timeLow);
7591 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7592 // if effect is requested to suspended but was not yet enabled, supend it now.
7593 if (desc->mEffect == 0) {
7594 desc->mEffect = effect;
7595 effect->setEnabled(false);
7596 effect->setSuspended(true);
7597 }
7598 } else {
7599 if (index < 0) {
7600 return;
7601 }
Steve Block3856b092011-10-20 11:56:00 +01007602 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007603 effect->desc().type.timeLow);
7604 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7605 desc->mEffect.clear();
7606 effect->setSuspended(false);
7607 }
7608}
7609
Mathias Agopian65ab4712010-07-14 17:59:35 -07007610#undef LOG_TAG
7611#define LOG_TAG "AudioFlinger"
7612
7613// ----------------------------------------------------------------------------
7614
7615status_t AudioFlinger::onTransact(
7616 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7617{
7618 return BnAudioFlinger::onTransact(code, data, reply, flags);
7619}
7620
Mathias Agopian65ab4712010-07-14 17:59:35 -07007621}; // namespace android