blob: a5894b6d4f347488abe5483ca0f8b8abc7d0204e [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Dima Zavin799a70e2011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261
262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800270 sp<Client> client = mClients.valueAt(i).promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274 }
275 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700276
277 result.append("Global session refs:\n");
278 result.append(" session pid cnt\n");
279 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
280 AudioSessionRef *r = mAudioSessionRefs[i];
281 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
282 result.append(buffer);
283 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700284 write(fd, result.string(), result.size());
285 return NO_ERROR;
286}
287
288
289status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
290{
291 const size_t SIZE = 256;
292 char buffer[SIZE];
293 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800294 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700295
296 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
297 result.append(buffer);
298 write(fd, result.string(), result.size());
299 return NO_ERROR;
300}
301
302status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307 snprintf(buffer, SIZE, "Permission Denial: "
308 "can't dump AudioFlinger from pid=%d, uid=%d\n",
309 IPCThreadState::self()->getCallingPid(),
310 IPCThreadState::self()->getCallingUid());
311 result.append(buffer);
312 write(fd, result.string(), result.size());
313 return NO_ERROR;
314}
315
316static bool tryLock(Mutex& mutex)
317{
318 bool locked = false;
319 for (int i = 0; i < kDumpLockRetries; ++i) {
320 if (mutex.tryLock() == NO_ERROR) {
321 locked = true;
322 break;
323 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800324 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 return locked;
327}
328
329status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
330{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800331 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332 dumpPermissionDenial(fd, args);
333 } else {
334 // get state of hardware lock
335 bool hardwareLocked = tryLock(mHardwareLock);
336 if (!hardwareLocked) {
337 String8 result(kHardwareLockedString);
338 write(fd, result.string(), result.size());
339 } else {
340 mHardwareLock.unlock();
341 }
342
343 bool locked = tryLock(mLock);
344
345 // failed to lock - AudioFlinger is probably deadlocked
346 if (!locked) {
347 String8 result(kDeadlockedString);
348 write(fd, result.string(), result.size());
349 }
350
351 dumpClients(fd, args);
352 dumpInternals(fd, args);
353
354 // dump playback threads
355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
356 mPlaybackThreads.valueAt(i)->dump(fd, args);
357 }
358
359 // dump record threads
360 for (size_t i = 0; i < mRecordThreads.size(); i++) {
361 mRecordThreads.valueAt(i)->dump(fd, args);
362 }
363
Dima Zavin799a70e2011-04-18 16:57:27 -0700364 // dump all hardware devs
365 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
366 audio_hw_device_t *dev = mAudioHwDevs[i];
367 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368 }
369 if (locked) mLock.unlock();
370 }
371 return NO_ERROR;
372}
373
374
375// IAudioFlinger interface
376
377
378sp<IAudioTrack> AudioFlinger::createTrack(
379 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800380 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700381 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800382 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700383 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384 int frameCount,
385 uint32_t flags,
386 const sp<IMemory>& sharedBuffer,
387 int output,
388 int *sessionId,
389 status_t *status)
390{
391 sp<PlaybackThread::Track> track;
392 sp<TrackHandle> trackHandle;
393 sp<Client> client;
394 wp<Client> wclient;
395 status_t lStatus;
396 int lSessionId;
397
Glenn Kasten263709e2012-01-06 08:40:01 -0800398 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
399 // but if someone uses binder directly they could bypass that and cause us to crash
400 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000401 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 lStatus = BAD_VALUE;
403 goto Exit;
404 }
405
406 {
407 Mutex::Autolock _l(mLock);
408 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700409 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000411 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 lStatus = BAD_VALUE;
413 goto Exit;
414 }
415
416 wclient = mClients.valueFor(pid);
417
418 if (wclient != NULL) {
419 client = wclient.promote();
420 } else {
421 client = new Client(this, pid);
422 mClients.add(pid, client);
423 }
424
Steve Block3856b092011-10-20 11:56:00 +0100425 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700426 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700427 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700428 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
429 if (mPlaybackThreads.keyAt(i) != output) {
430 // prevent same audio session on different output threads
431 uint32_t sessions = t->hasAudioSession(*sessionId);
432 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000433 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700434 lStatus = BAD_VALUE;
435 goto Exit;
436 }
437 // check if an effect with same session ID is waiting for a track to be created
438 if (sessions & PlaybackThread::EFFECT_SESSION) {
439 effectThread = t.get();
440 }
Eric Laurentde070132010-07-13 04:45:46 -0700441 }
442 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 lSessionId = *sessionId;
444 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700445 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700446 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 if (sessionId != NULL) {
448 *sessionId = lSessionId;
449 }
450 }
Steve Block3856b092011-10-20 11:56:00 +0100451 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452
453 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700454 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700455
456 // move effect chain to this output thread if an effect on same session was waiting
457 // for a track to be created
458 if (lStatus == NO_ERROR && effectThread != NULL) {
459 Mutex::Autolock _dl(thread->mLock);
460 Mutex::Autolock _sl(effectThread->mLock);
461 moveEffectChain_l(lSessionId, effectThread, thread, true);
462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 }
464 if (lStatus == NO_ERROR) {
465 trackHandle = new TrackHandle(track);
466 } else {
467 // remove local strong reference to Client before deleting the Track so that the Client
468 // destructor is called by the TrackBase destructor with mLock held
469 client.clear();
470 track.clear();
471 }
472
473Exit:
474 if(status) {
475 *status = lStatus;
476 }
477 return trackHandle;
478}
479
480uint32_t AudioFlinger::sampleRate(int output) const
481{
482 Mutex::Autolock _l(mLock);
483 PlaybackThread *thread = checkPlaybackThread_l(output);
484 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000485 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486 return 0;
487 }
488 return thread->sampleRate();
489}
490
491int AudioFlinger::channelCount(int output) const
492{
493 Mutex::Autolock _l(mLock);
494 PlaybackThread *thread = checkPlaybackThread_l(output);
495 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000496 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 return 0;
498 }
499 return thread->channelCount();
500}
501
Glenn Kasten58f30212012-01-12 12:27:51 -0800502audio_format_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503{
504 Mutex::Autolock _l(mLock);
505 PlaybackThread *thread = checkPlaybackThread_l(output);
506 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000507 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800508 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509 }
510 return thread->format();
511}
512
513size_t AudioFlinger::frameCount(int output) const
514{
515 Mutex::Autolock _l(mLock);
516 PlaybackThread *thread = checkPlaybackThread_l(output);
517 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000518 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 return 0;
520 }
521 return thread->frameCount();
522}
523
524uint32_t AudioFlinger::latency(int output) const
525{
526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000529 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 return 0;
531 }
532 return thread->latency();
533}
534
535status_t AudioFlinger::setMasterVolume(float value)
536{
Eric Laurenta1884f92011-08-23 08:25:03 -0700537 status_t ret = initCheck();
538 if (ret != NO_ERROR) {
539 return ret;
540 }
541
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 // check calling permissions
543 if (!settingsAllowed()) {
544 return PERMISSION_DENIED;
545 }
546
547 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800548 { // scope for the lock
549 AutoMutex lock(mHardwareLock);
550 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700551 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800552 value = 1.0f;
553 }
554 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556
Eric Laurent93575202011-01-18 18:39:02 -0800557 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 mMasterVolume = value;
559 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
560 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
561
562 return NO_ERROR;
563}
564
Glenn Kastenf78aee72012-01-04 11:00:47 -0800565status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566{
Eric Laurenta1884f92011-08-23 08:25:03 -0700567 status_t ret = initCheck();
568 if (ret != NO_ERROR) {
569 return ret;
570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571
572 // check calling permissions
573 if (!settingsAllowed()) {
574 return PERMISSION_DENIED;
575 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800576 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return BAD_VALUE;
579 }
580
581 { // scope for the lock
582 AutoMutex lock(mHardwareLock);
583 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700584 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 mHardwareStatus = AUDIO_HW_IDLE;
586 }
587
588 if (NO_ERROR == ret) {
589 Mutex::Autolock _l(mLock);
590 mMode = mode;
591 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
592 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 }
594
595 return ret;
596}
597
598status_t AudioFlinger::setMicMute(bool state)
599{
Eric Laurenta1884f92011-08-23 08:25:03 -0700600 status_t ret = initCheck();
601 if (ret != NO_ERROR) {
602 return ret;
603 }
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 // check calling permissions
606 if (!settingsAllowed()) {
607 return PERMISSION_DENIED;
608 }
609
610 AutoMutex lock(mHardwareLock);
611 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700612 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 mHardwareStatus = AUDIO_HW_IDLE;
614 return ret;
615}
616
617bool AudioFlinger::getMicMute() const
618{
Eric Laurenta1884f92011-08-23 08:25:03 -0700619 status_t ret = initCheck();
620 if (ret != NO_ERROR) {
621 return false;
622 }
623
Dima Zavinfce7a472011-04-19 22:30:36 -0700624 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700626 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 mHardwareStatus = AUDIO_HW_IDLE;
628 return state;
629}
630
631status_t AudioFlinger::setMasterMute(bool muted)
632{
633 // check calling permissions
634 if (!settingsAllowed()) {
635 return PERMISSION_DENIED;
636 }
637
Eric Laurent93575202011-01-18 18:39:02 -0800638 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639 mMasterMute = muted;
640 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
641 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
642
643 return NO_ERROR;
644}
645
646float AudioFlinger::masterVolume() const
647{
Glenn Kasten98067102011-12-13 11:47:54 -0800648 Mutex::Autolock _l(mLock);
649 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650}
651
652bool AudioFlinger::masterMute() const
653{
Glenn Kasten98067102011-12-13 11:47:54 -0800654 Mutex::Autolock _l(mLock);
655 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656}
657
Glenn Kastenfff6d712012-01-12 16:38:12 -0800658status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659{
660 // check calling permissions
661 if (!settingsAllowed()) {
662 return PERMISSION_DENIED;
663 }
664
Glenn Kasten263709e2012-01-06 08:40:01 -0800665 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000666 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 return BAD_VALUE;
668 }
669
670 AutoMutex lock(mLock);
671 PlaybackThread *thread = NULL;
672 if (output) {
673 thread = checkPlaybackThread_l(output);
674 if (thread == NULL) {
675 return BAD_VALUE;
676 }
677 }
678
679 mStreamTypes[stream].volume = value;
680
681 if (thread == NULL) {
682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
683 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
684 }
685 } else {
686 thread->setStreamVolume(stream, value);
687 }
688
689 return NO_ERROR;
690}
691
Glenn Kastenfff6d712012-01-12 16:38:12 -0800692status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Glenn Kasten263709e2012-01-06 08:40:01 -0800699 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000701 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return BAD_VALUE;
703 }
704
Eric Laurent93575202011-01-18 18:39:02 -0800705 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 mStreamTypes[stream].mute = muted;
707 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
708 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
709
710 return NO_ERROR;
711}
712
Glenn Kastenfff6d712012-01-12 16:38:12 -0800713float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714{
Glenn Kasten263709e2012-01-06 08:40:01 -0800715 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 return 0.0f;
717 }
718
719 AutoMutex lock(mLock);
720 float volume;
721 if (output) {
722 PlaybackThread *thread = checkPlaybackThread_l(output);
723 if (thread == NULL) {
724 return 0.0f;
725 }
726 volume = thread->streamVolume(stream);
727 } else {
728 volume = mStreamTypes[stream].volume;
729 }
730
731 return volume;
732}
733
Glenn Kastenfff6d712012-01-12 16:38:12 -0800734bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735{
Glenn Kasten263709e2012-01-06 08:40:01 -0800736 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 return true;
738 }
739
740 return mStreamTypes[stream].mute;
741}
742
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
744{
745 status_t result;
746
Steve Block3856b092011-10-20 11:56:00 +0100747 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
752 }
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 // ioHandle == 0 means the parameters are global to the audio hardware interface
755 if (ioHandle == 0) {
756 AutoMutex lock(mHardwareLock);
757 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700758 status_t final_result = NO_ERROR;
759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 result = dev->set_parameters(dev, keyValuePairs.string());
762 final_result = result ?: final_result;
763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
766 AudioParameter param = AudioParameter(keyValuePairs);
767 String8 value;
768 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
769 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700770 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
771 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 sp<RecordThread> thread = mRecordThreads.valueAt(i);
774 RecordThread::RecordTrack *track = thread->track();
775 if (track != NULL) {
776 audio_devices_t device = (audio_devices_t)(
777 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700778 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700779 thread->setEffectSuspended(FX_IID_AEC,
780 suspend,
781 track->sessionId());
782 thread->setEffectSuspended(FX_IID_NS,
783 suspend,
784 track->sessionId());
785 }
786 }
Eric Laurentbee53372011-08-29 12:42:48 -0700787 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700788 }
789 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700790 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 }
792
793 // hold a strong ref on thread in case closeOutput() or closeInput() is called
794 // and the thread is exited once the lock is released
795 sp<ThreadBase> thread;
796 {
797 Mutex::Autolock _l(mLock);
798 thread = checkPlaybackThread_l(ioHandle);
799 if (thread == NULL) {
800 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800801 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700802 // indicate output device change to all input threads for pre processing
803 AudioParameter param = AudioParameter(keyValuePairs);
804 int value;
805 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
807 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
808 }
809 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811 }
812 if (thread != NULL) {
813 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return result;
815 }
816 return BAD_VALUE;
817}
818
819String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
820{
Steve Block3856b092011-10-20 11:56:00 +0100821// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
823
824 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700825 String8 out_s8;
826
Dima Zavin799a70e2011-04-18 16:57:27 -0700827 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
828 audio_hw_device_t *dev = mAudioHwDevs[i];
829 char *s = dev->get_parameters(dev, keys.string());
830 out_s8 += String8(s);
831 free(s);
832 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700833 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 }
835
836 Mutex::Autolock _l(mLock);
837
838 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
839 if (playbackThread != NULL) {
840 return playbackThread->getParameters(keys);
841 }
842 RecordThread *recordThread = checkRecordThread_l(ioHandle);
843 if (recordThread != NULL) {
844 return recordThread->getParameters(keys);
845 }
846 return String8("");
847}
848
Glenn Kasten58f30212012-01-12 12:27:51 -0800849size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850{
Eric Laurenta1884f92011-08-23 08:25:03 -0700851 status_t ret = initCheck();
852 if (ret != NO_ERROR) {
853 return 0;
854 }
855
Dima Zavin799a70e2011-04-18 16:57:27 -0700856 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857}
858
859unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
860{
861 if (ioHandle == 0) {
862 return 0;
863 }
864
865 Mutex::Autolock _l(mLock);
866
867 RecordThread *recordThread = checkRecordThread_l(ioHandle);
868 if (recordThread != NULL) {
869 return recordThread->getInputFramesLost();
870 }
871 return 0;
872}
873
874status_t AudioFlinger::setVoiceVolume(float value)
875{
Eric Laurenta1884f92011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
886 AutoMutex lock(mHardwareLock);
887 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700888 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 mHardwareStatus = AUDIO_HW_IDLE;
890
891 return ret;
892}
893
894status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
895{
896 status_t status;
897
898 Mutex::Autolock _l(mLock);
899
900 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
901 if (playbackThread != NULL) {
902 return playbackThread->getRenderPosition(halFrames, dspFrames);
903 }
904
905 return BAD_VALUE;
906}
907
908void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
909{
910
911 Mutex::Autolock _l(mLock);
912
913 int pid = IPCThreadState::self()->getCallingPid();
914 if (mNotificationClients.indexOfKey(pid) < 0) {
915 sp<NotificationClient> notificationClient = new NotificationClient(this,
916 client,
917 pid);
Steve Block3856b092011-10-20 11:56:00 +0100918 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919
920 mNotificationClients.add(pid, notificationClient);
921
922 sp<IBinder> binder = client->asBinder();
923 binder->linkToDeath(notificationClient);
924
925 // the config change is always sent from playback or record threads to avoid deadlock
926 // with AudioSystem::gLock
927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
929 }
930
931 for (size_t i = 0; i < mRecordThreads.size(); i++) {
932 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
933 }
934 }
935}
936
937void AudioFlinger::removeNotificationClient(pid_t pid)
938{
939 Mutex::Autolock _l(mLock);
940
941 int index = mNotificationClients.indexOfKey(pid);
942 if (index >= 0) {
943 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100944 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 mNotificationClients.removeItem(pid);
946 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700947
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700949 int num = mAudioSessionRefs.size();
950 bool removed = false;
951 for (int i = 0; i< num; i++) {
952 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100955 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700956 mAudioSessionRefs.removeAt(i);
957 delete ref;
958 removed = true;
959 i--;
960 num--;
961 }
962 }
963 if (removed) {
964 purgeStaleEffects_l();
965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966}
967
968// audioConfigChanged_l() must be called with AudioFlinger::mLock held
969void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
970{
971 size_t size = mNotificationClients.size();
972 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800973 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
974 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 }
976}
977
978// removeClient_l() must be called with AudioFlinger::mLock held
979void AudioFlinger::removeClient_l(pid_t pid)
980{
Steve Block3856b092011-10-20 11:56:00 +0100981 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 mClients.removeItem(pid);
983}
984
985
986// ----------------------------------------------------------------------------
987
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
989 type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800991 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800992 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
993 // mChannelMask
994 mChannelCount(0),
995 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
996 mParamStatus(NO_ERROR),
997 mStandby(false), mId(id), mExiting(false),
998 mDevice(device),
999 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000{
1001}
1002
1003AudioFlinger::ThreadBase::~ThreadBase()
1004{
1005 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001006 // do not lock the mutex in destructor
1007 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001008 if (mPowerManager != 0) {
1009 sp<IBinder> binder = mPowerManager->asBinder();
1010 binder->unlinkToDeath(mDeathRecipient);
1011 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012}
1013
1014void AudioFlinger::ThreadBase::exit()
1015{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001016 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 // destroyed in the middle of requestExitAndWait()
1018 sp <ThreadBase> strongMe = this;
1019
Steve Block3856b092011-10-20 11:56:00 +01001020 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001022 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 mExiting = true;
1024 requestExit();
1025 mWaitWorkCV.signal();
1026 }
1027 requestExitAndWait();
1028}
1029
1030uint32_t AudioFlinger::ThreadBase::sampleRate() const
1031{
1032 return mSampleRate;
1033}
1034
1035int AudioFlinger::ThreadBase::channelCount() const
1036{
1037 return (int)mChannelCount;
1038}
1039
Glenn Kasten58f30212012-01-12 12:27:51 -08001040audio_format_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001041{
1042 return mFormat;
1043}
1044
1045size_t AudioFlinger::ThreadBase::frameCount() const
1046{
1047 return mFrameCount;
1048}
1049
1050status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1051{
1052 status_t status;
1053
Steve Block3856b092011-10-20 11:56:00 +01001054 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055 Mutex::Autolock _l(mLock);
1056
1057 mNewParameters.add(keyValuePairs);
1058 mWaitWorkCV.signal();
1059 // wait condition with timeout in case the thread loop has exited
1060 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001061 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 status = mParamStatus;
1063 mWaitWorkCV.signal();
1064 } else {
1065 status = TIMED_OUT;
1066 }
1067 return status;
1068}
1069
1070void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1071{
1072 Mutex::Autolock _l(mLock);
1073 sendConfigEvent_l(event, param);
1074}
1075
1076// sendConfigEvent_l() must be called with ThreadBase::mLock held
1077void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1078{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001079 ConfigEvent configEvent;
1080 configEvent.mEvent = event;
1081 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001082 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 mWaitWorkCV.signal();
1085}
1086
1087void AudioFlinger::ThreadBase::processConfigEvents()
1088{
1089 mLock.lock();
1090 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001091 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001092 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 mConfigEvents.removeAt(0);
1094 // release mLock before locking AudioFlinger mLock: lock order is always
1095 // AudioFlinger then ThreadBase to avoid cross deadlock
1096 mLock.unlock();
1097 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001098 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001100 mLock.lock();
1101 }
1102 mLock.unlock();
1103}
1104
1105status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1106{
1107 const size_t SIZE = 256;
1108 char buffer[SIZE];
1109 String8 result;
1110
1111 bool locked = tryLock(mLock);
1112 if (!locked) {
1113 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1114 write(fd, buffer, strlen(buffer));
1115 }
1116
1117 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1118 result.append(buffer);
1119 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1122 result.append(buffer);
1123 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1124 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001125 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1126 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1128 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001129 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001130 result.append(buffer);
1131
1132 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1133 result.append(buffer);
1134 result.append(" Index Command");
1135 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1136 snprintf(buffer, SIZE, "\n %02d ", i);
1137 result.append(buffer);
1138 result.append(mNewParameters[i]);
1139 }
1140
1141 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1142 result.append(buffer);
1143 snprintf(buffer, SIZE, " Index event param\n");
1144 result.append(buffer);
1145 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001146 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001147 result.append(buffer);
1148 }
1149 result.append("\n");
1150
1151 write(fd, result.string(), result.size());
1152
1153 if (locked) {
1154 mLock.unlock();
1155 }
1156 return NO_ERROR;
1157}
1158
Eric Laurent1d2bff02011-07-24 17:49:51 -07001159status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1160{
1161 const size_t SIZE = 256;
1162 char buffer[SIZE];
1163 String8 result;
1164
1165 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1166 write(fd, buffer, strlen(buffer));
1167
1168 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1169 sp<EffectChain> chain = mEffectChains[i];
1170 if (chain != 0) {
1171 chain->dump(fd, args);
1172 }
1173 }
1174 return NO_ERROR;
1175}
1176
Eric Laurentfeb0db62011-07-22 09:04:31 -07001177void AudioFlinger::ThreadBase::acquireWakeLock()
1178{
1179 Mutex::Autolock _l(mLock);
1180 acquireWakeLock_l();
1181}
1182
1183void AudioFlinger::ThreadBase::acquireWakeLock_l()
1184{
1185 if (mPowerManager == 0) {
1186 // use checkService() to avoid blocking if power service is not up yet
1187 sp<IBinder> binder =
1188 defaultServiceManager()->checkService(String16("power"));
1189 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001190 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001191 } else {
1192 mPowerManager = interface_cast<IPowerManager>(binder);
1193 binder->linkToDeath(mDeathRecipient);
1194 }
1195 }
1196 if (mPowerManager != 0) {
1197 sp<IBinder> binder = new BBinder();
1198 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1199 binder,
1200 String16(mName));
1201 if (status == NO_ERROR) {
1202 mWakeLockToken = binder;
1203 }
Steve Block3856b092011-10-20 11:56:00 +01001204 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001205 }
1206}
1207
1208void AudioFlinger::ThreadBase::releaseWakeLock()
1209{
1210 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001211 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001212}
1213
1214void AudioFlinger::ThreadBase::releaseWakeLock_l()
1215{
1216 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001217 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001218 if (mPowerManager != 0) {
1219 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1220 }
1221 mWakeLockToken.clear();
1222 }
1223}
1224
1225void AudioFlinger::ThreadBase::clearPowerManager()
1226{
1227 Mutex::Autolock _l(mLock);
1228 releaseWakeLock_l();
1229 mPowerManager.clear();
1230}
1231
1232void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1233{
1234 sp<ThreadBase> thread = mThread.promote();
1235 if (thread != 0) {
1236 thread->clearPowerManager();
1237 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001238 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001239}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001240
Eric Laurent59255e42011-07-27 19:49:51 -07001241void AudioFlinger::ThreadBase::setEffectSuspended(
1242 const effect_uuid_t *type, bool suspend, int sessionId)
1243{
1244 Mutex::Autolock _l(mLock);
1245 setEffectSuspended_l(type, suspend, sessionId);
1246}
1247
1248void AudioFlinger::ThreadBase::setEffectSuspended_l(
1249 const effect_uuid_t *type, bool suspend, int sessionId)
1250{
1251 sp<EffectChain> chain;
1252 chain = getEffectChain_l(sessionId);
1253 if (chain != 0) {
1254 if (type != NULL) {
1255 chain->setEffectSuspended_l(type, suspend);
1256 } else {
1257 chain->setEffectSuspendedAll_l(suspend);
1258 }
1259 }
1260
1261 updateSuspendedSessions_l(type, suspend, sessionId);
1262}
1263
1264void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1265{
1266 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1267 if (index < 0) {
1268 return;
1269 }
1270
1271 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1272 mSuspendedSessions.editValueAt(index);
1273
1274 for (size_t i = 0; i < sessionEffects.size(); i++) {
1275 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1276 for (int j = 0; j < desc->mRefCount; j++) {
1277 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1278 chain->setEffectSuspendedAll_l(true);
1279 } else {
Steve Block3856b092011-10-20 11:56:00 +01001280 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001281 desc->mType.timeLow);
1282 chain->setEffectSuspended_l(&desc->mType, true);
1283 }
1284 }
1285 }
1286}
1287
Eric Laurent59255e42011-07-27 19:49:51 -07001288void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1289 bool suspend,
1290 int sessionId)
1291{
1292 int index = mSuspendedSessions.indexOfKey(sessionId);
1293
1294 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1295
1296 if (suspend) {
1297 if (index >= 0) {
1298 sessionEffects = mSuspendedSessions.editValueAt(index);
1299 } else {
1300 mSuspendedSessions.add(sessionId, sessionEffects);
1301 }
1302 } else {
1303 if (index < 0) {
1304 return;
1305 }
1306 sessionEffects = mSuspendedSessions.editValueAt(index);
1307 }
1308
1309
1310 int key = EffectChain::kKeyForSuspendAll;
1311 if (type != NULL) {
1312 key = type->timeLow;
1313 }
1314 index = sessionEffects.indexOfKey(key);
1315
1316 sp <SuspendedSessionDesc> desc;
1317 if (suspend) {
1318 if (index >= 0) {
1319 desc = sessionEffects.valueAt(index);
1320 } else {
1321 desc = new SuspendedSessionDesc();
1322 if (type != NULL) {
1323 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1324 }
1325 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001326 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001327 }
1328 desc->mRefCount++;
1329 } else {
1330 if (index < 0) {
1331 return;
1332 }
1333 desc = sessionEffects.valueAt(index);
1334 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001335 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001336 sessionEffects.removeItemsAt(index);
1337 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001338 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001339 sessionId);
1340 mSuspendedSessions.removeItem(sessionId);
1341 }
1342 }
1343 }
1344 if (!sessionEffects.isEmpty()) {
1345 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1346 }
1347}
1348
1349void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1350 bool enabled,
1351 int sessionId)
1352{
1353 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001354 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1355}
Eric Laurent59255e42011-07-27 19:49:51 -07001356
Eric Laurenta85a74a2011-10-19 11:44:54 -07001357void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1358 bool enabled,
1359 int sessionId)
1360{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001361 if (mType != RECORD) {
1362 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1363 // another session. This gives the priority to well behaved effect control panels
1364 // and applications not using global effects.
1365 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1366 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1367 }
1368 }
Eric Laurent59255e42011-07-27 19:49:51 -07001369
1370 sp<EffectChain> chain = getEffectChain_l(sessionId);
1371 if (chain != 0) {
1372 chain->checkSuspendOnEffectEnabled(effect, enabled);
1373 }
1374}
1375
Mathias Agopian65ab4712010-07-14 17:59:35 -07001376// ----------------------------------------------------------------------------
1377
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001378AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1379 AudioStreamOut* output,
1380 int id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001381 uint32_t device,
1382 type_t type)
1383 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001384 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1385 // Assumes constructor is called by AudioFlinger with it's mLock held,
1386 // but it would be safer to explicitly pass initial masterMute as parameter
1387 mMasterMute(audioFlinger->masterMute_l()),
1388 // mStreamTypes[] initialized in constructor body
1389 mOutput(output),
1390 // Assumes constructor is called by AudioFlinger with it's mLock held,
1391 // but it would be safer to explicitly pass initial masterVolume as parameter
1392 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001393 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001395 snprintf(mName, kNameLength, "AudioOut_%d", id);
1396
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397 readOutputParameters();
1398
Glenn Kasten263709e2012-01-06 08:40:01 -08001399 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001400 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1401 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1402 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1404 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001405 // initialized by stream_type_t default constructor
1406 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001407 }
1408}
1409
1410AudioFlinger::PlaybackThread::~PlaybackThread()
1411{
1412 delete [] mMixBuffer;
1413}
1414
1415status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1416{
1417 dumpInternals(fd, args);
1418 dumpTracks(fd, args);
1419 dumpEffectChains(fd, args);
1420 return NO_ERROR;
1421}
1422
1423status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1424{
1425 const size_t SIZE = 256;
1426 char buffer[SIZE];
1427 String8 result;
1428
1429 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1430 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001431 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432 for (size_t i = 0; i < mTracks.size(); ++i) {
1433 sp<Track> track = mTracks[i];
1434 if (track != 0) {
1435 track->dump(buffer, SIZE);
1436 result.append(buffer);
1437 }
1438 }
1439
1440 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1441 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001442 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 -07001443 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001444 sp<Track> track = mActiveTracks[i].promote();
1445 if (track != 0) {
1446 track->dump(buffer, SIZE);
1447 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448 }
1449 }
1450 write(fd, result.string(), result.size());
1451 return NO_ERROR;
1452}
1453
Mathias Agopian65ab4712010-07-14 17:59:35 -07001454status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1455{
1456 const size_t SIZE = 256;
1457 char buffer[SIZE];
1458 String8 result;
1459
1460 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1461 result.append(buffer);
1462 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1463 result.append(buffer);
1464 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1465 result.append(buffer);
1466 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1467 result.append(buffer);
1468 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1469 result.append(buffer);
1470 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1471 result.append(buffer);
1472 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1473 result.append(buffer);
1474 write(fd, result.string(), result.size());
1475
1476 dumpBase(fd, args);
1477
1478 return NO_ERROR;
1479}
1480
1481// Thread virtuals
1482status_t AudioFlinger::PlaybackThread::readyToRun()
1483{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001484 status_t status = initCheck();
1485 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001486 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001487 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001488 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001490 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491}
1492
1493void AudioFlinger::PlaybackThread::onFirstRef()
1494{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001495 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496}
1497
1498// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1499sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1500 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001501 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001503 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001504 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 int frameCount,
1506 const sp<IMemory>& sharedBuffer,
1507 int sessionId,
1508 status_t *status)
1509{
1510 sp<Track> track;
1511 status_t lStatus;
1512
1513 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001514 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1515 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001516 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001517 "for output %p with format %d",
1518 sampleRate, format, channelMask, mOutput, mFormat);
1519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 }
1523 } else {
1524 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1525 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001526 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 lStatus = BAD_VALUE;
1528 goto Exit;
1529 }
1530 }
1531
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001532 lStatus = initCheck();
1533 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001534 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 goto Exit;
1536 }
1537
1538 { // scope for mLock
1539 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001540
1541 // all tracks in same audio session must share the same routing strategy otherwise
1542 // conflicts will happen when tracks are moved from one output to another by audio policy
1543 // manager
1544 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001545 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001546 for (size_t i = 0; i < mTracks.size(); ++i) {
1547 sp<Track> t = mTracks[i];
1548 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001549 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1550 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001551 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001552 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001553 lStatus = BAD_VALUE;
1554 goto Exit;
1555 }
1556 }
1557 }
1558
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001560 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 if (track->getCblk() == NULL || track->name() < 0) {
1562 lStatus = NO_MEMORY;
1563 goto Exit;
1564 }
1565 mTracks.add(track);
1566
1567 sp<EffectChain> chain = getEffectChain_l(sessionId);
1568 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001569 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001571 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001572 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001574
1575 // invalidate track immediately if the stream type was moved to another thread since
1576 // createTrack() was called by the client process.
1577 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001578 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001579 this, streamType);
1580 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1581 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 }
1583 lStatus = NO_ERROR;
1584
1585Exit:
1586 if(status) {
1587 *status = lStatus;
1588 }
1589 return track;
1590}
1591
1592uint32_t AudioFlinger::PlaybackThread::latency() const
1593{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001594 Mutex::Autolock _l(mLock);
1595 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001596 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001597 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 return 0;
1599 }
1600}
1601
1602status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1603{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 mMasterVolume = value;
1605 return NO_ERROR;
1606}
1607
1608status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1609{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 mMasterMute = muted;
1611 return NO_ERROR;
1612}
1613
1614float AudioFlinger::PlaybackThread::masterVolume() const
1615{
1616 return mMasterVolume;
1617}
1618
1619bool AudioFlinger::PlaybackThread::masterMute() const
1620{
1621 return mMasterMute;
1622}
1623
Glenn Kastenfff6d712012-01-12 16:38:12 -08001624status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626 mStreamTypes[stream].volume = value;
1627 return NO_ERROR;
1628}
1629
Glenn Kastenfff6d712012-01-12 16:38:12 -08001630status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632 mStreamTypes[stream].mute = muted;
1633 return NO_ERROR;
1634}
1635
Glenn Kastenfff6d712012-01-12 16:38:12 -08001636float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637{
1638 return mStreamTypes[stream].volume;
1639}
1640
Glenn Kastenfff6d712012-01-12 16:38:12 -08001641bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642{
1643 return mStreamTypes[stream].mute;
1644}
1645
Mathias Agopian65ab4712010-07-14 17:59:35 -07001646// addTrack_l() must be called with ThreadBase::mLock held
1647status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1648{
1649 status_t status = ALREADY_EXISTS;
1650
1651 // set retry count for buffer fill
1652 track->mRetryCount = kMaxTrackStartupRetries;
1653 if (mActiveTracks.indexOf(track) < 0) {
1654 // the track is newly added, make sure it fills up all its
1655 // buffers before playing. This is to ensure the client will
1656 // effectively get the latency it requested.
1657 track->mFillingUpStatus = Track::FS_FILLING;
1658 track->mResetDone = false;
1659 mActiveTracks.add(track);
1660 if (track->mainBuffer() != mMixBuffer) {
1661 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1662 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001663 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001664 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
1666 }
1667
1668 status = NO_ERROR;
1669 }
1670
Steve Block3856b092011-10-20 11:56:00 +01001671 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672 mWaitWorkCV.broadcast();
1673
1674 return status;
1675}
1676
1677// destroyTrack_l() must be called with ThreadBase::mLock held
1678void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1679{
1680 track->mState = TrackBase::TERMINATED;
1681 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001682 removeTrack_l(track);
1683 }
1684}
1685
1686void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1687{
1688 mTracks.remove(track);
1689 deleteTrackName_l(track->name());
1690 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1691 if (chain != 0) {
1692 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 }
1694}
1695
1696String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1697{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001698 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001699 char *s;
1700
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001701 Mutex::Autolock _l(mLock);
1702 if (initCheck() != NO_ERROR) {
1703 return out_s8;
1704 }
1705
Dima Zavin799a70e2011-04-18 16:57:27 -07001706 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001707 out_s8 = String8(s);
1708 free(s);
1709 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001710}
1711
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001712// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1714 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001715 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716
Steve Block3856b092011-10-20 11:56:00 +01001717 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718
1719 switch (event) {
1720 case AudioSystem::OUTPUT_OPENED:
1721 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001722 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 desc.samplingRate = mSampleRate;
1724 desc.format = mFormat;
1725 desc.frameCount = mFrameCount;
1726 desc.latency = latency();
1727 param2 = &desc;
1728 break;
1729
1730 case AudioSystem::STREAM_CONFIG_CHANGED:
1731 param2 = &param;
1732 case AudioSystem::OUTPUT_CLOSED:
1733 default:
1734 break;
1735 }
1736 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1737}
1738
1739void AudioFlinger::PlaybackThread::readOutputParameters()
1740{
Dima Zavin799a70e2011-04-18 16:57:27 -07001741 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001742 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1743 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001744 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001745 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001746 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747
1748 // FIXME - Current mixer implementation only supports stereo output: Always
1749 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001750 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 mMixBuffer = new int16_t[mFrameCount * 2];
1752 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1753
Eric Laurentde070132010-07-13 04:45:46 -07001754 // force reconfiguration of effect chains and engines to take new buffer size and audio
1755 // parameters into account
1756 // Note that mLock is not held when readOutputParameters() is called from the constructor
1757 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1758 // matter.
1759 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1760 Vector< sp<EffectChain> > effectChains = mEffectChains;
1761 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001762 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
1766status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1767{
Glenn Kastena0d68332012-01-27 16:47:15 -08001768 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 return BAD_VALUE;
1770 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001771 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001772 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 return INVALID_OPERATION;
1774 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001775 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776
Dima Zavin799a70e2011-04-18 16:57:27 -07001777 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778}
1779
Eric Laurent39e94f82010-07-28 01:32:47 -07001780uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781{
1782 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001783 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001785 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786 }
1787
1788 for (size_t i = 0; i < mTracks.size(); ++i) {
1789 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001790 if (sessionId == track->sessionId() &&
1791 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001792 result |= TRACK_SESSION;
1793 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794 }
1795 }
1796
Eric Laurent39e94f82010-07-28 01:32:47 -07001797 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001798}
1799
Eric Laurentde070132010-07-13 04:45:46 -07001800uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1801{
Dima Zavinfce7a472011-04-19 22:30:36 -07001802 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001803 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001804 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1805 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001806 }
1807 for (size_t i = 0; i < mTracks.size(); i++) {
1808 sp<Track> track = mTracks[i];
1809 if (sessionId == track->sessionId() &&
1810 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001811 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001812 }
1813 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001814 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001815}
1816
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817
Glenn Kastenaed850d2012-01-26 09:46:34 -08001818AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001819{
1820 Mutex::Autolock _l(mLock);
1821 return mOutput;
1822}
1823
1824AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1825{
1826 Mutex::Autolock _l(mLock);
1827 AudioStreamOut *output = mOutput;
1828 mOutput = NULL;
1829 return output;
1830}
1831
1832// this method must always be called either with ThreadBase mLock held or inside the thread loop
1833audio_stream_t* AudioFlinger::PlaybackThread::stream()
1834{
1835 if (mOutput == NULL) {
1836 return NULL;
1837 }
1838 return &mOutput->stream->common;
1839}
1840
Eric Laurent162b40b2011-12-05 09:47:19 -08001841uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1842{
1843 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1844 // decoding and transfer time. So sleeping for half of the latency would likely cause
1845 // underruns
1846 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1847 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1848 } else {
1849 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1850 }
1851}
1852
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853// ----------------------------------------------------------------------------
1854
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001855AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1856 int id, uint32_t device, type_t type)
1857 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001858 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1859 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 // FIXME - Current mixer implementation only supports stereo output
1862 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001863 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 }
1865}
1866
1867AudioFlinger::MixerThread::~MixerThread()
1868{
1869 delete mAudioMixer;
1870}
1871
1872bool AudioFlinger::MixerThread::threadLoop()
1873{
1874 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001875 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 nsecs_t standbyTime = systemTime();
1877 size_t mixBufferSize = mFrameCount * mFrameSize;
1878 // FIXME: Relaxed timing because of a certain device that can't meet latency
1879 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001880 // increase threshold again due to low power audio mode. The way this warning threshold is
1881 // calculated and its usefulness should be reconsidered anyway.
1882 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 nsecs_t lastWarning = 0;
1884 bool longStandbyExit = false;
1885 uint32_t activeSleepTime = activeSleepTimeUs();
1886 uint32_t idleSleepTime = idleSleepTimeUs();
1887 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001888 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001890#ifdef DEBUG_CPU_USAGE
1891 ThreadCpuUsage cpu;
1892 const CentralTendencyStatistics& stats = cpu.statistics();
1893#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894
Eric Laurentfeb0db62011-07-22 09:04:31 -07001895 acquireWakeLock();
1896
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 while (!exitPending())
1898 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001899#ifdef DEBUG_CPU_USAGE
1900 cpu.sampleAndEnable();
1901 unsigned n = stats.n();
1902 // cpu.elapsed() is expensive, so don't call it every loop
1903 if ((n & 127) == 1) {
1904 long long elapsed = cpu.elapsed();
1905 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1906 double perLoop = elapsed / (double) n;
1907 double perLoop100 = perLoop * 0.01;
1908 double mean = stats.mean();
1909 double stddev = stats.stddev();
1910 double minimum = stats.minimum();
1911 double maximum = stats.maximum();
1912 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001913 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 -07001914 elapsed * .000000001, n, perLoop * .000001,
1915 mean * .001,
1916 stddev * .001,
1917 minimum * .001,
1918 maximum * .001,
1919 mean / perLoop100,
1920 stddev / perLoop100,
1921 minimum / perLoop100,
1922 maximum / perLoop100);
1923 }
1924 }
1925#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 processConfigEvents();
1927
1928 mixerStatus = MIXER_IDLE;
1929 { // scope for mLock
1930
1931 Mutex::Autolock _l(mLock);
1932
1933 if (checkForNewParameters_l()) {
1934 mixBufferSize = mFrameCount * mFrameSize;
1935 // FIXME: Relaxed timing because of a certain device that can't meet latency
1936 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001937 // increase threshold again due to low power audio mode. The way this warning
1938 // threshold is calculated and its usefulness should be reconsidered anyway.
1939 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 activeSleepTime = activeSleepTimeUs();
1941 idleSleepTime = idleSleepTimeUs();
1942 }
1943
1944 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1945
1946 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001947 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1948 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001950 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001951 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 mStandby = true;
1953 mBytesWritten = 0;
1954 }
1955
1956 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1957 // we're about to wait, flush the binder command buffer
1958 IPCThreadState::self()->flushCommands();
1959
1960 if (exitPending()) break;
1961
Eric Laurentfeb0db62011-07-22 09:04:31 -07001962 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001964 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001966 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001967 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968
Eric Laurent27741442012-01-17 19:20:12 -08001969 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001970 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 char value[PROPERTY_VALUE_MAX];
1972 property_get("ro.audio.silent", value, "0");
1973 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001974 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 setMasterMute(true);
1976 }
1977 }
1978
1979 standbyTime = systemTime() + kStandbyTimeInNsecs;
1980 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001981 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 continue;
1983 }
1984 }
1985
1986 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1987
1988 // prevent any changes in effect chain list and in each effect chain
1989 // during mixing and effect process as the audio buffers could be deleted
1990 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001991 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993
Glenn Kastenf6b16782011-12-15 09:51:17 -08001994 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995 // mix buffers...
1996 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001997 // increase sleep time progressively when application underrun condition clears.
1998 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1999 // that a steady state of alternating ready/not ready conditions keeps the sleep time
2000 // such that we would underrun the audio HAL.
2001 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002002 sleepTimeShift--;
2003 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002004 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 standbyTime = systemTime() + kStandbyTimeInNsecs;
2006 //TODO: delay standby when effects have a tail
2007 } else {
2008 // If no tracks are ready, sleep once for the duration of an output
2009 // buffer size, then write 0s to the output
2010 if (sleepTime == 0) {
2011 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002012 sleepTime = activeSleepTime >> sleepTimeShift;
2013 if (sleepTime < kMinThreadSleepTimeUs) {
2014 sleepTime = kMinThreadSleepTimeUs;
2015 }
2016 // reduce sleep time in case of consecutive application underruns to avoid
2017 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2018 // duration we would end up writing less data than needed by the audio HAL if
2019 // the condition persists.
2020 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2021 sleepTimeShift++;
2022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 } else {
2024 sleepTime = idleSleepTime;
2025 }
2026 } else if (mBytesWritten != 0 ||
2027 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2028 memset (mMixBuffer, 0, mixBufferSize);
2029 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002030 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031 }
2032 // TODO add standby time extension fct of effect tail
2033 }
2034
2035 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002036 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 }
2038 // sleepTime == 0 means we must write to audio hardware
2039 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002040 for (size_t i = 0; i < effectChains.size(); i ++) {
2041 effectChains[i]->process_l();
2042 }
2043 // enable changes in effect chain
2044 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 mLastWriteTime = systemTime();
2046 mInWrite = true;
2047 mBytesWritten += mixBufferSize;
2048
Dima Zavin799a70e2011-04-18 16:57:27 -07002049 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2051 mNumWrites++;
2052 mInWrite = false;
2053 nsecs_t now = systemTime();
2054 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002055 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002057 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002058 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 ns2ms(delta), mNumDelayedWrites, this);
2060 lastWarning = now;
2061 }
2062 if (mStandby) {
2063 longStandbyExit = true;
2064 }
2065 }
2066 mStandby = false;
2067 } else {
2068 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002069 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 usleep(sleepTime);
2071 }
2072
2073 // finally let go of all our tracks, without the lock held
2074 // since we can't guarantee the destructors won't acquire that
2075 // same lock.
2076 tracksToRemove.clear();
2077
2078 // Effect chains will be actually deleted here if they were removed from
2079 // mEffectChains list during mixing or effects processing
2080 effectChains.clear();
2081 }
2082
2083 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002084 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 }
2086
Eric Laurentfeb0db62011-07-22 09:04:31 -07002087 releaseWakeLock();
2088
Steve Block3856b092011-10-20 11:56:00 +01002089 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 return false;
2091}
2092
2093// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002094AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2095 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096{
2097
Glenn Kasten29c23c32012-01-26 13:37:52 -08002098 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 // find out which tracks need to be processed
2100 size_t count = activeTracks.size();
2101 size_t mixedTracks = 0;
2102 size_t tracksWithEffect = 0;
2103
2104 float masterVolume = mMasterVolume;
2105 bool masterMute = mMasterMute;
2106
Eric Laurent571d49c2010-08-11 05:20:11 -07002107 if (masterMute) {
2108 masterVolume = 0;
2109 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002111 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002113 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002114 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 masterVolume = (float)((v + (1 << 23)) >> 24);
2116 chain.clear();
2117 }
2118
2119 for (size_t i=0 ; i<count ; i++) {
2120 sp<Track> t = activeTracks[i].promote();
2121 if (t == 0) continue;
2122
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002123 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 Track* const track = t.get();
2125 audio_track_cblk_t* cblk = track->cblk();
2126
2127 // The first time a track is added we wait
2128 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002129 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002130 // make sure that we have enough frames to mix one full buffer.
2131 // enforce this condition only once to enable draining the buffer in case the client
2132 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002133 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002134 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002135 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002136 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002137 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002138 if (t->sampleRate() == (int)mSampleRate) {
2139 minFrames = mFrameCount;
2140 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002141 // +1 for rounding and +1 for additional sample needed for interpolation
2142 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2143 // add frames already consumed but not yet released by the resampler
2144 // because cblk->framesReady() will include these frames
2145 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2146 // the minimum track buffer size is normally twice the number of frames necessary
2147 // to fill one buffer and the resampler should not leave more than one buffer worth
2148 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002149 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002150 }
2151 }
2152 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 !track->isPaused() && !track->isTerminated())
2154 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002155 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156
2157 mixedTracks++;
2158
2159 // track->mainBuffer() != mMixBuffer means there is an effect chain
2160 // connected to the track
2161 chain.clear();
2162 if (track->mainBuffer() != mMixBuffer) {
2163 chain = getEffectChain_l(track->sessionId());
2164 // Delegate volume control to effect in track effect chain if needed
2165 if (chain != 0) {
2166 tracksWithEffect++;
2167 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002168 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002169 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170 }
2171 }
2172
2173
2174 int param = AudioMixer::VOLUME;
2175 if (track->mFillingUpStatus == Track::FS_FILLED) {
2176 // no ramp for the first volume setting
2177 track->mFillingUpStatus = Track::FS_ACTIVE;
2178 if (track->mState == TrackBase::RESUMING) {
2179 track->mState = TrackBase::ACTIVE;
2180 param = AudioMixer::RAMP_VOLUME;
2181 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002182 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 } else if (cblk->server != 0) {
2184 // If the track is stopped before the first frame was mixed,
2185 // do not apply ramp
2186 param = AudioMixer::RAMP_VOLUME;
2187 }
2188
2189 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002190 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002191 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002193 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 if (track->isPausing()) {
2195 track->setPaused();
2196 }
2197 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002198
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 // read original volumes with volume control
2200 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002202 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002203 vl = vlr & 0xFFFF;
2204 vr = vlr >> 16;
2205 // track volumes come from shared memory, so can't be trusted and must be clamped
2206 if (vl > MAX_GAIN_INT) {
2207 ALOGV("Track left volume out of range: %04X", vl);
2208 vl = MAX_GAIN_INT;
2209 }
2210 if (vr > MAX_GAIN_INT) {
2211 ALOGV("Track right volume out of range: %04X", vr);
2212 vr = MAX_GAIN_INT;
2213 }
2214 // now apply the master volume and stream type volume
2215 vl = (uint32_t)(v * vl) << 12;
2216 vr = (uint32_t)(v * vr) << 12;
2217 // assuming master volume and stream type volume each go up to 1.0,
2218 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Glenn Kasten05632a52012-01-03 14:22:33 -08002220 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2221 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002222 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002223 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002224 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002225 }
2226 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002228 // Delegate volume control to effect in track effect chain if needed
2229 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2230 // Do not ramp volume if volume is controlled by effect
2231 param = AudioMixer::VOLUME;
2232 track->mHasVolumeController = true;
2233 } else {
2234 // force no volume ramp when volume controller was just disabled or removed
2235 // from effect chain to avoid volume spike
2236 if (track->mHasVolumeController) {
2237 param = AudioMixer::VOLUME;
2238 }
2239 track->mHasVolumeController = false;
2240 }
2241
2242 // Convert volumes from 8.24 to 4.12 format
2243 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002244 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002245 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2246 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2247 left = int16_t(v_clamped);
2248 v_clamped = (vr + (1 << 11)) >> 12;
2249 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2250 right = int16_t(v_clamped);
2251
2252 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2253 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002256 mAudioMixer->setBufferProvider(name, track);
2257 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002259 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2260 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2261 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002263 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002264 AudioMixer::TRACK,
2265 AudioMixer::FORMAT, (void *)track->format());
2266 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002267 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002269 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002271 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 AudioMixer::RESAMPLE,
2273 AudioMixer::SAMPLE_RATE,
2274 (void *)(cblk->sampleRate));
2275 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002276 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 AudioMixer::TRACK,
2278 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2279 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002280 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 AudioMixer::TRACK,
2282 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2283
2284 // reset retry count
2285 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002286 // If one track is ready, set the mixer ready if:
2287 // - the mixer was not ready during previous round OR
2288 // - no other track is not ready
2289 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2290 mixerStatus != MIXER_TRACKS_ENABLED) {
2291 mixerStatus = MIXER_TRACKS_READY;
2292 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002294 //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 -07002295 if (track->isStopped()) {
2296 track->reset();
2297 }
2298 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2299 // We have consumed all the buffers of this track.
2300 // Remove it from the list of active tracks.
2301 tracksToRemove->add(track);
2302 } else {
2303 // No buffers for this track. Give it a few chances to
2304 // fill a buffer, then remove it from active list.
2305 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002306 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002308 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002309 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002310 // If one track is not ready, mark the mixer also not ready if:
2311 // - the mixer was ready during previous round OR
2312 // - no other track is ready
2313 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2314 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 mixerStatus = MIXER_TRACKS_ENABLED;
2316 }
2317 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002318 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 }
2320 }
2321
2322 // remove all the tracks that need to be...
2323 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002324 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325 for (size_t i=0 ; i<count ; i++) {
2326 const sp<Track>& track = tracksToRemove->itemAt(i);
2327 mActiveTracks.remove(track);
2328 if (track->mainBuffer() != mMixBuffer) {
2329 chain = getEffectChain_l(track->sessionId());
2330 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002331 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002332 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 }
2334 }
2335 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002336 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337 }
2338 }
2339 }
2340
2341 // mix buffer must be cleared if all tracks are connected to an
2342 // effect chain as in this case the mixer will not write to
2343 // mix buffer and track effects will accumulate into it
2344 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2345 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2346 }
2347
Eric Laurent27741442012-01-17 19:20:12 -08002348 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 return mixerStatus;
2350}
2351
Glenn Kastenfff6d712012-01-12 16:38:12 -08002352void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353{
Steve Block3856b092011-10-20 11:56:00 +01002354 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002355 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002357
Mathias Agopian65ab4712010-07-14 17:59:35 -07002358 size_t size = mTracks.size();
2359 for (size_t i = 0; i < size; i++) {
2360 sp<Track> t = mTracks[i];
2361 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002362 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 }
2365 }
2366}
2367
Glenn Kastenfff6d712012-01-12 16:38:12 -08002368void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002369{
Steve Block3856b092011-10-20 11:56:00 +01002370 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002371 this, streamType, valid);
2372 Mutex::Autolock _l(mLock);
2373
2374 mStreamTypes[streamType].valid = valid;
2375}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376
2377// getTrackName_l() must be called with ThreadBase::mLock held
2378int AudioFlinger::MixerThread::getTrackName_l()
2379{
2380 return mAudioMixer->getTrackName();
2381}
2382
2383// deleteTrackName_l() must be called with ThreadBase::mLock held
2384void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2385{
Steve Block3856b092011-10-20 11:56:00 +01002386 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 mAudioMixer->deleteTrackName(name);
2388}
2389
2390// checkForNewParameters_l() must be called with ThreadBase::mLock held
2391bool AudioFlinger::MixerThread::checkForNewParameters_l()
2392{
2393 bool reconfig = false;
2394
2395 while (!mNewParameters.isEmpty()) {
2396 status_t status = NO_ERROR;
2397 String8 keyValuePair = mNewParameters[0];
2398 AudioParameter param = AudioParameter(keyValuePair);
2399 int value;
2400
2401 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2402 reconfig = true;
2403 }
2404 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002405 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 status = BAD_VALUE;
2407 } else {
2408 reconfig = true;
2409 }
2410 }
2411 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002412 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002413 status = BAD_VALUE;
2414 } else {
2415 reconfig = true;
2416 }
2417 }
2418 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2419 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002420 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 // if frame count is changed after track creation
2422 if (!mTracks.isEmpty()) {
2423 status = INVALID_OPERATION;
2424 } else {
2425 reconfig = true;
2426 }
2427 }
2428 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002429 // when changing the audio output device, call addBatteryData to notify
2430 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002431 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002432 uint32_t params = 0;
2433 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002434 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002435 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2436 }
2437
2438 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002439 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002440 // check if any other device (except speaker) is on
2441 if (value & deviceWithoutSpeaker ) {
2442 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2443 }
2444
2445 if (params != 0) {
2446 addBatteryData(params);
2447 }
2448 }
2449
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 // forward device change to effects that have requested to be
2451 // aware of attached audio device.
2452 mDevice = (uint32_t)value;
2453 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002454 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002455 }
2456 }
2457
2458 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002459 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002460 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002461 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002462 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463 mStandby = true;
2464 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002465 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002466 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 }
2468 if (status == NO_ERROR && reconfig) {
2469 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002470 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2471 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 readOutputParameters();
2473 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2474 for (size_t i = 0; i < mTracks.size() ; i++) {
2475 int name = getTrackName_l();
2476 if (name < 0) break;
2477 mTracks[i]->mName = name;
2478 // limit track sample rate to 2 x new output sample rate
2479 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2480 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2481 }
2482 }
2483 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2484 }
2485 }
2486
2487 mNewParameters.removeAt(0);
2488
2489 mParamStatus = status;
2490 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002491 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2492 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002493 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 }
2495 return reconfig;
2496}
2497
2498status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2499{
2500 const size_t SIZE = 256;
2501 char buffer[SIZE];
2502 String8 result;
2503
2504 PlaybackThread::dumpInternals(fd, args);
2505
2506 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2507 result.append(buffer);
2508 write(fd, result.string(), result.size());
2509 return NO_ERROR;
2510}
2511
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2513{
Eric Laurent60e18242010-07-29 06:50:24 -07002514 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515}
2516
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002517uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2518{
2519 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2520}
2521
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002523AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002524 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002525 // mLeftVolFloat, mRightVolFloat
2526 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528}
2529
2530AudioFlinger::DirectOutputThread::~DirectOutputThread()
2531{
2532}
2533
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534static inline
2535int32_t mul(int16_t in, int16_t v)
2536{
2537#if defined(__arm__) && !defined(__thumb__)
2538 int32_t out;
2539 asm( "smulbb %[out], %[in], %[v] \n"
2540 : [out]"=r"(out)
2541 : [in]"%r"(in), [v]"r"(v)
2542 : );
2543 return out;
2544#else
2545 return in * int32_t(v);
2546#endif
2547}
2548
2549void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2550{
2551 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002552 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 return;
2554 }
2555
2556 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002557 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002558 size_t count = mFrameCount * mChannelCount;
2559 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2560 int16_t *dst = mMixBuffer + count-1;
2561 while(count--) {
2562 *dst-- = (int16_t)(*src--^0x80) << 8;
2563 }
2564 }
2565
2566 size_t frameCount = mFrameCount;
2567 int16_t *out = mMixBuffer;
2568 if (ramp) {
2569 if (mChannelCount == 1) {
2570 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2571 int32_t vlInc = d / (int32_t)frameCount;
2572 int32_t vl = ((int32_t)mLeftVolShort << 16);
2573 do {
2574 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2575 out++;
2576 vl += vlInc;
2577 } while (--frameCount);
2578
2579 } else {
2580 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2581 int32_t vlInc = d / (int32_t)frameCount;
2582 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2583 int32_t vrInc = d / (int32_t)frameCount;
2584 int32_t vl = ((int32_t)mLeftVolShort << 16);
2585 int32_t vr = ((int32_t)mRightVolShort << 16);
2586 do {
2587 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2588 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2589 out += 2;
2590 vl += vlInc;
2591 vr += vrInc;
2592 } while (--frameCount);
2593 }
2594 } else {
2595 if (mChannelCount == 1) {
2596 do {
2597 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2598 out++;
2599 } while (--frameCount);
2600 } else {
2601 do {
2602 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2603 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2604 out += 2;
2605 } while (--frameCount);
2606 }
2607 }
2608
2609 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002610 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611 size_t count = mFrameCount * mChannelCount;
2612 int16_t *src = mMixBuffer;
2613 uint8_t *dst = (uint8_t *)mMixBuffer;
2614 while(count--) {
2615 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2616 }
2617 }
2618
2619 mLeftVolShort = leftVol;
2620 mRightVolShort = rightVol;
2621}
2622
2623bool AudioFlinger::DirectOutputThread::threadLoop()
2624{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002625 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626 sp<Track> trackToRemove;
2627 sp<Track> activeTrack;
2628 nsecs_t standbyTime = systemTime();
2629 int8_t *curBuf;
2630 size_t mixBufferSize = mFrameCount*mFrameSize;
2631 uint32_t activeSleepTime = activeSleepTimeUs();
2632 uint32_t idleSleepTime = idleSleepTimeUs();
2633 uint32_t sleepTime = idleSleepTime;
2634 // use shorter standby delay as on normal output to release
2635 // hardware resources as soon as possible
2636 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2637
Eric Laurentfeb0db62011-07-22 09:04:31 -07002638 acquireWakeLock();
2639
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 while (!exitPending())
2641 {
2642 bool rampVolume;
2643 uint16_t leftVol;
2644 uint16_t rightVol;
2645 Vector< sp<EffectChain> > effectChains;
2646
2647 processConfigEvents();
2648
2649 mixerStatus = MIXER_IDLE;
2650
2651 { // scope for the mLock
2652
2653 Mutex::Autolock _l(mLock);
2654
2655 if (checkForNewParameters_l()) {
2656 mixBufferSize = mFrameCount*mFrameSize;
2657 activeSleepTime = activeSleepTimeUs();
2658 idleSleepTime = idleSleepTimeUs();
2659 standbyDelay = microseconds(activeSleepTime*2);
2660 }
2661
2662 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002663 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2664 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 // wait until we have something to do...
2666 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002667 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002668 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669 mStandby = true;
2670 mBytesWritten = 0;
2671 }
2672
2673 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2674 // we're about to wait, flush the binder command buffer
2675 IPCThreadState::self()->flushCommands();
2676
2677 if (exitPending()) break;
2678
Eric Laurentfeb0db62011-07-22 09:04:31 -07002679 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002680 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002682 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002683 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684
Glenn Kastenf1d45922012-01-13 15:54:24 -08002685 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 char value[PROPERTY_VALUE_MAX];
2687 property_get("ro.audio.silent", value, "0");
2688 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002689 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 setMasterMute(true);
2691 }
2692 }
2693
2694 standbyTime = systemTime() + standbyDelay;
2695 sleepTime = idleSleepTime;
2696 continue;
2697 }
2698 }
2699
2700 effectChains = mEffectChains;
2701
2702 // find out which tracks need to be processed
2703 if (mActiveTracks.size() != 0) {
2704 sp<Track> t = mActiveTracks[0].promote();
2705 if (t == 0) continue;
2706
2707 Track* const track = t.get();
2708 audio_track_cblk_t* cblk = track->cblk();
2709
2710 // The first time a track is added we wait
2711 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002712 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 !track->isPaused() && !track->isTerminated())
2714 {
Steve Block3856b092011-10-20 11:56:00 +01002715 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716
2717 if (track->mFillingUpStatus == Track::FS_FILLED) {
2718 track->mFillingUpStatus = Track::FS_ACTIVE;
2719 mLeftVolFloat = mRightVolFloat = 0;
2720 mLeftVolShort = mRightVolShort = 0;
2721 if (track->mState == TrackBase::RESUMING) {
2722 track->mState = TrackBase::ACTIVE;
2723 rampVolume = true;
2724 }
2725 } else if (cblk->server != 0) {
2726 // If the track is stopped before the first frame was mixed,
2727 // do not apply ramp
2728 rampVolume = true;
2729 }
2730 // compute volume for this track
2731 float left, right;
2732 if (track->isMuted() || mMasterMute || track->isPausing() ||
2733 mStreamTypes[track->type()].mute) {
2734 left = right = 0;
2735 if (track->isPausing()) {
2736 track->setPaused();
2737 }
2738 } else {
2739 float typeVolume = mStreamTypes[track->type()].volume;
2740 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002741 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002742 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2744 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002745 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2747 right = v_clamped/MAX_GAIN;
2748 }
2749
2750 if (left != mLeftVolFloat || right != mRightVolFloat) {
2751 mLeftVolFloat = left;
2752 mRightVolFloat = right;
2753
2754 // If audio HAL implements volume control,
2755 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002756 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 left = 1.0f;
2758 right = 1.0f;
2759 }
2760
2761 // Convert volumes from float to 8.24
2762 uint32_t vl = (uint32_t)(left * (1 << 24));
2763 uint32_t vr = (uint32_t)(right * (1 << 24));
2764
2765 // Delegate volume control to effect in track effect chain if needed
2766 // only one effect chain can be present on DirectOutputThread, so if
2767 // there is one, the track is connected to it
2768 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002769 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002770 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 rampVolume = false;
2772 }
2773 }
2774
2775 // Convert volumes from 8.24 to 4.12 format
2776 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2777 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2778 leftVol = (uint16_t)v_clamped;
2779 v_clamped = (vr + (1 << 11)) >> 12;
2780 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2781 rightVol = (uint16_t)v_clamped;
2782 } else {
2783 leftVol = mLeftVolShort;
2784 rightVol = mRightVolShort;
2785 rampVolume = false;
2786 }
2787
2788 // reset retry count
2789 track->mRetryCount = kMaxTrackRetriesDirect;
2790 activeTrack = t;
2791 mixerStatus = MIXER_TRACKS_READY;
2792 } else {
Steve Block3856b092011-10-20 11:56:00 +01002793 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 if (track->isStopped()) {
2795 track->reset();
2796 }
2797 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2798 // We have consumed all the buffers of this track.
2799 // Remove it from the list of active tracks.
2800 trackToRemove = track;
2801 } else {
2802 // No buffers for this track. Give it a few chances to
2803 // fill a buffer, then remove it from active list.
2804 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002805 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 trackToRemove = track;
2807 } else {
2808 mixerStatus = MIXER_TRACKS_ENABLED;
2809 }
2810 }
2811 }
2812 }
2813
2814 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002815 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816 mActiveTracks.remove(trackToRemove);
2817 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002818 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002819 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002820 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 }
2822 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002823 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 }
2825 }
2826
Eric Laurentde070132010-07-13 04:45:46 -07002827 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 }
2829
Glenn Kastenf6b16782011-12-15 09:51:17 -08002830 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 AudioBufferProvider::Buffer buffer;
2832 size_t frameCount = mFrameCount;
2833 curBuf = (int8_t *)mMixBuffer;
2834 // output audio to hardware
2835 while (frameCount) {
2836 buffer.frameCount = frameCount;
2837 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002838 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 memset(curBuf, 0, frameCount * mFrameSize);
2840 break;
2841 }
2842 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2843 frameCount -= buffer.frameCount;
2844 curBuf += buffer.frameCount * mFrameSize;
2845 activeTrack->releaseBuffer(&buffer);
2846 }
2847 sleepTime = 0;
2848 standbyTime = systemTime() + standbyDelay;
2849 } else {
2850 if (sleepTime == 0) {
2851 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2852 sleepTime = activeSleepTime;
2853 } else {
2854 sleepTime = idleSleepTime;
2855 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002856 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2858 sleepTime = 0;
2859 }
2860 }
2861
2862 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002863 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002864 }
2865 // sleepTime == 0 means we must write to audio hardware
2866 if (sleepTime == 0) {
2867 if (mixerStatus == MIXER_TRACKS_READY) {
2868 applyVolume(leftVol, rightVol, rampVolume);
2869 }
2870 for (size_t i = 0; i < effectChains.size(); i ++) {
2871 effectChains[i]->process_l();
2872 }
Eric Laurentde070132010-07-13 04:45:46 -07002873 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874
2875 mLastWriteTime = systemTime();
2876 mInWrite = true;
2877 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002878 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2880 mNumWrites++;
2881 mInWrite = false;
2882 mStandby = false;
2883 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002884 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885 usleep(sleepTime);
2886 }
2887
2888 // finally let go of removed track, without the lock held
2889 // since we can't guarantee the destructors won't acquire that
2890 // same lock.
2891 trackToRemove.clear();
2892 activeTrack.clear();
2893
2894 // Effect chains will be actually deleted here if they were removed from
2895 // mEffectChains list during mixing or effects processing
2896 effectChains.clear();
2897 }
2898
2899 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002900 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901 }
2902
Eric Laurentfeb0db62011-07-22 09:04:31 -07002903 releaseWakeLock();
2904
Steve Block3856b092011-10-20 11:56:00 +01002905 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 return false;
2907}
2908
2909// getTrackName_l() must be called with ThreadBase::mLock held
2910int AudioFlinger::DirectOutputThread::getTrackName_l()
2911{
2912 return 0;
2913}
2914
2915// deleteTrackName_l() must be called with ThreadBase::mLock held
2916void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2917{
2918}
2919
2920// checkForNewParameters_l() must be called with ThreadBase::mLock held
2921bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2922{
2923 bool reconfig = false;
2924
2925 while (!mNewParameters.isEmpty()) {
2926 status_t status = NO_ERROR;
2927 String8 keyValuePair = mNewParameters[0];
2928 AudioParameter param = AudioParameter(keyValuePair);
2929 int value;
2930
2931 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2932 // do not accept frame count changes if tracks are open as the track buffer
2933 // size depends on frame count and correct behavior would not be garantied
2934 // if frame count is changed after track creation
2935 if (!mTracks.isEmpty()) {
2936 status = INVALID_OPERATION;
2937 } else {
2938 reconfig = true;
2939 }
2940 }
2941 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002942 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002943 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002945 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 mStandby = true;
2947 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002948 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002949 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950 }
2951 if (status == NO_ERROR && reconfig) {
2952 readOutputParameters();
2953 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2954 }
2955 }
2956
2957 mNewParameters.removeAt(0);
2958
2959 mParamStatus = status;
2960 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002961 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2962 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002963 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 }
2965 return reconfig;
2966}
2967
2968uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2969{
2970 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002971 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002972 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 } else {
2974 time = 10000;
2975 }
2976 return time;
2977}
2978
2979uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2980{
2981 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002982 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002983 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 } else {
2985 time = 10000;
2986 }
2987 return time;
2988}
2989
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002990uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2991{
2992 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002993 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002994 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2995 } else {
2996 time = 10000;
2997 }
2998 return time;
2999}
3000
3001
Mathias Agopian65ab4712010-07-14 17:59:35 -07003002// ----------------------------------------------------------------------------
3003
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003004AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3005 AudioFlinger::MixerThread* mainThread, int id)
3006 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3007 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 addOutputTrack(mainThread);
3010}
3011
3012AudioFlinger::DuplicatingThread::~DuplicatingThread()
3013{
3014 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3015 mOutputTracks[i]->destroy();
3016 }
3017 mOutputTracks.clear();
3018}
3019
3020bool AudioFlinger::DuplicatingThread::threadLoop()
3021{
3022 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003023 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 nsecs_t standbyTime = systemTime();
3025 size_t mixBufferSize = mFrameCount*mFrameSize;
3026 SortedVector< sp<OutputTrack> > outputTracks;
3027 uint32_t writeFrames = 0;
3028 uint32_t activeSleepTime = activeSleepTimeUs();
3029 uint32_t idleSleepTime = idleSleepTimeUs();
3030 uint32_t sleepTime = idleSleepTime;
3031 Vector< sp<EffectChain> > effectChains;
3032
Eric Laurentfeb0db62011-07-22 09:04:31 -07003033 acquireWakeLock();
3034
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 while (!exitPending())
3036 {
3037 processConfigEvents();
3038
3039 mixerStatus = MIXER_IDLE;
3040 { // scope for the mLock
3041
3042 Mutex::Autolock _l(mLock);
3043
3044 if (checkForNewParameters_l()) {
3045 mixBufferSize = mFrameCount*mFrameSize;
3046 updateWaitTime();
3047 activeSleepTime = activeSleepTimeUs();
3048 idleSleepTime = idleSleepTimeUs();
3049 }
3050
3051 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3052
3053 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3054 outputTracks.add(mOutputTracks[i]);
3055 }
3056
3057 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003058 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3059 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 if (!mStandby) {
3061 for (size_t i = 0; i < outputTracks.size(); i++) {
3062 outputTracks[i]->stop();
3063 }
3064 mStandby = true;
3065 mBytesWritten = 0;
3066 }
3067
3068 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3069 // we're about to wait, flush the binder command buffer
3070 IPCThreadState::self()->flushCommands();
3071 outputTracks.clear();
3072
3073 if (exitPending()) break;
3074
Eric Laurentfeb0db62011-07-22 09:04:31 -07003075 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003076 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003078 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003079 acquireWakeLock_l();
3080
Eric Laurent27741442012-01-17 19:20:12 -08003081 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003082 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003083 char value[PROPERTY_VALUE_MAX];
3084 property_get("ro.audio.silent", value, "0");
3085 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003086 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 setMasterMute(true);
3088 }
3089 }
3090
3091 standbyTime = systemTime() + kStandbyTimeInNsecs;
3092 sleepTime = idleSleepTime;
3093 continue;
3094 }
3095 }
3096
3097 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3098
3099 // prevent any changes in effect chain list and in each effect chain
3100 // during mixing and effect process as the audio buffers could be deleted
3101 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003102 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 }
3104
Glenn Kastenf6b16782011-12-15 09:51:17 -08003105 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106 // mix buffers...
3107 if (outputsReady(outputTracks)) {
3108 mAudioMixer->process();
3109 } else {
3110 memset(mMixBuffer, 0, mixBufferSize);
3111 }
3112 sleepTime = 0;
3113 writeFrames = mFrameCount;
3114 } else {
3115 if (sleepTime == 0) {
3116 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3117 sleepTime = activeSleepTime;
3118 } else {
3119 sleepTime = idleSleepTime;
3120 }
3121 } else if (mBytesWritten != 0) {
3122 // flush remaining overflow buffers in output tracks
3123 for (size_t i = 0; i < outputTracks.size(); i++) {
3124 if (outputTracks[i]->isActive()) {
3125 sleepTime = 0;
3126 writeFrames = 0;
3127 memset(mMixBuffer, 0, mixBufferSize);
3128 break;
3129 }
3130 }
3131 }
3132 }
3133
3134 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003135 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136 }
3137 // sleepTime == 0 means we must write to audio hardware
3138 if (sleepTime == 0) {
3139 for (size_t i = 0; i < effectChains.size(); i ++) {
3140 effectChains[i]->process_l();
3141 }
3142 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003143 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144
3145 standbyTime = systemTime() + kStandbyTimeInNsecs;
3146 for (size_t i = 0; i < outputTracks.size(); i++) {
3147 outputTracks[i]->write(mMixBuffer, writeFrames);
3148 }
3149 mStandby = false;
3150 mBytesWritten += mixBufferSize;
3151 } else {
3152 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003153 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 usleep(sleepTime);
3155 }
3156
3157 // finally let go of all our tracks, without the lock held
3158 // since we can't guarantee the destructors won't acquire that
3159 // same lock.
3160 tracksToRemove.clear();
3161 outputTracks.clear();
3162
3163 // Effect chains will be actually deleted here if they were removed from
3164 // mEffectChains list during mixing or effects processing
3165 effectChains.clear();
3166 }
3167
Eric Laurentfeb0db62011-07-22 09:04:31 -07003168 releaseWakeLock();
3169
Mathias Agopian65ab4712010-07-14 17:59:35 -07003170 return false;
3171}
3172
3173void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3174{
3175 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3176 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3177 this,
3178 mSampleRate,
3179 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003180 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 frameCount);
3182 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003183 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003185 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003186 updateWaitTime();
3187 }
3188}
3189
3190void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3191{
3192 Mutex::Autolock _l(mLock);
3193 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3194 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3195 mOutputTracks[i]->destroy();
3196 mOutputTracks.removeAt(i);
3197 updateWaitTime();
3198 return;
3199 }
3200 }
Steve Block3856b092011-10-20 11:56:00 +01003201 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202}
3203
3204void AudioFlinger::DuplicatingThread::updateWaitTime()
3205{
3206 mWaitTimeMs = UINT_MAX;
3207 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3208 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3209 if (strong != NULL) {
3210 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3211 if (waitTimeMs < mWaitTimeMs) {
3212 mWaitTimeMs = waitTimeMs;
3213 }
3214 }
3215 }
3216}
3217
3218
3219bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3220{
3221 for (size_t i = 0; i < outputTracks.size(); i++) {
3222 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3223 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003224 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 return false;
3226 }
3227 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3228 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003229 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 return false;
3231 }
3232 }
3233 return true;
3234}
3235
3236uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3237{
3238 return (mWaitTimeMs * 1000) / 2;
3239}
3240
3241// ----------------------------------------------------------------------------
3242
3243// TrackBase constructor must be called with AudioFlinger::mLock held
3244AudioFlinger::ThreadBase::TrackBase::TrackBase(
3245 const wp<ThreadBase>& thread,
3246 const sp<Client>& client,
3247 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003248 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003249 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003250 int frameCount,
3251 uint32_t flags,
3252 const sp<IMemory>& sharedBuffer,
3253 int sessionId)
3254 : RefBase(),
3255 mThread(thread),
3256 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003257 mCblk(NULL),
3258 // mBuffer
3259 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 mFrameCount(0),
3261 mState(IDLE),
3262 mClientTid(-1),
3263 mFormat(format),
3264 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3265 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003266 // mChannelCount
3267 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268{
Steve Block3856b092011-10-20 11:56:00 +01003269 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270
Steve Blockb8a80522011-12-20 16:23:08 +00003271 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003273 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3275 if (sharedBuffer == 0) {
3276 size += bufferSize;
3277 }
3278
3279 if (client != NULL) {
3280 mCblkMemory = client->heap()->allocate(size);
3281 if (mCblkMemory != 0) {
3282 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003283 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 new(mCblk) audio_track_cblk_t();
3285 // clear all buffers
3286 mCblk->frameCount = frameCount;
3287 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003288 mChannelCount = channelCount;
3289 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 if (sharedBuffer == 0) {
3291 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3292 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3293 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003294 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 mCblk->flags = CBLK_UNDERRUN_ON;
3296 } else {
3297 mBuffer = sharedBuffer->pointer();
3298 }
3299 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3300 }
3301 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003302 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 client->heap()->dump("AudioTrack");
3304 return;
3305 }
3306 } else {
3307 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003308 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 new(mCblk) audio_track_cblk_t();
3310 // clear all buffers
3311 mCblk->frameCount = frameCount;
3312 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003313 mChannelCount = channelCount;
3314 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003315 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3316 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3317 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003318 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 mCblk->flags = CBLK_UNDERRUN_ON;
3320 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 }
3322}
3323
3324AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3325{
Glenn Kastena0d68332012-01-27 16:47:15 -08003326 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003327 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003329 } else {
3330 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 }
3332 }
3333 mCblkMemory.clear(); // and free the shared memory
3334 if (mClient != NULL) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003335 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003336 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3337 mClient.clear();
3338 }
3339}
3340
3341void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3342{
Glenn Kastene0feee32011-12-13 11:53:26 -08003343 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 mFrameCount = buffer->frameCount;
3345 step();
3346 buffer->frameCount = 0;
3347}
3348
3349bool AudioFlinger::ThreadBase::TrackBase::step() {
3350 bool result;
3351 audio_track_cblk_t* cblk = this->cblk();
3352
3353 result = cblk->stepServer(mFrameCount);
3354 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003355 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 mFlags |= STEPSERVER_FAILED;
3357 }
3358 return result;
3359}
3360
3361void AudioFlinger::ThreadBase::TrackBase::reset() {
3362 audio_track_cblk_t* cblk = this->cblk();
3363
3364 cblk->user = 0;
3365 cblk->server = 0;
3366 cblk->userBase = 0;
3367 cblk->serverBase = 0;
3368 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003369 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370}
3371
3372sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3373{
3374 return mCblkMemory;
3375}
3376
3377int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3378 return (int)mCblk->sampleRate;
3379}
3380
3381int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003382 return (const int)mChannelCount;
3383}
3384
3385uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3386 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387}
3388
3389void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3390 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003391 size_t frameSize = cblk->frameSize;
3392 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3393 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394
3395 // Check validity of returned pointer in case the track control block would have been corrupted.
3396 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003397 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003398 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 -07003399 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003401 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003402 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 }
3404
3405 return bufferStart;
3406}
3407
3408// ----------------------------------------------------------------------------
3409
3410// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3411AudioFlinger::PlaybackThread::Track::Track(
3412 const wp<ThreadBase>& thread,
3413 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003414 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003416 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003417 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 int frameCount,
3419 const sp<IMemory>& sharedBuffer,
3420 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003421 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003422 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3423 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424{
3425 if (mCblk != NULL) {
3426 sp<ThreadBase> baseThread = thread.promote();
3427 if (baseThread != 0) {
3428 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3429 mName = playbackThread->getTrackName_l();
3430 mMainBuffer = playbackThread->mixBuffer();
3431 }
Steve Block3856b092011-10-20 11:56:00 +01003432 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003434 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 mStreamType = streamType;
3437 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3438 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003439 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003440 }
3441}
3442
3443AudioFlinger::PlaybackThread::Track::~Track()
3444{
Steve Block3856b092011-10-20 11:56:00 +01003445 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003446 sp<ThreadBase> thread = mThread.promote();
3447 if (thread != 0) {
3448 Mutex::Autolock _l(thread->mLock);
3449 mState = TERMINATED;
3450 }
3451}
3452
3453void AudioFlinger::PlaybackThread::Track::destroy()
3454{
3455 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3456 // by removing it from mTracks vector, so there is a risk that this Tracks's
3457 // desctructor is called. As the destructor needs to lock mLock,
3458 // we must acquire a strong reference on this Track before locking mLock
3459 // here so that the destructor is called only when exiting this function.
3460 // On the other hand, as long as Track::destroy() is only called by
3461 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3462 // this Track with its member mTrack.
3463 sp<Track> keep(this);
3464 { // scope for mLock
3465 sp<ThreadBase> thread = mThread.promote();
3466 if (thread != 0) {
3467 if (!isOutputTrack()) {
3468 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003469 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003470 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003471 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003472
3473 // to track the speaker usage
3474 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 }
3476 AudioSystem::releaseOutput(thread->id());
3477 }
3478 Mutex::Autolock _l(thread->mLock);
3479 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3480 playbackThread->destroyTrack_l(this);
3481 }
3482 }
3483}
3484
3485void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3486{
Glenn Kasten83d86532012-01-17 14:39:34 -08003487 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003488 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 -07003489 mName - AudioMixer::TRACK0,
3490 (mClient == NULL) ? getpid() : mClient->pid(),
3491 mStreamType,
3492 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003493 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 mSessionId,
3495 mFrameCount,
3496 mState,
3497 mMute,
3498 mFillingUpStatus,
3499 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003500 vlr & 0xFFFF,
3501 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 mCblk->server,
3503 mCblk->user,
3504 (int)mMainBuffer,
3505 (int)mAuxBuffer);
3506}
3507
3508status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3509{
3510 audio_track_cblk_t* cblk = this->cblk();
3511 uint32_t framesReady;
3512 uint32_t framesReq = buffer->frameCount;
3513
3514 // Check if last stepServer failed, try to step now
3515 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3516 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003517 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3519 }
3520
3521 framesReady = cblk->framesReady();
3522
Glenn Kastenf6b16782011-12-15 09:51:17 -08003523 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 uint32_t s = cblk->server;
3525 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3526
3527 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3528 if (framesReq > framesReady) {
3529 framesReq = framesReady;
3530 }
3531 if (s + framesReq > bufferEnd) {
3532 framesReq = bufferEnd - s;
3533 }
3534
3535 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003536 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537
3538 buffer->frameCount = framesReq;
3539 return NO_ERROR;
3540 }
3541
3542getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003543 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003545 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 return NOT_ENOUGH_DATA;
3547}
3548
3549bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003550 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551
3552 if (mCblk->framesReady() >= mCblk->frameCount ||
3553 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3554 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003555 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 return true;
3557 }
3558 return false;
3559}
3560
3561status_t AudioFlinger::PlaybackThread::Track::start()
3562{
3563 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003564 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003565 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 sp<ThreadBase> thread = mThread.promote();
3567 if (thread != 0) {
3568 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003569 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 // here the track could be either new, or restarted
3571 // in both cases "unstop" the track
3572 if (mState == PAUSED) {
3573 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003574 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 } else {
3576 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003577 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 }
3579
3580 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3581 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003582 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003583 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003584 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003586
3587 // to track the speaker usage
3588 if (status == NO_ERROR) {
3589 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3590 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 }
3592 if (status == NO_ERROR) {
3593 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3594 playbackThread->addTrack_l(this);
3595 } else {
3596 mState = state;
3597 }
3598 } else {
3599 status = BAD_VALUE;
3600 }
3601 return status;
3602}
3603
3604void AudioFlinger::PlaybackThread::Track::stop()
3605{
Steve Block3856b092011-10-20 11:56:00 +01003606 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 sp<ThreadBase> thread = mThread.promote();
3608 if (thread != 0) {
3609 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003610 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 if (mState > STOPPED) {
3612 mState = STOPPED;
3613 // If the track is not active (PAUSED and buffers full), flush buffers
3614 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3615 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3616 reset();
3617 }
Steve Block3856b092011-10-20 11:56:00 +01003618 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 }
3620 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3621 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003622 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003623 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003624 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003626
3627 // to track the speaker usage
3628 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629 }
3630 }
3631}
3632
3633void AudioFlinger::PlaybackThread::Track::pause()
3634{
Steve Block3856b092011-10-20 11:56:00 +01003635 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 sp<ThreadBase> thread = mThread.promote();
3637 if (thread != 0) {
3638 Mutex::Autolock _l(thread->mLock);
3639 if (mState == ACTIVE || mState == RESUMING) {
3640 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003641 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 if (!isOutputTrack()) {
3643 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003644 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003645 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003646 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003648
3649 // to track the speaker usage
3650 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651 }
3652 }
3653 }
3654}
3655
3656void AudioFlinger::PlaybackThread::Track::flush()
3657{
Steve Block3856b092011-10-20 11:56:00 +01003658 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 sp<ThreadBase> thread = mThread.promote();
3660 if (thread != 0) {
3661 Mutex::Autolock _l(thread->mLock);
3662 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3663 return;
3664 }
3665 // No point remaining in PAUSED state after a flush => go to
3666 // STOPPED state
3667 mState = STOPPED;
3668
Eric Laurent38ccae22011-03-28 18:37:07 -07003669 // do not reset the track if it is still in the process of being stopped or paused.
3670 // this will be done by prepareTracks_l() when the track is stopped.
3671 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3672 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3673 reset();
3674 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675 }
3676}
3677
3678void AudioFlinger::PlaybackThread::Track::reset()
3679{
3680 // Do not reset twice to avoid discarding data written just after a flush and before
3681 // the audioflinger thread detects the track is stopped.
3682 if (!mResetDone) {
3683 TrackBase::reset();
3684 // Force underrun condition to avoid false underrun callback until first data is
3685 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003686 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3687 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 mFillingUpStatus = FS_FILLING;
3689 mResetDone = true;
3690 }
3691}
3692
3693void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3694{
3695 mMute = muted;
3696}
3697
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3699{
3700 status_t status = DEAD_OBJECT;
3701 sp<ThreadBase> thread = mThread.promote();
3702 if (thread != 0) {
3703 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3704 status = playbackThread->attachAuxEffect(this, EffectId);
3705 }
3706 return status;
3707}
3708
3709void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3710{
3711 mAuxEffectId = EffectId;
3712 mAuxBuffer = buffer;
3713}
3714
3715// ----------------------------------------------------------------------------
3716
3717// RecordTrack constructor must be called with AudioFlinger::mLock held
3718AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3719 const wp<ThreadBase>& thread,
3720 const sp<Client>& client,
3721 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003722 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003723 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003724 int frameCount,
3725 uint32_t flags,
3726 int sessionId)
3727 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003728 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 mOverflow(false)
3730{
3731 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003732 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003733 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003734 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003735 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003736 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737 } else {
3738 mCblk->frameSize = sizeof(int8_t);
3739 }
3740 }
3741}
3742
3743AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3744{
3745 sp<ThreadBase> thread = mThread.promote();
3746 if (thread != 0) {
3747 AudioSystem::releaseInput(thread->id());
3748 }
3749}
3750
3751status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3752{
3753 audio_track_cblk_t* cblk = this->cblk();
3754 uint32_t framesAvail;
3755 uint32_t framesReq = buffer->frameCount;
3756
3757 // Check if last stepServer failed, try to step now
3758 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3759 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003760 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3762 }
3763
3764 framesAvail = cblk->framesAvailable_l();
3765
Glenn Kastenf6b16782011-12-15 09:51:17 -08003766 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 uint32_t s = cblk->server;
3768 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3769
3770 if (framesReq > framesAvail) {
3771 framesReq = framesAvail;
3772 }
3773 if (s + framesReq > bufferEnd) {
3774 framesReq = bufferEnd - s;
3775 }
3776
3777 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003778 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779
3780 buffer->frameCount = framesReq;
3781 return NO_ERROR;
3782 }
3783
3784getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003785 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 buffer->frameCount = 0;
3787 return NOT_ENOUGH_DATA;
3788}
3789
3790status_t AudioFlinger::RecordThread::RecordTrack::start()
3791{
3792 sp<ThreadBase> thread = mThread.promote();
3793 if (thread != 0) {
3794 RecordThread *recordThread = (RecordThread *)thread.get();
3795 return recordThread->start(this);
3796 } else {
3797 return BAD_VALUE;
3798 }
3799}
3800
3801void AudioFlinger::RecordThread::RecordTrack::stop()
3802{
3803 sp<ThreadBase> thread = mThread.promote();
3804 if (thread != 0) {
3805 RecordThread *recordThread = (RecordThread *)thread.get();
3806 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003807 TrackBase::reset();
3808 // Force overerrun condition to avoid false overrun callback until first data is
3809 // read from buffer
3810 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003811 }
3812}
3813
3814void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3815{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003816 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817 (mClient == NULL) ? getpid() : mClient->pid(),
3818 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003819 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 mSessionId,
3821 mFrameCount,
3822 mState,
3823 mCblk->sampleRate,
3824 mCblk->server,
3825 mCblk->user);
3826}
3827
3828
3829// ----------------------------------------------------------------------------
3830
3831AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3832 const wp<ThreadBase>& thread,
3833 DuplicatingThread *sourceThread,
3834 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003835 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003836 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003838 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 mActive(false), mSourceThread(sourceThread)
3840{
3841
3842 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3843 if (mCblk != NULL) {
3844 mCblk->flags |= CBLK_DIRECTION_OUT;
3845 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003846 mOutBuffer.frameCount = 0;
3847 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003848 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003849 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3850 mCblk, mBuffer, mCblk->buffers,
3851 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003853 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003854 }
3855}
3856
3857AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3858{
3859 clearBufferQueue();
3860}
3861
3862status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3863{
3864 status_t status = Track::start();
3865 if (status != NO_ERROR) {
3866 return status;
3867 }
3868
3869 mActive = true;
3870 mRetryCount = 127;
3871 return status;
3872}
3873
3874void AudioFlinger::PlaybackThread::OutputTrack::stop()
3875{
3876 Track::stop();
3877 clearBufferQueue();
3878 mOutBuffer.frameCount = 0;
3879 mActive = false;
3880}
3881
3882bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3883{
3884 Buffer *pInBuffer;
3885 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003886 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 bool outputBufferFull = false;
3888 inBuffer.frameCount = frames;
3889 inBuffer.i16 = data;
3890
3891 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3892
3893 if (!mActive && frames != 0) {
3894 start();
3895 sp<ThreadBase> thread = mThread.promote();
3896 if (thread != 0) {
3897 MixerThread *mixerThread = (MixerThread *)thread.get();
3898 if (mCblk->frameCount > frames){
3899 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3900 uint32_t startFrames = (mCblk->frameCount - frames);
3901 pInBuffer = new Buffer;
3902 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3903 pInBuffer->frameCount = startFrames;
3904 pInBuffer->i16 = pInBuffer->mBuffer;
3905 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3906 mBufferQueue.add(pInBuffer);
3907 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003908 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 }
3910 }
3911 }
3912 }
3913
3914 while (waitTimeLeftMs) {
3915 // First write pending buffers, then new data
3916 if (mBufferQueue.size()) {
3917 pInBuffer = mBufferQueue.itemAt(0);
3918 } else {
3919 pInBuffer = &inBuffer;
3920 }
3921
3922 if (pInBuffer->frameCount == 0) {
3923 break;
3924 }
3925
3926 if (mOutBuffer.frameCount == 0) {
3927 mOutBuffer.frameCount = pInBuffer->frameCount;
3928 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003929 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003930 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931 outputBufferFull = true;
3932 break;
3933 }
3934 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3935 if (waitTimeLeftMs >= waitTimeMs) {
3936 waitTimeLeftMs -= waitTimeMs;
3937 } else {
3938 waitTimeLeftMs = 0;
3939 }
3940 }
3941
3942 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3943 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3944 mCblk->stepUser(outFrames);
3945 pInBuffer->frameCount -= outFrames;
3946 pInBuffer->i16 += outFrames * channelCount;
3947 mOutBuffer.frameCount -= outFrames;
3948 mOutBuffer.i16 += outFrames * channelCount;
3949
3950 if (pInBuffer->frameCount == 0) {
3951 if (mBufferQueue.size()) {
3952 mBufferQueue.removeAt(0);
3953 delete [] pInBuffer->mBuffer;
3954 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003955 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 } else {
3957 break;
3958 }
3959 }
3960 }
3961
3962 // If we could not write all frames, allocate a buffer and queue it for next time.
3963 if (inBuffer.frameCount) {
3964 sp<ThreadBase> thread = mThread.promote();
3965 if (thread != 0 && !thread->standby()) {
3966 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3967 pInBuffer = new Buffer;
3968 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3969 pInBuffer->frameCount = inBuffer.frameCount;
3970 pInBuffer->i16 = pInBuffer->mBuffer;
3971 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3972 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003973 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003975 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 }
3977 }
3978 }
3979
3980 // Calling write() with a 0 length buffer, means that no more data will be written:
3981 // If no more buffers are pending, fill output track buffer to make sure it is started
3982 // by output mixer.
3983 if (frames == 0 && mBufferQueue.size() == 0) {
3984 if (mCblk->user < mCblk->frameCount) {
3985 frames = mCblk->frameCount - mCblk->user;
3986 pInBuffer = new Buffer;
3987 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3988 pInBuffer->frameCount = frames;
3989 pInBuffer->i16 = pInBuffer->mBuffer;
3990 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3991 mBufferQueue.add(pInBuffer);
3992 } else if (mActive) {
3993 stop();
3994 }
3995 }
3996
3997 return outputBufferFull;
3998}
3999
4000status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4001{
4002 int active;
4003 status_t result;
4004 audio_track_cblk_t* cblk = mCblk;
4005 uint32_t framesReq = buffer->frameCount;
4006
Steve Block3856b092011-10-20 11:56:00 +01004007// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 buffer->frameCount = 0;
4009
4010 uint32_t framesAvail = cblk->framesAvailable();
4011
4012
4013 if (framesAvail == 0) {
4014 Mutex::Autolock _l(cblk->lock);
4015 goto start_loop_here;
4016 while (framesAvail == 0) {
4017 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004018 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004019 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004020 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004021 }
4022 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4023 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004024 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004025 }
4026 // read the server count again
4027 start_loop_here:
4028 framesAvail = cblk->framesAvailable_l();
4029 }
4030 }
4031
4032// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004033// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034// }
4035
4036 if (framesReq > framesAvail) {
4037 framesReq = framesAvail;
4038 }
4039
4040 uint32_t u = cblk->user;
4041 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4042
4043 if (u + framesReq > bufferEnd) {
4044 framesReq = bufferEnd - u;
4045 }
4046
4047 buffer->frameCount = framesReq;
4048 buffer->raw = (void *)cblk->buffer(u);
4049 return NO_ERROR;
4050}
4051
4052
4053void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4054{
4055 size_t size = mBufferQueue.size();
4056 Buffer *pBuffer;
4057
4058 for (size_t i = 0; i < size; i++) {
4059 pBuffer = mBufferQueue.itemAt(i);
4060 delete [] pBuffer->mBuffer;
4061 delete pBuffer;
4062 }
4063 mBufferQueue.clear();
4064}
4065
4066// ----------------------------------------------------------------------------
4067
4068AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4069 : RefBase(),
4070 mAudioFlinger(audioFlinger),
4071 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4072 mPid(pid)
4073{
4074 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4075}
4076
4077// Client destructor must be called with AudioFlinger::mLock held
4078AudioFlinger::Client::~Client()
4079{
4080 mAudioFlinger->removeClient_l(mPid);
4081}
4082
Glenn Kasten435dbe62012-01-30 10:15:48 -08004083sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084{
4085 return mMemoryDealer;
4086}
4087
4088// ----------------------------------------------------------------------------
4089
4090AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4091 const sp<IAudioFlingerClient>& client,
4092 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004093 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094{
4095}
4096
4097AudioFlinger::NotificationClient::~NotificationClient()
4098{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099}
4100
4101void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4102{
4103 sp<NotificationClient> keep(this);
4104 {
4105 mAudioFlinger->removeNotificationClient(mPid);
4106 }
4107}
4108
4109// ----------------------------------------------------------------------------
4110
4111AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4112 : BnAudioTrack(),
4113 mTrack(track)
4114{
4115}
4116
4117AudioFlinger::TrackHandle::~TrackHandle() {
4118 // just stop the track on deletion, associated resources
4119 // will be freed from the main thread once all pending buffers have
4120 // been played. Unless it's not in the active track list, in which
4121 // case we free everything now...
4122 mTrack->destroy();
4123}
4124
Glenn Kasten90716c52012-01-26 13:40:12 -08004125sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4126 return mTrack->getCblk();
4127}
4128
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129status_t AudioFlinger::TrackHandle::start() {
4130 return mTrack->start();
4131}
4132
4133void AudioFlinger::TrackHandle::stop() {
4134 mTrack->stop();
4135}
4136
4137void AudioFlinger::TrackHandle::flush() {
4138 mTrack->flush();
4139}
4140
4141void AudioFlinger::TrackHandle::mute(bool e) {
4142 mTrack->mute(e);
4143}
4144
4145void AudioFlinger::TrackHandle::pause() {
4146 mTrack->pause();
4147}
4148
Mathias Agopian65ab4712010-07-14 17:59:35 -07004149status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4150{
4151 return mTrack->attachAuxEffect(EffectId);
4152}
4153
4154status_t AudioFlinger::TrackHandle::onTransact(
4155 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4156{
4157 return BnAudioTrack::onTransact(code, data, reply, flags);
4158}
4159
4160// ----------------------------------------------------------------------------
4161
4162sp<IAudioRecord> AudioFlinger::openRecord(
4163 pid_t pid,
4164 int input,
4165 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004166 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004167 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 int frameCount,
4169 uint32_t flags,
4170 int *sessionId,
4171 status_t *status)
4172{
4173 sp<RecordThread::RecordTrack> recordTrack;
4174 sp<RecordHandle> recordHandle;
4175 sp<Client> client;
4176 wp<Client> wclient;
4177 status_t lStatus;
4178 RecordThread *thread;
4179 size_t inFrameCount;
4180 int lSessionId;
4181
4182 // check calling permissions
4183 if (!recordingAllowed()) {
4184 lStatus = PERMISSION_DENIED;
4185 goto Exit;
4186 }
4187
4188 // add client to list
4189 { // scope for mLock
4190 Mutex::Autolock _l(mLock);
4191 thread = checkRecordThread_l(input);
4192 if (thread == NULL) {
4193 lStatus = BAD_VALUE;
4194 goto Exit;
4195 }
4196
4197 wclient = mClients.valueFor(pid);
4198 if (wclient != NULL) {
4199 client = wclient.promote();
4200 } else {
4201 client = new Client(this, pid);
4202 mClients.add(pid, client);
4203 }
4204
4205 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004206 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 lSessionId = *sessionId;
4208 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004209 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 if (sessionId != NULL) {
4211 *sessionId = lSessionId;
4212 }
4213 }
4214 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004215 recordTrack = thread->createRecordTrack_l(client,
4216 sampleRate,
4217 format,
4218 channelMask,
4219 frameCount,
4220 flags,
4221 lSessionId,
4222 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004224 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4226 // destructor is called by the TrackBase destructor with mLock held
4227 client.clear();
4228 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 goto Exit;
4230 }
4231
4232 // return to handle to client
4233 recordHandle = new RecordHandle(recordTrack);
4234 lStatus = NO_ERROR;
4235
4236Exit:
4237 if (status) {
4238 *status = lStatus;
4239 }
4240 return recordHandle;
4241}
4242
4243// ----------------------------------------------------------------------------
4244
4245AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4246 : BnAudioRecord(),
4247 mRecordTrack(recordTrack)
4248{
4249}
4250
4251AudioFlinger::RecordHandle::~RecordHandle() {
4252 stop();
4253}
4254
Glenn Kasten90716c52012-01-26 13:40:12 -08004255sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4256 return mRecordTrack->getCblk();
4257}
4258
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004260 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 return mRecordTrack->start();
4262}
4263
4264void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004265 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004266 mRecordTrack->stop();
4267}
4268
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269status_t AudioFlinger::RecordHandle::onTransact(
4270 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4271{
4272 return BnAudioRecord::onTransact(code, data, reply, flags);
4273}
4274
4275// ----------------------------------------------------------------------------
4276
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004277AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4278 AudioStreamIn *input,
4279 uint32_t sampleRate,
4280 uint32_t channels,
4281 int id,
4282 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004283 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004284 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4285 // mRsmpInIndex and mInputBytes set by readInputParameters()
4286 mReqChannelCount(popcount(channels)),
4287 mReqSampleRate(sampleRate)
4288 // mBytesRead is only meaningful while active, and so is cleared in start()
4289 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004291 snprintf(mName, kNameLength, "AudioIn_%d", id);
4292
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 readInputParameters();
4294}
4295
4296
4297AudioFlinger::RecordThread::~RecordThread()
4298{
4299 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004300 delete mResampler;
4301 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302}
4303
4304void AudioFlinger::RecordThread::onFirstRef()
4305{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004306 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307}
4308
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004309status_t AudioFlinger::RecordThread::readyToRun()
4310{
4311 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004312 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004313 return status;
4314}
4315
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316bool AudioFlinger::RecordThread::threadLoop()
4317{
4318 AudioBufferProvider::Buffer buffer;
4319 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004320 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321
Eric Laurent44d98482010-09-30 16:12:31 -07004322 nsecs_t lastWarning = 0;
4323
Eric Laurentfeb0db62011-07-22 09:04:31 -07004324 acquireWakeLock();
4325
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 // start recording
4327 while (!exitPending()) {
4328
4329 processConfigEvents();
4330
4331 { // scope for mLock
4332 Mutex::Autolock _l(mLock);
4333 checkForNewParameters_l();
4334 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4335 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004336 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337 mStandby = true;
4338 }
4339
4340 if (exitPending()) break;
4341
Eric Laurentfeb0db62011-07-22 09:04:31 -07004342 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004343 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 // go to sleep
4345 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004346 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004347 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 continue;
4349 }
4350 if (mActiveTrack != 0) {
4351 if (mActiveTrack->mState == TrackBase::PAUSING) {
4352 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004353 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004354 mStandby = true;
4355 }
4356 mActiveTrack.clear();
4357 mStartStopCond.broadcast();
4358 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4359 if (mReqChannelCount != mActiveTrack->channelCount()) {
4360 mActiveTrack.clear();
4361 mStartStopCond.broadcast();
4362 } else if (mBytesRead != 0) {
4363 // record start succeeds only if first read from audio input
4364 // succeeds
4365 if (mBytesRead > 0) {
4366 mActiveTrack->mState = TrackBase::ACTIVE;
4367 } else {
4368 mActiveTrack.clear();
4369 }
4370 mStartStopCond.broadcast();
4371 }
4372 mStandby = false;
4373 }
4374 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004375 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376 }
4377
4378 if (mActiveTrack != 0) {
4379 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4380 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004381 unlockEffectChains(effectChains);
4382 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383 continue;
4384 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004385 for (size_t i = 0; i < effectChains.size(); i ++) {
4386 effectChains[i]->process_l();
4387 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004388
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004390 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004392 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 // no resampling
4394 while (framesOut) {
4395 size_t framesIn = mFrameCount - mRsmpInIndex;
4396 if (framesIn) {
4397 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4398 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4399 if (framesIn > framesOut)
4400 framesIn = framesOut;
4401 mRsmpInIndex += framesIn;
4402 framesOut -= framesIn;
4403 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004404 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 memcpy(dst, src, framesIn * mFrameSize);
4406 } else {
4407 int16_t *src16 = (int16_t *)src;
4408 int16_t *dst16 = (int16_t *)dst;
4409 if (mChannelCount == 1) {
4410 while (framesIn--) {
4411 *dst16++ = *src16;
4412 *dst16++ = *src16++;
4413 }
4414 } else {
4415 while (framesIn--) {
4416 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4417 src16 += 2;
4418 }
4419 }
4420 }
4421 }
4422 if (framesOut && mFrameCount == mRsmpInIndex) {
4423 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004424 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004425 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 framesOut = 0;
4427 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004428 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 mRsmpInIndex = 0;
4430 }
4431 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004432 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4434 // Force input into standby so that it tries to
4435 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004436 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004437 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 }
4439 mRsmpInIndex = mFrameCount;
4440 framesOut = 0;
4441 buffer.frameCount = 0;
4442 }
4443 }
4444 }
4445 } else {
4446 // resampling
4447
4448 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4449 // alter output frame count as if we were expecting stereo samples
4450 if (mChannelCount == 1 && mReqChannelCount == 1) {
4451 framesOut >>= 1;
4452 }
4453 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4454 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4455 // are 32 bit aligned which should be always true.
4456 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004457 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 // the resampler always outputs stereo samples: do post stereo to mono conversion
4459 int16_t *src = (int16_t *)mRsmpOutBuffer;
4460 int16_t *dst = buffer.i16;
4461 while (framesOut--) {
4462 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4463 src += 2;
4464 }
4465 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004466 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467 }
4468
4469 }
4470 mActiveTrack->releaseBuffer(&buffer);
4471 mActiveTrack->overflow();
4472 }
4473 // client isn't retrieving buffers fast enough
4474 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004475 if (!mActiveTrack->setOverflow()) {
4476 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004477 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004478 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004479 lastWarning = now;
4480 }
4481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 // Release the processor for a while before asking for a new buffer.
4483 // This will give the application more chance to read from the buffer and
4484 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004485 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004486 }
4487 }
Eric Laurentec437d82011-07-26 20:54:46 -07004488 // enable changes in effect chain
4489 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004490 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 }
4492
4493 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004494 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 }
4496 mActiveTrack.clear();
4497
4498 mStartStopCond.broadcast();
4499
Eric Laurentfeb0db62011-07-22 09:04:31 -07004500 releaseWakeLock();
4501
Steve Block3856b092011-10-20 11:56:00 +01004502 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 return false;
4504}
4505
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004506
4507sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4508 const sp<AudioFlinger::Client>& client,
4509 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004510 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004511 int channelMask,
4512 int frameCount,
4513 uint32_t flags,
4514 int sessionId,
4515 status_t *status)
4516{
4517 sp<RecordTrack> track;
4518 status_t lStatus;
4519
4520 lStatus = initCheck();
4521 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004522 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004523 goto Exit;
4524 }
4525
4526 { // scope for mLock
4527 Mutex::Autolock _l(mLock);
4528
4529 track = new RecordTrack(this, client, sampleRate,
4530 format, channelMask, frameCount, flags, sessionId);
4531
4532 if (track->getCblk() == NULL) {
4533 lStatus = NO_MEMORY;
4534 goto Exit;
4535 }
4536
4537 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004538 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4539 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004540 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004541 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4542 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004543 }
4544 lStatus = NO_ERROR;
4545
4546Exit:
4547 if (status) {
4548 *status = lStatus;
4549 }
4550 return track;
4551}
4552
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4554{
Steve Block3856b092011-10-20 11:56:00 +01004555 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 sp <ThreadBase> strongMe = this;
4557 status_t status = NO_ERROR;
4558 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004559 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004560 if (mActiveTrack != 0) {
4561 if (recordTrack != mActiveTrack.get()) {
4562 status = -EBUSY;
4563 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4564 mActiveTrack->mState = TrackBase::ACTIVE;
4565 }
4566 return status;
4567 }
4568
4569 recordTrack->mState = TrackBase::IDLE;
4570 mActiveTrack = recordTrack;
4571 mLock.unlock();
4572 status_t status = AudioSystem::startInput(mId);
4573 mLock.lock();
4574 if (status != NO_ERROR) {
4575 mActiveTrack.clear();
4576 return status;
4577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 mRsmpInIndex = mFrameCount;
4579 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004580 if (mResampler != NULL) {
4581 mResampler->reset();
4582 }
4583 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004585 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004586 mWaitWorkCV.signal();
4587 // do not wait for mStartStopCond if exiting
4588 if (mExiting) {
4589 mActiveTrack.clear();
4590 status = INVALID_OPERATION;
4591 goto startError;
4592 }
4593 mStartStopCond.wait(mLock);
4594 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004595 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 status = BAD_VALUE;
4597 goto startError;
4598 }
Steve Block3856b092011-10-20 11:56:00 +01004599 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004600 return status;
4601 }
4602startError:
4603 AudioSystem::stopInput(mId);
4604 return status;
4605}
4606
4607void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004608 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 sp <ThreadBase> strongMe = this;
4610 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004611 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4613 mActiveTrack->mState = TrackBase::PAUSING;
4614 // do not wait for mStartStopCond if exiting
4615 if (mExiting) {
4616 return;
4617 }
4618 mStartStopCond.wait(mLock);
4619 // if we have been restarted, recordTrack == mActiveTrack.get() here
4620 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4621 mLock.unlock();
4622 AudioSystem::stopInput(mId);
4623 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004624 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625 }
4626 }
4627 }
4628}
4629
4630status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4631{
4632 const size_t SIZE = 256;
4633 char buffer[SIZE];
4634 String8 result;
4635 pid_t pid = 0;
4636
4637 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4638 result.append(buffer);
4639
4640 if (mActiveTrack != 0) {
4641 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004642 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 mActiveTrack->dump(buffer, SIZE);
4644 result.append(buffer);
4645
4646 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4647 result.append(buffer);
4648 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4649 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004650 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 result.append(buffer);
4652 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4653 result.append(buffer);
4654 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4655 result.append(buffer);
4656
4657
4658 } else {
4659 result.append("No record client\n");
4660 }
4661 write(fd, result.string(), result.size());
4662
4663 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004664 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665
4666 return NO_ERROR;
4667}
4668
4669status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4670{
4671 size_t framesReq = buffer->frameCount;
4672 size_t framesReady = mFrameCount - mRsmpInIndex;
4673 int channelCount;
4674
4675 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004676 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004678 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4680 // Force input into standby so that it tries to
4681 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004682 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004683 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004684 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004685 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 buffer->frameCount = 0;
4687 return NOT_ENOUGH_DATA;
4688 }
4689 mRsmpInIndex = 0;
4690 framesReady = mFrameCount;
4691 }
4692
4693 if (framesReq > framesReady) {
4694 framesReq = framesReady;
4695 }
4696
4697 if (mChannelCount == 1 && mReqChannelCount == 2) {
4698 channelCount = 1;
4699 } else {
4700 channelCount = 2;
4701 }
4702 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4703 buffer->frameCount = framesReq;
4704 return NO_ERROR;
4705}
4706
4707void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4708{
4709 mRsmpInIndex += buffer->frameCount;
4710 buffer->frameCount = 0;
4711}
4712
4713bool AudioFlinger::RecordThread::checkForNewParameters_l()
4714{
4715 bool reconfig = false;
4716
4717 while (!mNewParameters.isEmpty()) {
4718 status_t status = NO_ERROR;
4719 String8 keyValuePair = mNewParameters[0];
4720 AudioParameter param = AudioParameter(keyValuePair);
4721 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004722 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 int reqSamplingRate = mReqSampleRate;
4724 int reqChannelCount = mReqChannelCount;
4725
4726 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4727 reqSamplingRate = value;
4728 reconfig = true;
4729 }
4730 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004731 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732 reconfig = true;
4733 }
4734 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004735 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 reconfig = true;
4737 }
4738 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4739 // do not accept frame count changes if tracks are open as the track buffer
4740 // size depends on frame count and correct behavior would not be garantied
4741 // if frame count is changed after track creation
4742 if (mActiveTrack != 0) {
4743 status = INVALID_OPERATION;
4744 } else {
4745 reconfig = true;
4746 }
4747 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004748 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4749 // forward device change to effects that have requested to be
4750 // aware of attached audio device.
4751 for (size_t i = 0; i < mEffectChains.size(); i++) {
4752 mEffectChains[i]->setDevice_l(value);
4753 }
4754 // store input device and output device but do not forward output device to audio HAL.
4755 // Note that status is ignored by the caller for output device
4756 // (see AudioFlinger::setParameters()
4757 if (value & AUDIO_DEVICE_OUT_ALL) {
4758 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4759 status = BAD_VALUE;
4760 } else {
4761 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004762 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4763 if (mTrack != NULL) {
4764 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004765 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004766 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4767 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4768 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004769 }
4770 mDevice |= (uint32_t)value;
4771 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004773 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004775 mInput->stream->common.standby(&mInput->stream->common);
4776 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777 }
4778 if (reconfig) {
4779 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004780 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004781 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004782 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4783 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004784 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004785 status = NO_ERROR;
4786 }
4787 if (status == NO_ERROR) {
4788 readInputParameters();
4789 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4790 }
4791 }
4792 }
4793
4794 mNewParameters.removeAt(0);
4795
4796 mParamStatus = status;
4797 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004798 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4799 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004800 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004801 }
4802 return reconfig;
4803}
4804
4805String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4806{
Dima Zavinfce7a472011-04-19 22:30:36 -07004807 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004808 String8 out_s8 = String8();
4809
4810 Mutex::Autolock _l(mLock);
4811 if (initCheck() != NO_ERROR) {
4812 return out_s8;
4813 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004814
Dima Zavin799a70e2011-04-18 16:57:27 -07004815 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004816 out_s8 = String8(s);
4817 free(s);
4818 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819}
4820
4821void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4822 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004823 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004824
4825 switch (event) {
4826 case AudioSystem::INPUT_OPENED:
4827 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004828 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004829 desc.samplingRate = mSampleRate;
4830 desc.format = mFormat;
4831 desc.frameCount = mFrameCount;
4832 desc.latency = 0;
4833 param2 = &desc;
4834 break;
4835
4836 case AudioSystem::INPUT_CLOSED:
4837 default:
4838 break;
4839 }
4840 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4841}
4842
4843void AudioFlinger::RecordThread::readInputParameters()
4844{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004845 delete mRsmpInBuffer;
4846 // mRsmpInBuffer is always assigned a new[] below
4847 delete mRsmpOutBuffer;
4848 mRsmpOutBuffer = NULL;
4849 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004850 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004851
Dima Zavin799a70e2011-04-18 16:57:27 -07004852 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004853 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4854 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004855 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004856 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004857 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004858 mFrameCount = mInputBytes / mFrameSize;
4859 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4860
4861 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4862 {
4863 int channelCount;
4864 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4865 // stereo to mono post process as the resampler always outputs stereo.
4866 if (mChannelCount == 1 && mReqChannelCount == 2) {
4867 channelCount = 1;
4868 } else {
4869 channelCount = 2;
4870 }
4871 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4872 mResampler->setSampleRate(mSampleRate);
4873 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4874 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4875
4876 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4877 if (mChannelCount == 1 && mReqChannelCount == 1) {
4878 mFrameCount >>= 1;
4879 }
4880
4881 }
4882 mRsmpInIndex = mFrameCount;
4883}
4884
4885unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4886{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004887 Mutex::Autolock _l(mLock);
4888 if (initCheck() != NO_ERROR) {
4889 return 0;
4890 }
4891
Dima Zavin799a70e2011-04-18 16:57:27 -07004892 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893}
4894
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004895uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4896{
4897 Mutex::Autolock _l(mLock);
4898 uint32_t result = 0;
4899 if (getEffectChain_l(sessionId) != 0) {
4900 result = EFFECT_SESSION;
4901 }
4902
4903 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4904 result |= TRACK_SESSION;
4905 }
4906
4907 return result;
4908}
4909
Eric Laurent59bd0da2011-08-01 09:52:20 -07004910AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4911{
4912 Mutex::Autolock _l(mLock);
4913 return mTrack;
4914}
4915
Glenn Kastenaed850d2012-01-26 09:46:34 -08004916AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004917{
4918 Mutex::Autolock _l(mLock);
4919 return mInput;
4920}
4921
4922AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4923{
4924 Mutex::Autolock _l(mLock);
4925 AudioStreamIn *input = mInput;
4926 mInput = NULL;
4927 return input;
4928}
4929
4930// this method must always be called either with ThreadBase mLock held or inside the thread loop
4931audio_stream_t* AudioFlinger::RecordThread::stream()
4932{
4933 if (mInput == NULL) {
4934 return NULL;
4935 }
4936 return &mInput->stream->common;
4937}
4938
4939
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940// ----------------------------------------------------------------------------
4941
4942int AudioFlinger::openOutput(uint32_t *pDevices,
4943 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004944 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945 uint32_t *pChannels,
4946 uint32_t *pLatencyMs,
4947 uint32_t flags)
4948{
4949 status_t status;
4950 PlaybackThread *thread = NULL;
4951 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4952 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004953 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954 uint32_t channels = pChannels ? *pChannels : 0;
4955 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004956 audio_stream_out_t *outStream;
4957 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958
Steve Block3856b092011-10-20 11:56:00 +01004959 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960 pDevices ? *pDevices : 0,
4961 samplingRate,
4962 format,
4963 channels,
4964 flags);
4965
4966 if (pDevices == NULL || *pDevices == 0) {
4967 return 0;
4968 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004969
Mathias Agopian65ab4712010-07-14 17:59:35 -07004970 Mutex::Autolock _l(mLock);
4971
Dima Zavin799a70e2011-04-18 16:57:27 -07004972 outHwDev = findSuitableHwDev_l(*pDevices);
4973 if (outHwDev == NULL)
4974 return 0;
4975
Glenn Kasten58f30212012-01-12 12:27:51 -08004976 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004977 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004978 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004979 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 samplingRate,
4981 format,
4982 channels,
4983 status);
4984
4985 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004986 if (outStream != NULL) {
4987 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004988 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004989
Dima Zavinfce7a472011-04-19 22:30:36 -07004990 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4991 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4992 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004994 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 } else {
4996 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004997 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998 }
4999 mPlaybackThreads.add(id, thread);
5000
Glenn Kastena0d68332012-01-27 16:47:15 -08005001 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5002 if (pFormat != NULL) *pFormat = format;
5003 if (pChannels != NULL) *pChannels = channels;
5004 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005
5006 // notify client processes of the new output creation
5007 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5008 return id;
5009 }
5010
5011 return 0;
5012}
5013
5014int AudioFlinger::openDuplicateOutput(int output1, int output2)
5015{
5016 Mutex::Autolock _l(mLock);
5017 MixerThread *thread1 = checkMixerThread_l(output1);
5018 MixerThread *thread2 = checkMixerThread_l(output2);
5019
5020 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005021 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005022 return 0;
5023 }
5024
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005025 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5027 thread->addOutputTrack(thread2);
5028 mPlaybackThreads.add(id, thread);
5029 // notify client processes of the new output creation
5030 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5031 return id;
5032}
5033
5034status_t AudioFlinger::closeOutput(int output)
5035{
5036 // keep strong reference on the playback thread so that
5037 // it is not destroyed while exit() is executed
5038 sp <PlaybackThread> thread;
5039 {
5040 Mutex::Autolock _l(mLock);
5041 thread = checkPlaybackThread_l(output);
5042 if (thread == NULL) {
5043 return BAD_VALUE;
5044 }
5045
Steve Block3856b092011-10-20 11:56:00 +01005046 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005048 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005050 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5052 dupThread->removeOutputTrack((MixerThread *)thread.get());
5053 }
5054 }
5055 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005056 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005057 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5058 mPlaybackThreads.removeItem(output);
5059 }
5060 thread->exit();
5061
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005062 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005063 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005064 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005065 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005066 out->hwDev->close_output_stream(out->hwDev, out->stream);
5067 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005068 }
5069 return NO_ERROR;
5070}
5071
5072status_t AudioFlinger::suspendOutput(int output)
5073{
5074 Mutex::Autolock _l(mLock);
5075 PlaybackThread *thread = checkPlaybackThread_l(output);
5076
5077 if (thread == NULL) {
5078 return BAD_VALUE;
5079 }
5080
Steve Block3856b092011-10-20 11:56:00 +01005081 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 thread->suspend();
5083
5084 return NO_ERROR;
5085}
5086
5087status_t AudioFlinger::restoreOutput(int output)
5088{
5089 Mutex::Autolock _l(mLock);
5090 PlaybackThread *thread = checkPlaybackThread_l(output);
5091
5092 if (thread == NULL) {
5093 return BAD_VALUE;
5094 }
5095
Steve Block3856b092011-10-20 11:56:00 +01005096 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005097
5098 thread->restore();
5099
5100 return NO_ERROR;
5101}
5102
5103int AudioFlinger::openInput(uint32_t *pDevices,
5104 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005105 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005107 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108{
5109 status_t status;
5110 RecordThread *thread = NULL;
5111 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005112 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 uint32_t channels = pChannels ? *pChannels : 0;
5114 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005115 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005117 audio_stream_in_t *inStream;
5118 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005119
5120 if (pDevices == NULL || *pDevices == 0) {
5121 return 0;
5122 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005123
Mathias Agopian65ab4712010-07-14 17:59:35 -07005124 Mutex::Autolock _l(mLock);
5125
Dima Zavin799a70e2011-04-18 16:57:27 -07005126 inHwDev = findSuitableHwDev_l(*pDevices);
5127 if (inHwDev == NULL)
5128 return 0;
5129
Glenn Kasten58f30212012-01-12 12:27:51 -08005130 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005131 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005132 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005133 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005134 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005135 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136 samplingRate,
5137 format,
5138 channels,
5139 acoustics,
5140 status);
5141
5142 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5143 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5144 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005145 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005146 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005148 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005149 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005150 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005151 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005152 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005153 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 }
5155
Dima Zavin799a70e2011-04-18 16:57:27 -07005156 if (inStream != NULL) {
5157 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5158
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005159 int id = nextUniqueId();
5160 // Start record thread
5161 // RecorThread require both input and output device indication to forward to audio
5162 // pre processing modules
5163 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5164 thread = new RecordThread(this,
5165 input,
5166 reqSamplingRate,
5167 reqChannels,
5168 id,
5169 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005171 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005172 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5173 if (pFormat != NULL) *pFormat = format;
5174 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175
Dima Zavin799a70e2011-04-18 16:57:27 -07005176 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177
5178 // notify client processes of the new input creation
5179 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5180 return id;
5181 }
5182
5183 return 0;
5184}
5185
5186status_t AudioFlinger::closeInput(int input)
5187{
5188 // keep strong reference on the record thread so that
5189 // it is not destroyed while exit() is executed
5190 sp <RecordThread> thread;
5191 {
5192 Mutex::Autolock _l(mLock);
5193 thread = checkRecordThread_l(input);
5194 if (thread == NULL) {
5195 return BAD_VALUE;
5196 }
5197
Steve Block3856b092011-10-20 11:56:00 +01005198 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005199 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5201 mRecordThreads.removeItem(input);
5202 }
5203 thread->exit();
5204
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005205 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005206 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005207 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005208 in->hwDev->close_input_stream(in->hwDev, in->stream);
5209 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005210
5211 return NO_ERROR;
5212}
5213
Glenn Kastenfff6d712012-01-12 16:38:12 -08005214status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005215{
5216 Mutex::Autolock _l(mLock);
5217 MixerThread *dstThread = checkMixerThread_l(output);
5218 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005219 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005220 return BAD_VALUE;
5221 }
5222
Steve Block3856b092011-10-20 11:56:00 +01005223 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005224 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5225
Eric Laurent9f6530f2011-08-30 10:18:54 -07005226 dstThread->setStreamValid(stream, true);
5227
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5229 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5230 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005231 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005232 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005233 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005234 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005235 }
Eric Laurentde070132010-07-13 04:45:46 -07005236 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005237
5238 return NO_ERROR;
5239}
5240
5241
5242int AudioFlinger::newAudioSessionId()
5243{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005244 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005245}
5246
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005247void AudioFlinger::acquireAudioSessionId(int audioSession)
5248{
5249 Mutex::Autolock _l(mLock);
5250 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005251 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005252 int num = mAudioSessionRefs.size();
5253 for (int i = 0; i< num; i++) {
5254 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5255 if (ref->sessionid == audioSession && ref->pid == caller) {
5256 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005257 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005258 return;
5259 }
5260 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005261 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5262 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005263}
5264
5265void AudioFlinger::releaseAudioSessionId(int audioSession)
5266{
5267 Mutex::Autolock _l(mLock);
5268 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005269 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005270 int num = mAudioSessionRefs.size();
5271 for (int i = 0; i< num; i++) {
5272 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5273 if (ref->sessionid == audioSession && ref->pid == caller) {
5274 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005275 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005276 if (ref->cnt == 0) {
5277 mAudioSessionRefs.removeAt(i);
5278 delete ref;
5279 purgeStaleEffects_l();
5280 }
5281 return;
5282 }
5283 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005284 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005285}
5286
5287void AudioFlinger::purgeStaleEffects_l() {
5288
Steve Block3856b092011-10-20 11:56:00 +01005289 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005290
5291 Vector< sp<EffectChain> > chains;
5292
5293 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5294 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5295 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5296 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005297 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5298 chains.push(ec);
5299 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005300 }
5301 }
5302 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5303 sp<RecordThread> t = mRecordThreads.valueAt(i);
5304 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5305 sp<EffectChain> ec = t->mEffectChains[j];
5306 chains.push(ec);
5307 }
5308 }
5309
5310 for (size_t i = 0; i < chains.size(); i++) {
5311 sp<EffectChain> ec = chains[i];
5312 int sessionid = ec->sessionId();
5313 sp<ThreadBase> t = ec->mThread.promote();
5314 if (t == 0) {
5315 continue;
5316 }
5317 size_t numsessionrefs = mAudioSessionRefs.size();
5318 bool found = false;
5319 for (size_t k = 0; k < numsessionrefs; k++) {
5320 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5321 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005322 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005323 sessionid, ref->pid, ref->cnt);
5324 found = true;
5325 break;
5326 }
5327 }
5328 if (!found) {
5329 // remove all effects from the chain
5330 while (ec->mEffects.size()) {
5331 sp<EffectModule> effect = ec->mEffects[0];
5332 effect->unPin();
5333 Mutex::Autolock _l (t->mLock);
5334 t->removeEffect_l(effect);
5335 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5336 sp<EffectHandle> handle = effect->mHandles[j].promote();
5337 if (handle != 0) {
5338 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005339 if (handle->mHasControl && handle->mEnabled) {
5340 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5341 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005342 }
5343 }
5344 AudioSystem::unregisterEffect(effect->id());
5345 }
5346 }
5347 }
5348 return;
5349}
5350
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5352AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5353{
5354 PlaybackThread *thread = NULL;
5355 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5356 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5357 }
5358 return thread;
5359}
5360
5361// checkMixerThread_l() must be called with AudioFlinger::mLock held
5362AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5363{
5364 PlaybackThread *thread = checkPlaybackThread_l(output);
5365 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005366 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367 thread = NULL;
5368 }
5369 }
5370 return (MixerThread *)thread;
5371}
5372
5373// checkRecordThread_l() must be called with AudioFlinger::mLock held
5374AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5375{
5376 RecordThread *thread = NULL;
5377 if (mRecordThreads.indexOfKey(input) >= 0) {
5378 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5379 }
5380 return thread;
5381}
5382
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005383uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005385 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386}
5387
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005388AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5389{
5390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5391 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005392 AudioStreamOut *output = thread->getOutput();
5393 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005394 return thread;
5395 }
5396 }
5397 return NULL;
5398}
5399
5400uint32_t AudioFlinger::primaryOutputDevice_l()
5401{
5402 PlaybackThread *thread = primaryPlaybackThread_l();
5403
5404 if (thread == NULL) {
5405 return 0;
5406 }
5407
5408 return thread->device();
5409}
5410
5411
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412// ----------------------------------------------------------------------------
5413// Effect management
5414// ----------------------------------------------------------------------------
5415
5416
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5418{
5419 Mutex::Autolock _l(mLock);
5420 return EffectQueryNumberEffects(numEffects);
5421}
5422
5423status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5424{
5425 Mutex::Autolock _l(mLock);
5426 return EffectQueryEffect(index, descriptor);
5427}
5428
5429status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5430{
5431 Mutex::Autolock _l(mLock);
5432 return EffectGetDescriptor(pUuid, descriptor);
5433}
5434
5435
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5437 effect_descriptor_t *pDesc,
5438 const sp<IEffectClient>& effectClient,
5439 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005440 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 int sessionId,
5442 status_t *status,
5443 int *id,
5444 int *enabled)
5445{
5446 status_t lStatus = NO_ERROR;
5447 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 effect_descriptor_t desc;
5449 sp<Client> client;
5450 wp<Client> wclient;
5451
Steve Block3856b092011-10-20 11:56:00 +01005452 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005453 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454
5455 if (pDesc == NULL) {
5456 lStatus = BAD_VALUE;
5457 goto Exit;
5458 }
5459
Eric Laurent84e9a102010-09-23 16:10:16 -07005460 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005461 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005462 lStatus = PERMISSION_DENIED;
5463 goto Exit;
5464 }
5465
Dima Zavinfce7a472011-04-19 22:30:36 -07005466 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005467 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005468 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005469 lStatus = PERMISSION_DENIED;
5470 goto Exit;
5471 }
5472
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005473 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005474 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005475 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005476 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005477 lStatus = BAD_VALUE;
5478 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005479 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005480 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005481 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005482 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005483 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005484 }
5485 }
5486
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 {
5488 Mutex::Autolock _l(mLock);
5489
Mathias Agopian65ab4712010-07-14 17:59:35 -07005490
5491 if (!EffectIsNullUuid(&pDesc->uuid)) {
5492 // if uuid is specified, request effect descriptor
5493 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5494 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005495 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 goto Exit;
5497 }
5498 } else {
5499 // if uuid is not specified, look for an available implementation
5500 // of the required type in effect factory
5501 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005502 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 lStatus = BAD_VALUE;
5504 goto Exit;
5505 }
5506 uint32_t numEffects = 0;
5507 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005508 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 bool found = false;
5510
5511 lStatus = EffectQueryNumberEffects(&numEffects);
5512 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005513 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 goto Exit;
5515 }
5516 for (uint32_t i = 0; i < numEffects; i++) {
5517 lStatus = EffectQueryEffect(i, &desc);
5518 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005519 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 continue;
5521 }
5522 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5523 // If matching type found save effect descriptor. If the session is
5524 // 0 and the effect is not auxiliary, continue enumeration in case
5525 // an auxiliary version of this effect type is available
5526 found = true;
5527 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005528 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5530 break;
5531 }
5532 }
5533 }
5534 if (!found) {
5535 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005536 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537 goto Exit;
5538 }
5539 // For same effect type, chose auxiliary version over insert version if
5540 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005541 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5543 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5544 }
5545 }
5546
5547 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005548 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5550 lStatus = INVALID_OPERATION;
5551 goto Exit;
5552 }
5553
Eric Laurent59255e42011-07-27 19:49:51 -07005554 // check recording permission for visualizer
5555 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5556 !recordingAllowed()) {
5557 lStatus = PERMISSION_DENIED;
5558 goto Exit;
5559 }
5560
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 // return effect descriptor
5562 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5563
5564 // If output is not specified try to find a matching audio session ID in one of the
5565 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005566 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5567 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005568 // Note: io is never 0 when creating an effect on an input
5569 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005570 // look for the thread where the specified audio session is present
5571 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5572 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005573 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005574 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005575 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005576 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005577 if (io == 0) {
5578 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5579 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5580 io = mRecordThreads.keyAt(i);
5581 break;
5582 }
5583 }
5584 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005585 // If no output thread contains the requested session ID, default to
5586 // first output. The effect chain will be moved to the correct output
5587 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005588 if (io == 0 && mPlaybackThreads.size()) {
5589 io = mPlaybackThreads.keyAt(0);
5590 }
Steve Block3856b092011-10-20 11:56:00 +01005591 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005592 }
5593 ThreadBase *thread = checkRecordThread_l(io);
5594 if (thread == NULL) {
5595 thread = checkPlaybackThread_l(io);
5596 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005597 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005598 lStatus = BAD_VALUE;
5599 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005602
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 wclient = mClients.valueFor(pid);
5604
5605 if (wclient != NULL) {
5606 client = wclient.promote();
5607 } else {
5608 client = new Client(this, pid);
5609 mClients.add(pid, client);
5610 }
5611
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005612 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005613 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5614 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 if (handle != 0 && id != NULL) {
5616 *id = handle->id();
5617 }
5618 }
5619
5620Exit:
5621 if(status) {
5622 *status = lStatus;
5623 }
5624 return handle;
5625}
5626
Eric Laurent59255e42011-07-27 19:49:51 -07005627status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005628{
Steve Block3856b092011-10-20 11:56:00 +01005629 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005630 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005631 Mutex::Autolock _l(mLock);
5632 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005633 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005634 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635 }
Eric Laurentde070132010-07-13 04:45:46 -07005636 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5637 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005638 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005639 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005640 }
Eric Laurentde070132010-07-13 04:45:46 -07005641 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5642 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005643 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005644 return BAD_VALUE;
5645 }
5646
5647 Mutex::Autolock _dl(dstThread->mLock);
5648 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005649 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005650
Mathias Agopian65ab4712010-07-14 17:59:35 -07005651 return NO_ERROR;
5652}
5653
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005654// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005655status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005656 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005657 AudioFlinger::PlaybackThread *dstThread,
5658 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005659{
Steve Block3856b092011-10-20 11:56:00 +01005660 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005661 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005662
Eric Laurent59255e42011-07-27 19:49:51 -07005663 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005664 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005665 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005666 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005667 return INVALID_OPERATION;
5668 }
5669
Eric Laurent39e94f82010-07-28 01:32:47 -07005670 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005671 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005672 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005673 // removed.
5674 srcThread->removeEffectChain_l(chain);
5675
5676 // transfer all effects one by one so that new effect chain is created on new thread with
5677 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005678 int dstOutput = dstThread->id();
5679 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005680 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005681 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5682 while (effect != 0) {
5683 srcThread->removeEffect_l(effect);
5684 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005685 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5686 if (effect->state() == EffectModule::ACTIVE ||
5687 effect->state() == EffectModule::STOPPING) {
5688 effect->start();
5689 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005690 // if the move request is not received from audio policy manager, the effect must be
5691 // re-registered with the new strategy and output
5692 if (dstChain == 0) {
5693 dstChain = effect->chain().promote();
5694 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005695 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005696 srcThread->addEffect_l(effect);
5697 return NO_INIT;
5698 }
5699 strategy = dstChain->strategy();
5700 }
5701 if (reRegister) {
5702 AudioSystem::unregisterEffect(effect->id());
5703 AudioSystem::registerEffect(&effect->desc(),
5704 dstOutput,
5705 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005706 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005707 effect->id());
5708 }
Eric Laurentde070132010-07-13 04:45:46 -07005709 effect = chain->getEffectFromId_l(0);
5710 }
5711
5712 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713}
5714
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005715
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005717sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 const sp<AudioFlinger::Client>& client,
5719 const sp<IEffectClient>& effectClient,
5720 int32_t priority,
5721 int sessionId,
5722 effect_descriptor_t *desc,
5723 int *enabled,
5724 status_t *status
5725 )
5726{
5727 sp<EffectModule> effect;
5728 sp<EffectHandle> handle;
5729 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005731 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 bool effectCreated = false;
5733 bool effectRegistered = false;
5734
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005735 lStatus = initCheck();
5736 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005737 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 goto Exit;
5739 }
5740
5741 // Do not allow effects with session ID 0 on direct output or duplicating threads
5742 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005743 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005744 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005745 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 lStatus = BAD_VALUE;
5747 goto Exit;
5748 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005749 // Only Pre processor effects are allowed on input threads and only on input threads
5750 if ((mType == RECORD &&
5751 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5752 (mType != RECORD &&
5753 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005754 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005755 desc->name, desc->flags, mType);
5756 lStatus = BAD_VALUE;
5757 goto Exit;
5758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005759
Steve Block3856b092011-10-20 11:56:00 +01005760 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761
5762 { // scope for mLock
5763 Mutex::Autolock _l(mLock);
5764
5765 // check for existing effect chain with the requested audio session
5766 chain = getEffectChain_l(sessionId);
5767 if (chain == 0) {
5768 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005769 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 chain = new EffectChain(this, sessionId);
5771 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005772 chain->setStrategy(getStrategyForSession_l(sessionId));
5773 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005775 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 }
5777
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005778 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779
5780 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005781 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005783 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 if (lStatus != NO_ERROR) {
5785 goto Exit;
5786 }
5787 effectRegistered = true;
5788 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005789 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 lStatus = effect->status();
5791 if (lStatus != NO_ERROR) {
5792 goto Exit;
5793 }
Eric Laurentcab11242010-07-15 12:50:15 -07005794 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005795 if (lStatus != NO_ERROR) {
5796 goto Exit;
5797 }
5798 effectCreated = true;
5799
5800 effect->setDevice(mDevice);
5801 effect->setMode(mAudioFlinger->getMode());
5802 }
5803 // create effect handle and connect it to effect module
5804 handle = new EffectHandle(effect, client, effectClient, priority);
5805 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005806 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 *enabled = (int)effect->isEnabled();
5808 }
5809 }
5810
5811Exit:
5812 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005813 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005814 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005815 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005816 }
5817 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005818 AudioSystem::unregisterEffect(effect->id());
5819 }
5820 if (chainCreated) {
5821 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 }
5823 handle.clear();
5824 }
5825
5826 if(status) {
5827 *status = lStatus;
5828 }
5829 return handle;
5830}
5831
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005832sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5833{
5834 sp<EffectModule> effect;
5835
5836 sp<EffectChain> chain = getEffectChain_l(sessionId);
5837 if (chain != 0) {
5838 effect = chain->getEffectFromId_l(effectId);
5839 }
5840 return effect;
5841}
5842
Eric Laurentde070132010-07-13 04:45:46 -07005843// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5844// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005845status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005846{
5847 // check for existing effect chain with the requested audio session
5848 int sessionId = effect->sessionId();
5849 sp<EffectChain> chain = getEffectChain_l(sessionId);
5850 bool chainCreated = false;
5851
5852 if (chain == 0) {
5853 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005854 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005855 chain = new EffectChain(this, sessionId);
5856 addEffectChain_l(chain);
5857 chain->setStrategy(getStrategyForSession_l(sessionId));
5858 chainCreated = true;
5859 }
Steve Block3856b092011-10-20 11:56:00 +01005860 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005861
5862 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005863 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005864 this, effect->desc().name, chain.get());
5865 return BAD_VALUE;
5866 }
5867
5868 status_t status = chain->addEffect_l(effect);
5869 if (status != NO_ERROR) {
5870 if (chainCreated) {
5871 removeEffectChain_l(chain);
5872 }
5873 return status;
5874 }
5875
5876 effect->setDevice(mDevice);
5877 effect->setMode(mAudioFlinger->getMode());
5878 return NO_ERROR;
5879}
5880
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005881void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005882
Steve Block3856b092011-10-20 11:56:00 +01005883 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005885 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5886 detachAuxEffect_l(effect->id());
5887 }
5888
5889 sp<EffectChain> chain = effect->chain().promote();
5890 if (chain != 0) {
5891 // remove effect chain if removing last effect
5892 if (chain->removeEffect_l(effect) == 0) {
5893 removeEffectChain_l(chain);
5894 }
5895 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005896 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005897 }
5898}
5899
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005900void AudioFlinger::ThreadBase::lockEffectChains_l(
5901 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5902{
5903 effectChains = mEffectChains;
5904 for (size_t i = 0; i < mEffectChains.size(); i++) {
5905 mEffectChains[i]->lock();
5906 }
5907}
5908
5909void AudioFlinger::ThreadBase::unlockEffectChains(
5910 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5911{
5912 for (size_t i = 0; i < effectChains.size(); i++) {
5913 effectChains[i]->unlock();
5914 }
5915}
5916
5917sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5918{
5919 Mutex::Autolock _l(mLock);
5920 return getEffectChain_l(sessionId);
5921}
5922
5923sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5924{
5925 sp<EffectChain> chain;
5926
5927 size_t size = mEffectChains.size();
5928 for (size_t i = 0; i < size; i++) {
5929 if (mEffectChains[i]->sessionId() == sessionId) {
5930 chain = mEffectChains[i];
5931 break;
5932 }
5933 }
5934 return chain;
5935}
5936
Glenn Kastenf78aee72012-01-04 11:00:47 -08005937void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005938{
5939 Mutex::Autolock _l(mLock);
5940 size_t size = mEffectChains.size();
5941 for (size_t i = 0; i < size; i++) {
5942 mEffectChains[i]->setMode_l(mode);
5943 }
5944}
5945
5946void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005947 const wp<EffectHandle>& handle,
5948 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005949
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005951 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 // delete the effect module if removing last handle on it
5953 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005954 if (!effect->isPinned() || unpiniflast) {
5955 removeEffect_l(effect);
5956 AudioSystem::unregisterEffect(effect->id());
5957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 }
5959}
5960
5961status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5962{
5963 int session = chain->sessionId();
5964 int16_t *buffer = mMixBuffer;
5965 bool ownsBuffer = false;
5966
Steve Block3856b092011-10-20 11:56:00 +01005967 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 if (session > 0) {
5969 // Only one effect chain can be present in direct output thread and it uses
5970 // the mix buffer as input
5971 if (mType != DIRECT) {
5972 size_t numSamples = mFrameCount * mChannelCount;
5973 buffer = new int16_t[numSamples];
5974 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005975 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 ownsBuffer = true;
5977 }
5978
5979 // Attach all tracks with same session ID to this chain.
5980 for (size_t i = 0; i < mTracks.size(); ++i) {
5981 sp<Track> track = mTracks[i];
5982 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005983 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005985 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986 }
5987 }
5988
5989 // indicate all active tracks in the chain
5990 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5991 sp<Track> track = mActiveTracks[i].promote();
5992 if (track == 0) continue;
5993 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005994 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005995 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 }
5997 }
5998 }
5999
6000 chain->setInBuffer(buffer, ownsBuffer);
6001 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006002 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006003 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006004 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6005 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006007 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6008 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006009 // Effect chain for other sessions are inserted at beginning of effect
6010 // chains list to be processed before output mix effects. Relative order between other
6011 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012 size_t size = mEffectChains.size();
6013 size_t i = 0;
6014 for (i = 0; i < size; i++) {
6015 if (mEffectChains[i]->sessionId() < session) break;
6016 }
6017 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006018 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019
6020 return NO_ERROR;
6021}
6022
6023size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6024{
6025 int session = chain->sessionId();
6026
Steve Block3856b092011-10-20 11:56:00 +01006027 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028
6029 for (size_t i = 0; i < mEffectChains.size(); i++) {
6030 if (chain == mEffectChains[i]) {
6031 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006032 // detach all active tracks from the chain
6033 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6034 sp<Track> track = mActiveTracks[i].promote();
6035 if (track == 0) continue;
6036 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006037 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006038 chain.get(), session);
6039 chain->decActiveTrackCnt();
6040 }
6041 }
6042
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 // detach all tracks with same session ID from this chain
6044 for (size_t i = 0; i < mTracks.size(); ++i) {
6045 sp<Track> track = mTracks[i];
6046 if (session == track->sessionId()) {
6047 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006048 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 }
6050 }
Eric Laurentde070132010-07-13 04:45:46 -07006051 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006052 }
6053 }
6054 return mEffectChains.size();
6055}
6056
Eric Laurentde070132010-07-13 04:45:46 -07006057status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6058 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006059{
6060 Mutex::Autolock _l(mLock);
6061 return attachAuxEffect_l(track, EffectId);
6062}
6063
Eric Laurentde070132010-07-13 04:45:46 -07006064status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6065 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066{
6067 status_t status = NO_ERROR;
6068
6069 if (EffectId == 0) {
6070 track->setAuxBuffer(0, NULL);
6071 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006072 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6073 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 if (effect != 0) {
6075 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6076 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6077 } else {
6078 status = INVALID_OPERATION;
6079 }
6080 } else {
6081 status = BAD_VALUE;
6082 }
6083 }
6084 return status;
6085}
6086
6087void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6088{
6089 for (size_t i = 0; i < mTracks.size(); ++i) {
6090 sp<Track> track = mTracks[i];
6091 if (track->auxEffectId() == effectId) {
6092 attachAuxEffect_l(track, 0);
6093 }
6094 }
6095}
6096
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006097status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6098{
6099 // only one chain per input thread
6100 if (mEffectChains.size() != 0) {
6101 return INVALID_OPERATION;
6102 }
Steve Block3856b092011-10-20 11:56:00 +01006103 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006104
6105 chain->setInBuffer(NULL);
6106 chain->setOutBuffer(NULL);
6107
Eric Laurent59255e42011-07-27 19:49:51 -07006108 checkSuspendOnAddEffectChain_l(chain);
6109
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006110 mEffectChains.add(chain);
6111
6112 return NO_ERROR;
6113}
6114
6115size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6116{
Steve Block3856b092011-10-20 11:56:00 +01006117 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006118 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006119 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6120 chain.get(), mEffectChains.size(), this);
6121 if (mEffectChains.size() == 1) {
6122 mEffectChains.removeAt(0);
6123 }
6124 return 0;
6125}
6126
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127// ----------------------------------------------------------------------------
6128// EffectModule implementation
6129// ----------------------------------------------------------------------------
6130
6131#undef LOG_TAG
6132#define LOG_TAG "AudioFlinger::EffectModule"
6133
6134AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6135 const wp<AudioFlinger::EffectChain>& chain,
6136 effect_descriptor_t *desc,
6137 int id,
6138 int sessionId)
6139 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006140 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006141{
Steve Block3856b092011-10-20 11:56:00 +01006142 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 int lStatus;
6144 sp<ThreadBase> thread = mThread.promote();
6145 if (thread == 0) {
6146 return;
6147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148
6149 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6150
6151 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153
6154 if (mStatus != NO_ERROR) {
6155 return;
6156 }
6157 lStatus = init();
6158 if (lStatus < 0) {
6159 mStatus = lStatus;
6160 goto Error;
6161 }
6162
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006163 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6164 mPinned = true;
6165 }
Steve Block3856b092011-10-20 11:56:00 +01006166 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167 return;
6168Error:
6169 EffectRelease(mEffectInterface);
6170 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006171 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172}
6173
6174AudioFlinger::EffectModule::~EffectModule()
6175{
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006178 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6179 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6180 sp<ThreadBase> thread = mThread.promote();
6181 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006182 audio_stream_t *stream = thread->stream();
6183 if (stream != NULL) {
6184 stream->remove_audio_effect(stream, mEffectInterface);
6185 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006186 }
6187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 // release effect engine
6189 EffectRelease(mEffectInterface);
6190 }
6191}
6192
Glenn Kasten435dbe62012-01-30 10:15:48 -08006193status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194{
6195 status_t status;
6196
6197 Mutex::Autolock _l(mLock);
6198 // First handle in mHandles has highest priority and controls the effect module
6199 int priority = handle->priority();
6200 size_t size = mHandles.size();
6201 sp<EffectHandle> h;
6202 size_t i;
6203 for (i = 0; i < size; i++) {
6204 h = mHandles[i].promote();
6205 if (h == 0) continue;
6206 if (h->priority() <= priority) break;
6207 }
6208 // if inserted in first place, move effect control from previous owner to this handle
6209 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006210 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006212 enabled = h->enabled();
6213 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 }
Eric Laurent59255e42011-07-27 19:49:51 -07006215 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 status = NO_ERROR;
6217 } else {
6218 status = ALREADY_EXISTS;
6219 }
Steve Block3856b092011-10-20 11:56:00 +01006220 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 mHandles.insertAt(handle, i);
6222 return status;
6223}
6224
6225size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6226{
6227 Mutex::Autolock _l(mLock);
6228 size_t size = mHandles.size();
6229 size_t i;
6230 for (i = 0; i < size; i++) {
6231 if (mHandles[i] == handle) break;
6232 }
6233 if (i == size) {
6234 return size;
6235 }
Steve Block3856b092011-10-20 11:56:00 +01006236 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006237
6238 bool enabled = false;
6239 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006240 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006241 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006242 enabled = hdl->enabled();
6243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 mHandles.removeAt(i);
6245 size = mHandles.size();
6246 // if removed from first place, move effect control from this handle to next in line
6247 if (i == 0 && size != 0) {
6248 sp<EffectHandle> h = mHandles[0].promote();
6249 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006250 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 }
6252 }
6253
Eric Laurentec437d82011-07-26 20:54:46 -07006254 // Prevent calls to process() and other functions on effect interface from now on.
6255 // The effect engine will be released by the destructor when the last strong reference on
6256 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006257 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006258 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006259 }
6260
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 return size;
6262}
6263
Eric Laurent59255e42011-07-27 19:49:51 -07006264sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6265{
6266 Mutex::Autolock _l(mLock);
6267 sp<EffectHandle> handle;
6268 if (mHandles.size() != 0) {
6269 handle = mHandles[0].promote();
6270 }
6271 return handle;
6272}
6273
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006274void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275{
Steve Block3856b092011-10-20 11:56:00 +01006276 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 // keep a strong reference on this EffectModule to avoid calling the
6278 // destructor before we exit
6279 sp<EffectModule> keep(this);
6280 {
6281 sp<ThreadBase> thread = mThread.promote();
6282 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006283 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 }
6285 }
6286}
6287
6288void AudioFlinger::EffectModule::updateState() {
6289 Mutex::Autolock _l(mLock);
6290
6291 switch (mState) {
6292 case RESTART:
6293 reset_l();
6294 // FALL THROUGH
6295
6296 case STARTING:
6297 // clear auxiliary effect input buffer for next accumulation
6298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6299 memset(mConfig.inputCfg.buffer.raw,
6300 0,
6301 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6302 }
6303 start_l();
6304 mState = ACTIVE;
6305 break;
6306 case STOPPING:
6307 stop_l();
6308 mDisableWaitCnt = mMaxDisableWaitCnt;
6309 mState = STOPPED;
6310 break;
6311 case STOPPED:
6312 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6313 // turn off sequence.
6314 if (--mDisableWaitCnt == 0) {
6315 reset_l();
6316 mState = IDLE;
6317 }
6318 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006319 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006320 break;
6321 }
6322}
6323
6324void AudioFlinger::EffectModule::process()
6325{
6326 Mutex::Autolock _l(mLock);
6327
Eric Laurentec437d82011-07-26 20:54:46 -07006328 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 mConfig.inputCfg.buffer.raw == NULL ||
6330 mConfig.outputCfg.buffer.raw == NULL) {
6331 return;
6332 }
6333
Eric Laurent8f45bd72010-08-31 13:50:07 -07006334 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6336 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006337 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006339 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 }
6341
6342 // do the actual processing in the effect engine
6343 int ret = (*mEffectInterface)->process(mEffectInterface,
6344 &mConfig.inputCfg.buffer,
6345 &mConfig.outputCfg.buffer);
6346
6347 // force transition to IDLE state when engine is ready
6348 if (mState == STOPPED && ret == -ENODATA) {
6349 mDisableWaitCnt = 1;
6350 }
6351
6352 // clear auxiliary effect input buffer for next accumulation
6353 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006354 memset(mConfig.inputCfg.buffer.raw, 0,
6355 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 }
6357 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006358 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6359 // If an insert effect is idle and input buffer is different from output buffer,
6360 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006362 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006363 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6364 int16_t *in = mConfig.inputCfg.buffer.s16;
6365 int16_t *out = mConfig.outputCfg.buffer.s16;
6366 for (size_t i = 0; i < frameCnt; i++) {
6367 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 }
6370 }
6371}
6372
6373void AudioFlinger::EffectModule::reset_l()
6374{
6375 if (mEffectInterface == NULL) {
6376 return;
6377 }
6378 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6379}
6380
6381status_t AudioFlinger::EffectModule::configure()
6382{
6383 uint32_t channels;
6384 if (mEffectInterface == NULL) {
6385 return NO_INIT;
6386 }
6387
6388 sp<ThreadBase> thread = mThread.promote();
6389 if (thread == 0) {
6390 return DEAD_OBJECT;
6391 }
6392
6393 // TODO: handle configuration of effects replacing track process
6394 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006395 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006397 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 }
6399
6400 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006401 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 } else {
6403 mConfig.inputCfg.channels = channels;
6404 }
6405 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006406 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6407 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006408 mConfig.inputCfg.samplingRate = thread->sampleRate();
6409 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6410 mConfig.inputCfg.bufferProvider.cookie = NULL;
6411 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6412 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6413 mConfig.outputCfg.bufferProvider.cookie = NULL;
6414 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6415 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6416 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6417 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006418 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006419 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420 // - in other sessions:
6421 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6422 // other effect: overwrites output buffer: input buffer == output buffer
6423 // Auxiliary effect:
6424 // accumulates in output buffer: input buffer != output buffer
6425 // Therefore: accumulate <=> input buffer != output buffer
6426 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6427 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6428 } else {
6429 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6430 }
6431 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6432 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6433 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6434 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6435
Steve Block3856b092011-10-20 11:56:00 +01006436 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006437 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6438
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006440 uint32_t size = sizeof(int);
6441 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006442 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006443 sizeof(effect_config_t),
6444 &mConfig,
6445 &size,
6446 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447 if (status == 0) {
6448 status = cmdStatus;
6449 }
6450
6451 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6452 (1000 * mConfig.outputCfg.buffer.frameCount);
6453
6454 return status;
6455}
6456
6457status_t AudioFlinger::EffectModule::init()
6458{
6459 Mutex::Autolock _l(mLock);
6460 if (mEffectInterface == NULL) {
6461 return NO_INIT;
6462 }
6463 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006464 uint32_t size = sizeof(status_t);
6465 status_t status = (*mEffectInterface)->command(mEffectInterface,
6466 EFFECT_CMD_INIT,
6467 0,
6468 NULL,
6469 &size,
6470 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471 if (status == 0) {
6472 status = cmdStatus;
6473 }
6474 return status;
6475}
6476
Eric Laurentec35a142011-10-05 17:42:25 -07006477status_t AudioFlinger::EffectModule::start()
6478{
6479 Mutex::Autolock _l(mLock);
6480 return start_l();
6481}
6482
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483status_t AudioFlinger::EffectModule::start_l()
6484{
6485 if (mEffectInterface == NULL) {
6486 return NO_INIT;
6487 }
6488 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006489 uint32_t size = sizeof(status_t);
6490 status_t status = (*mEffectInterface)->command(mEffectInterface,
6491 EFFECT_CMD_ENABLE,
6492 0,
6493 NULL,
6494 &size,
6495 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496 if (status == 0) {
6497 status = cmdStatus;
6498 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006499 if (status == 0 &&
6500 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6501 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6502 sp<ThreadBase> thread = mThread.promote();
6503 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006504 audio_stream_t *stream = thread->stream();
6505 if (stream != NULL) {
6506 stream->add_audio_effect(stream, mEffectInterface);
6507 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006508 }
6509 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510 return status;
6511}
6512
Eric Laurentec437d82011-07-26 20:54:46 -07006513status_t AudioFlinger::EffectModule::stop()
6514{
6515 Mutex::Autolock _l(mLock);
6516 return stop_l();
6517}
6518
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519status_t AudioFlinger::EffectModule::stop_l()
6520{
6521 if (mEffectInterface == NULL) {
6522 return NO_INIT;
6523 }
6524 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006525 uint32_t size = sizeof(status_t);
6526 status_t status = (*mEffectInterface)->command(mEffectInterface,
6527 EFFECT_CMD_DISABLE,
6528 0,
6529 NULL,
6530 &size,
6531 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 if (status == 0) {
6533 status = cmdStatus;
6534 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006535 if (status == 0 &&
6536 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6537 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6538 sp<ThreadBase> thread = mThread.promote();
6539 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006540 audio_stream_t *stream = thread->stream();
6541 if (stream != NULL) {
6542 stream->remove_audio_effect(stream, mEffectInterface);
6543 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006544 }
6545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 return status;
6547}
6548
Eric Laurent25f43952010-07-28 05:40:18 -07006549status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6550 uint32_t cmdSize,
6551 void *pCmdData,
6552 uint32_t *replySize,
6553 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554{
6555 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006556// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557
Eric Laurentec437d82011-07-26 20:54:46 -07006558 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 return NO_INIT;
6560 }
Eric Laurent25f43952010-07-28 05:40:18 -07006561 status_t status = (*mEffectInterface)->command(mEffectInterface,
6562 cmdCode,
6563 cmdSize,
6564 pCmdData,
6565 replySize,
6566 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006568 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 for (size_t i = 1; i < mHandles.size(); i++) {
6570 sp<EffectHandle> h = mHandles[i].promote();
6571 if (h != 0) {
6572 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6573 }
6574 }
6575 }
6576 return status;
6577}
6578
6579status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6580{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006581
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006583 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584
6585 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006586 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6587 if (enabled && status != NO_ERROR) {
6588 return status;
6589 }
6590
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 switch (mState) {
6592 // going from disabled to enabled
6593 case IDLE:
6594 mState = STARTING;
6595 break;
6596 case STOPPED:
6597 mState = RESTART;
6598 break;
6599 case STOPPING:
6600 mState = ACTIVE;
6601 break;
6602
6603 // going from enabled to disabled
6604 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006605 mState = STOPPED;
6606 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 case STARTING:
6608 mState = IDLE;
6609 break;
6610 case ACTIVE:
6611 mState = STOPPING;
6612 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006613 case DESTROYED:
6614 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 }
6616 for (size_t i = 1; i < mHandles.size(); i++) {
6617 sp<EffectHandle> h = mHandles[i].promote();
6618 if (h != 0) {
6619 h->setEnabled(enabled);
6620 }
6621 }
6622 }
6623 return NO_ERROR;
6624}
6625
6626bool AudioFlinger::EffectModule::isEnabled()
6627{
6628 switch (mState) {
6629 case RESTART:
6630 case STARTING:
6631 case ACTIVE:
6632 return true;
6633 case IDLE:
6634 case STOPPING:
6635 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006636 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006637 default:
6638 return false;
6639 }
6640}
6641
Eric Laurent8f45bd72010-08-31 13:50:07 -07006642bool AudioFlinger::EffectModule::isProcessEnabled()
6643{
6644 switch (mState) {
6645 case RESTART:
6646 case ACTIVE:
6647 case STOPPING:
6648 case STOPPED:
6649 return true;
6650 case IDLE:
6651 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006652 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006653 default:
6654 return false;
6655 }
6656}
6657
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6659{
6660 Mutex::Autolock _l(mLock);
6661 status_t status = NO_ERROR;
6662
6663 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6664 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006665 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006666 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6667 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 status_t cmdStatus;
6669 uint32_t volume[2];
6670 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006671 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672 volume[0] = *left;
6673 volume[1] = *right;
6674 if (controller) {
6675 pVolume = volume;
6676 }
Eric Laurent25f43952010-07-28 05:40:18 -07006677 status = (*mEffectInterface)->command(mEffectInterface,
6678 EFFECT_CMD_SET_VOLUME,
6679 size,
6680 volume,
6681 &size,
6682 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6684 *left = volume[0];
6685 *right = volume[1];
6686 }
6687 }
6688 return status;
6689}
6690
6691status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6692{
6693 Mutex::Autolock _l(mLock);
6694 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006695 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6696 // audio pre processing modules on RecordThread can receive both output and
6697 // input device indication in the same call
6698 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6699 if (dev) {
6700 status_t cmdStatus;
6701 uint32_t size = sizeof(status_t);
6702
6703 status = (*mEffectInterface)->command(mEffectInterface,
6704 EFFECT_CMD_SET_DEVICE,
6705 sizeof(uint32_t),
6706 &dev,
6707 &size,
6708 &cmdStatus);
6709 if (status == NO_ERROR) {
6710 status = cmdStatus;
6711 }
6712 }
6713 dev = device & AUDIO_DEVICE_IN_ALL;
6714 if (dev) {
6715 status_t cmdStatus;
6716 uint32_t size = sizeof(status_t);
6717
6718 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6719 EFFECT_CMD_SET_INPUT_DEVICE,
6720 sizeof(uint32_t),
6721 &dev,
6722 &size,
6723 &cmdStatus);
6724 if (status2 == NO_ERROR) {
6725 status2 = cmdStatus;
6726 }
6727 if (status == NO_ERROR) {
6728 status = status2;
6729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730 }
6731 }
6732 return status;
6733}
6734
Glenn Kastenf78aee72012-01-04 11:00:47 -08006735status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736{
6737 Mutex::Autolock _l(mLock);
6738 status_t status = NO_ERROR;
6739 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006741 uint32_t size = sizeof(status_t);
6742 status = (*mEffectInterface)->command(mEffectInterface,
6743 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006744 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006745 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006746 &size,
6747 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 if (status == NO_ERROR) {
6749 status = cmdStatus;
6750 }
6751 }
6752 return status;
6753}
6754
Eric Laurent59255e42011-07-27 19:49:51 -07006755void AudioFlinger::EffectModule::setSuspended(bool suspended)
6756{
6757 Mutex::Autolock _l(mLock);
6758 mSuspended = suspended;
6759}
Glenn Kastena3a85482012-01-04 11:01:11 -08006760
6761bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006762{
6763 Mutex::Autolock _l(mLock);
6764 return mSuspended;
6765}
6766
Mathias Agopian65ab4712010-07-14 17:59:35 -07006767status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6768{
6769 const size_t SIZE = 256;
6770 char buffer[SIZE];
6771 String8 result;
6772
6773 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6774 result.append(buffer);
6775
6776 bool locked = tryLock(mLock);
6777 // failed to lock - AudioFlinger is probably deadlocked
6778 if (!locked) {
6779 result.append("\t\tCould not lock Fx mutex:\n");
6780 }
6781
6782 result.append("\t\tSession Status State Engine:\n");
6783 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6784 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6785 result.append(buffer);
6786
6787 result.append("\t\tDescriptor:\n");
6788 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6789 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6790 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6791 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6792 result.append(buffer);
6793 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6794 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6795 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6796 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6797 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006798 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 mDescriptor.apiVersion,
6800 mDescriptor.flags);
6801 result.append(buffer);
6802 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6803 mDescriptor.name);
6804 result.append(buffer);
6805 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6806 mDescriptor.implementor);
6807 result.append(buffer);
6808
6809 result.append("\t\t- Input configuration:\n");
6810 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6811 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6812 (uint32_t)mConfig.inputCfg.buffer.raw,
6813 mConfig.inputCfg.buffer.frameCount,
6814 mConfig.inputCfg.samplingRate,
6815 mConfig.inputCfg.channels,
6816 mConfig.inputCfg.format);
6817 result.append(buffer);
6818
6819 result.append("\t\t- Output configuration:\n");
6820 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6821 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6822 (uint32_t)mConfig.outputCfg.buffer.raw,
6823 mConfig.outputCfg.buffer.frameCount,
6824 mConfig.outputCfg.samplingRate,
6825 mConfig.outputCfg.channels,
6826 mConfig.outputCfg.format);
6827 result.append(buffer);
6828
6829 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6830 result.append(buffer);
6831 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6832 for (size_t i = 0; i < mHandles.size(); ++i) {
6833 sp<EffectHandle> handle = mHandles[i].promote();
6834 if (handle != 0) {
6835 handle->dump(buffer, SIZE);
6836 result.append(buffer);
6837 }
6838 }
6839
6840 result.append("\n");
6841
6842 write(fd, result.string(), result.length());
6843
6844 if (locked) {
6845 mLock.unlock();
6846 }
6847
6848 return NO_ERROR;
6849}
6850
6851// ----------------------------------------------------------------------------
6852// EffectHandle implementation
6853// ----------------------------------------------------------------------------
6854
6855#undef LOG_TAG
6856#define LOG_TAG "AudioFlinger::EffectHandle"
6857
6858AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6859 const sp<AudioFlinger::Client>& client,
6860 const sp<IEffectClient>& effectClient,
6861 int32_t priority)
6862 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006863 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006864 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865{
Steve Block3856b092011-10-20 11:56:00 +01006866 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006867
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006868 if (client == 0) {
6869 return;
6870 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6872 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6873 if (mCblkMemory != 0) {
6874 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6875
Glenn Kastena0d68332012-01-27 16:47:15 -08006876 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006877 new(mCblk) effect_param_cblk_t();
6878 mBuffer = (uint8_t *)mCblk + bufOffset;
6879 }
6880 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006881 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 return;
6883 }
6884}
6885
6886AudioFlinger::EffectHandle::~EffectHandle()
6887{
Steve Block3856b092011-10-20 11:56:00 +01006888 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006889 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006890 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891}
6892
6893status_t AudioFlinger::EffectHandle::enable()
6894{
Steve Block3856b092011-10-20 11:56:00 +01006895 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896 if (!mHasControl) return INVALID_OPERATION;
6897 if (mEffect == 0) return DEAD_OBJECT;
6898
Eric Laurentdb7c0792011-08-10 10:37:50 -07006899 if (mEnabled) {
6900 return NO_ERROR;
6901 }
6902
Eric Laurent59255e42011-07-27 19:49:51 -07006903 mEnabled = true;
6904
6905 sp<ThreadBase> thread = mEffect->thread().promote();
6906 if (thread != 0) {
6907 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6908 }
6909
6910 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6911 if (mEffect->suspended()) {
6912 return NO_ERROR;
6913 }
6914
Eric Laurentdb7c0792011-08-10 10:37:50 -07006915 status_t status = mEffect->setEnabled(true);
6916 if (status != NO_ERROR) {
6917 if (thread != 0) {
6918 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6919 }
6920 mEnabled = false;
6921 }
6922 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923}
6924
6925status_t AudioFlinger::EffectHandle::disable()
6926{
Steve Block3856b092011-10-20 11:56:00 +01006927 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006929 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930
Eric Laurentdb7c0792011-08-10 10:37:50 -07006931 if (!mEnabled) {
6932 return NO_ERROR;
6933 }
Eric Laurent59255e42011-07-27 19:49:51 -07006934 mEnabled = false;
6935
6936 if (mEffect->suspended()) {
6937 return NO_ERROR;
6938 }
6939
6940 status_t status = mEffect->setEnabled(false);
6941
6942 sp<ThreadBase> thread = mEffect->thread().promote();
6943 if (thread != 0) {
6944 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6945 }
6946
6947 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948}
6949
6950void AudioFlinger::EffectHandle::disconnect()
6951{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006952 disconnect(true);
6953}
6954
6955void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6956{
Steve Block3856b092011-10-20 11:56:00 +01006957 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006958 if (mEffect == 0) {
6959 return;
6960 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006961 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006962
Eric Laurenta85a74a2011-10-19 11:44:54 -07006963 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006964 sp<ThreadBase> thread = mEffect->thread().promote();
6965 if (thread != 0) {
6966 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6967 }
Eric Laurent59255e42011-07-27 19:49:51 -07006968 }
6969
Mathias Agopian65ab4712010-07-14 17:59:35 -07006970 // release sp on module => module destructor can be called now
6971 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006973 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006974 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006975 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6976 }
6977 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6979 mClient.clear();
6980 }
6981}
6982
Eric Laurent25f43952010-07-28 05:40:18 -07006983status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6984 uint32_t cmdSize,
6985 void *pCmdData,
6986 uint32_t *replySize,
6987 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988{
Steve Block3856b092011-10-20 11:56:00 +01006989// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006990// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991
6992 // only get parameter command is permitted for applications not controlling the effect
6993 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6994 return INVALID_OPERATION;
6995 }
6996 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006997 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
6999 // handle commands that are not forwarded transparently to effect engine
7000 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7001 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7002 // no risk to block the whole media server process or mixer threads is we are stuck here
7003 Mutex::Autolock _l(mCblk->lock);
7004 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7005 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7006 mCblk->serverIndex = 0;
7007 mCblk->clientIndex = 0;
7008 return BAD_VALUE;
7009 }
7010 status_t status = NO_ERROR;
7011 while (mCblk->serverIndex < mCblk->clientIndex) {
7012 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007013 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 int *p = (int *)(mBuffer + mCblk->serverIndex);
7015 int size = *p++;
7016 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007017 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 break;
7019 }
7020 effect_param_t *param = (effect_param_t *)p;
7021 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007022 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 mCblk->serverIndex += size;
7024 continue;
7025 }
Eric Laurent25f43952010-07-28 05:40:18 -07007026 uint32_t psize = sizeof(effect_param_t) +
7027 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7028 param->vsize;
7029 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7030 psize,
7031 p,
7032 &rsize,
7033 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007034 // stop at first error encountered
7035 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007037 *(int *)pReplyData = reply;
7038 break;
7039 } else if (reply != NO_ERROR) {
7040 *(int *)pReplyData = reply;
7041 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042 }
7043 mCblk->serverIndex += size;
7044 }
7045 mCblk->serverIndex = 0;
7046 mCblk->clientIndex = 0;
7047 return status;
7048 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007049 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 return enable();
7051 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007052 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 return disable();
7054 }
7055
7056 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7057}
7058
7059sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7060 return mCblkMemory;
7061}
7062
Eric Laurent59255e42011-07-27 19:49:51 -07007063void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064{
Steve Block3856b092011-10-20 11:56:00 +01007065 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066
7067 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007068 mEnabled = enabled;
7069
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070 if (signal && mEffectClient != 0) {
7071 mEffectClient->controlStatusChanged(hasControl);
7072 }
7073}
7074
Eric Laurent25f43952010-07-28 05:40:18 -07007075void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7076 uint32_t cmdSize,
7077 void *pCmdData,
7078 uint32_t replySize,
7079 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080{
7081 if (mEffectClient != 0) {
7082 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7083 }
7084}
7085
7086
7087
7088void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7089{
7090 if (mEffectClient != 0) {
7091 mEffectClient->enableStatusChanged(enabled);
7092 }
7093}
7094
7095status_t AudioFlinger::EffectHandle::onTransact(
7096 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7097{
7098 return BnEffect::onTransact(code, data, reply, flags);
7099}
7100
7101
7102void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7103{
Glenn Kastena0d68332012-01-27 16:47:15 -08007104 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105
7106 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7107 (mClient == NULL) ? getpid() : mClient->pid(),
7108 mPriority,
7109 mHasControl,
7110 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007111 mCblk ? mCblk->clientIndex : 0,
7112 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113 );
7114
7115 if (locked) {
7116 mCblk->lock.unlock();
7117 }
7118}
7119
7120#undef LOG_TAG
7121#define LOG_TAG "AudioFlinger::EffectChain"
7122
7123AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7124 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007125 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007126 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7127 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128{
Dima Zavinfce7a472011-04-19 22:30:36 -07007129 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007130 sp<ThreadBase> thread = mThread.promote();
7131 if (thread == 0) {
7132 return;
7133 }
7134 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7135 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136}
7137
7138AudioFlinger::EffectChain::~EffectChain()
7139{
7140 if (mOwnInBuffer) {
7141 delete mInBuffer;
7142 }
7143
7144}
7145
Eric Laurent59255e42011-07-27 19:49:51 -07007146// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007147sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148{
7149 sp<EffectModule> effect;
7150 size_t size = mEffects.size();
7151
7152 for (size_t i = 0; i < size; i++) {
7153 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7154 effect = mEffects[i];
7155 break;
7156 }
7157 }
7158 return effect;
7159}
7160
Eric Laurent59255e42011-07-27 19:49:51 -07007161// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007162sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
7164 sp<EffectModule> effect;
7165 size_t size = mEffects.size();
7166
7167 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007168 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7169 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170 effect = mEffects[i];
7171 break;
7172 }
7173 }
7174 return effect;
7175}
7176
Eric Laurent59255e42011-07-27 19:49:51 -07007177// getEffectFromType_l() must be called with ThreadBase::mLock held
7178sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7179 const effect_uuid_t *type)
7180{
7181 sp<EffectModule> effect;
7182 size_t size = mEffects.size();
7183
7184 for (size_t i = 0; i < size; i++) {
7185 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7186 effect = mEffects[i];
7187 break;
7188 }
7189 }
7190 return effect;
7191}
7192
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193// Must be called with EffectChain::mLock locked
7194void AudioFlinger::EffectChain::process_l()
7195{
Eric Laurentdac69112010-09-28 14:09:57 -07007196 sp<ThreadBase> thread = mThread.promote();
7197 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007198 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007199 return;
7200 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007201 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7202 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007203 // always process effects unless no more tracks are on the session and the effect tail
7204 // has been rendered
7205 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007206 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007207 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007208
Eric Laurent544fe9b2011-11-11 15:42:52 -08007209 if (!tracksOnSession && mTailBufferCount == 0) {
7210 doProcess = false;
7211 }
7212
7213 if (activeTrackCnt() == 0) {
7214 // if no track is active and the effect tail has not been rendered,
7215 // the input buffer must be cleared here as the mixer process will not do it
7216 if (tracksOnSession || mTailBufferCount > 0) {
7217 size_t numSamples = thread->frameCount() * thread->channelCount();
7218 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7219 if (mTailBufferCount > 0) {
7220 mTailBufferCount--;
7221 }
7222 }
7223 }
Eric Laurentdac69112010-09-28 14:09:57 -07007224 }
7225
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007227 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007228 for (size_t i = 0; i < size; i++) {
7229 mEffects[i]->process();
7230 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231 }
7232 for (size_t i = 0; i < size; i++) {
7233 mEffects[i]->updateState();
7234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235}
7236
Eric Laurentcab11242010-07-15 12:50:15 -07007237// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007238status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007239{
7240 effect_descriptor_t desc = effect->desc();
7241 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7242
7243 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007244 effect->setChain(this);
7245 sp<ThreadBase> thread = mThread.promote();
7246 if (thread == 0) {
7247 return NO_INIT;
7248 }
7249 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007250
7251 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7252 // Auxiliary effects are inserted at the beginning of mEffects vector as
7253 // they are processed first and accumulated in chain input buffer
7254 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007255
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256 // the input buffer for auxiliary effect contains mono samples in
7257 // 32 bit format. This is to avoid saturation in AudoMixer
7258 // accumulation stage. Saturation is done in EffectModule::process() before
7259 // calling the process in effect engine
7260 size_t numSamples = thread->frameCount();
7261 int32_t *buffer = new int32_t[numSamples];
7262 memset(buffer, 0, numSamples * sizeof(int32_t));
7263 effect->setInBuffer((int16_t *)buffer);
7264 // auxiliary effects output samples to chain input buffer for further processing
7265 // by insert effects
7266 effect->setOutBuffer(mInBuffer);
7267 } else {
7268 // Insert effects are inserted at the end of mEffects vector as they are processed
7269 // after track and auxiliary effects.
7270 // Insert effect order as a function of indicated preference:
7271 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7272 // another effect is present
7273 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7274 // last effect claiming first position
7275 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7276 // first effect claiming last position
7277 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7278 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7279 // already present
7280
7281 int size = (int)mEffects.size();
7282 int idx_insert = size;
7283 int idx_insert_first = -1;
7284 int idx_insert_last = -1;
7285
7286 for (int i = 0; i < size; i++) {
7287 effect_descriptor_t d = mEffects[i]->desc();
7288 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7289 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7290 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7291 // check invalid effect chaining combinations
7292 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7293 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007294 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 return INVALID_OPERATION;
7296 }
7297 // remember position of first insert effect and by default
7298 // select this as insert position for new effect
7299 if (idx_insert == size) {
7300 idx_insert = i;
7301 }
7302 // remember position of last insert effect claiming
7303 // first position
7304 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7305 idx_insert_first = i;
7306 }
7307 // remember position of first insert effect claiming
7308 // last position
7309 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7310 idx_insert_last == -1) {
7311 idx_insert_last = i;
7312 }
7313 }
7314 }
7315
7316 // modify idx_insert from first position if needed
7317 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7318 if (idx_insert_last != -1) {
7319 idx_insert = idx_insert_last;
7320 } else {
7321 idx_insert = size;
7322 }
7323 } else {
7324 if (idx_insert_first != -1) {
7325 idx_insert = idx_insert_first + 1;
7326 }
7327 }
7328
7329 // always read samples from chain input buffer
7330 effect->setInBuffer(mInBuffer);
7331
7332 // if last effect in the chain, output samples to chain
7333 // output buffer, otherwise to chain input buffer
7334 if (idx_insert == size) {
7335 if (idx_insert != 0) {
7336 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7337 mEffects[idx_insert-1]->configure();
7338 }
7339 effect->setOutBuffer(mOutBuffer);
7340 } else {
7341 effect->setOutBuffer(mInBuffer);
7342 }
7343 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344
Steve Block3856b092011-10-20 11:56:00 +01007345 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 }
7347 effect->configure();
7348 return NO_ERROR;
7349}
7350
Eric Laurentcab11242010-07-15 12:50:15 -07007351// removeEffect_l() must be called with PlaybackThread::mLock held
7352size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353{
7354 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007355 int size = (int)mEffects.size();
7356 int i;
7357 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7358
7359 for (i = 0; i < size; i++) {
7360 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007361 // calling stop here will remove pre-processing effect from the audio HAL.
7362 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7363 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007364 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7365 mEffects[i]->state() == EffectModule::STOPPING) {
7366 mEffects[i]->stop();
7367 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7369 delete[] effect->inBuffer();
7370 } else {
7371 if (i == size - 1 && i != 0) {
7372 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7373 mEffects[i - 1]->configure();
7374 }
7375 }
7376 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007377 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 break;
7379 }
7380 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381
7382 return mEffects.size();
7383}
7384
Eric Laurentcab11242010-07-15 12:50:15 -07007385// setDevice_l() must be called with PlaybackThread::mLock held
7386void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387{
7388 size_t size = mEffects.size();
7389 for (size_t i = 0; i < size; i++) {
7390 mEffects[i]->setDevice(device);
7391 }
7392}
7393
Eric Laurentcab11242010-07-15 12:50:15 -07007394// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007395void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396{
7397 size_t size = mEffects.size();
7398 for (size_t i = 0; i < size; i++) {
7399 mEffects[i]->setMode(mode);
7400 }
7401}
7402
Eric Laurentcab11242010-07-15 12:50:15 -07007403// setVolume_l() must be called with PlaybackThread::mLock held
7404bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405{
7406 uint32_t newLeft = *left;
7407 uint32_t newRight = *right;
7408 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007409 int ctrlIdx = -1;
7410 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411
Eric Laurentcab11242010-07-15 12:50:15 -07007412 // first update volume controller
7413 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007414 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007415 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7416 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007417 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007418 break;
7419 }
7420 }
7421
7422 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007423 if (hasControl) {
7424 *left = mNewLeftVolume;
7425 *right = mNewRightVolume;
7426 }
7427 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007428 }
7429
7430 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007431 mLeftVolume = newLeft;
7432 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007433
7434 // second get volume update from volume controller
7435 if (ctrlIdx >= 0) {
7436 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007437 mNewLeftVolume = newLeft;
7438 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439 }
7440 // then indicate volume to all other effects in chain.
7441 // Pass altered volume to effects before volume controller
7442 // and requested volume to effects after controller
7443 uint32_t lVol = newLeft;
7444 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007445
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007447 if ((int)i == ctrlIdx) continue;
7448 // this also works for ctrlIdx == -1 when there is no volume controller
7449 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 lVol = *left;
7451 rVol = *right;
7452 }
7453 mEffects[i]->setVolume(&lVol, &rVol, false);
7454 }
7455 *left = newLeft;
7456 *right = newRight;
7457
7458 return hasControl;
7459}
7460
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7462{
7463 const size_t SIZE = 256;
7464 char buffer[SIZE];
7465 String8 result;
7466
7467 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7468 result.append(buffer);
7469
7470 bool locked = tryLock(mLock);
7471 // failed to lock - AudioFlinger is probably deadlocked
7472 if (!locked) {
7473 result.append("\tCould not lock mutex:\n");
7474 }
7475
Eric Laurentcab11242010-07-15 12:50:15 -07007476 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7477 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478 mEffects.size(),
7479 (uint32_t)mInBuffer,
7480 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 mActiveTrackCnt);
7482 result.append(buffer);
7483 write(fd, result.string(), result.size());
7484
7485 for (size_t i = 0; i < mEffects.size(); ++i) {
7486 sp<EffectModule> effect = mEffects[i];
7487 if (effect != 0) {
7488 effect->dump(fd, args);
7489 }
7490 }
7491
7492 if (locked) {
7493 mLock.unlock();
7494 }
7495
7496 return NO_ERROR;
7497}
7498
Eric Laurent59255e42011-07-27 19:49:51 -07007499// must be called with ThreadBase::mLock held
7500void AudioFlinger::EffectChain::setEffectSuspended_l(
7501 const effect_uuid_t *type, bool suspend)
7502{
7503 sp<SuspendedEffectDesc> desc;
7504 // use effect type UUID timelow as key as there is no real risk of identical
7505 // timeLow fields among effect type UUIDs.
7506 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7507 if (suspend) {
7508 if (index >= 0) {
7509 desc = mSuspendedEffects.valueAt(index);
7510 } else {
7511 desc = new SuspendedEffectDesc();
7512 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7513 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007514 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007515 }
7516 if (desc->mRefCount++ == 0) {
7517 sp<EffectModule> effect = getEffectIfEnabled(type);
7518 if (effect != 0) {
7519 desc->mEffect = effect;
7520 effect->setSuspended(true);
7521 effect->setEnabled(false);
7522 }
7523 }
7524 } else {
7525 if (index < 0) {
7526 return;
7527 }
7528 desc = mSuspendedEffects.valueAt(index);
7529 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007530 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007531 desc->mRefCount = 1;
7532 }
7533 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007534 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007535 if (desc->mEffect != 0) {
7536 sp<EffectModule> effect = desc->mEffect.promote();
7537 if (effect != 0) {
7538 effect->setSuspended(false);
7539 sp<EffectHandle> handle = effect->controlHandle();
7540 if (handle != 0) {
7541 effect->setEnabled(handle->enabled());
7542 }
7543 }
7544 desc->mEffect.clear();
7545 }
7546 mSuspendedEffects.removeItemsAt(index);
7547 }
7548 }
7549}
7550
7551// must be called with ThreadBase::mLock held
7552void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7553{
7554 sp<SuspendedEffectDesc> desc;
7555
7556 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7557 if (suspend) {
7558 if (index >= 0) {
7559 desc = mSuspendedEffects.valueAt(index);
7560 } else {
7561 desc = new SuspendedEffectDesc();
7562 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007563 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007564 }
7565 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007566 Vector< sp<EffectModule> > effects;
7567 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007568 for (size_t i = 0; i < effects.size(); i++) {
7569 setEffectSuspended_l(&effects[i]->desc().type, true);
7570 }
7571 }
7572 } else {
7573 if (index < 0) {
7574 return;
7575 }
7576 desc = mSuspendedEffects.valueAt(index);
7577 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007578 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007579 desc->mRefCount = 1;
7580 }
7581 if (--desc->mRefCount == 0) {
7582 Vector<const effect_uuid_t *> types;
7583 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7584 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7585 continue;
7586 }
7587 types.add(&mSuspendedEffects.valueAt(i)->mType);
7588 }
7589 for (size_t i = 0; i < types.size(); i++) {
7590 setEffectSuspended_l(types[i], false);
7591 }
Steve Block3856b092011-10-20 11:56:00 +01007592 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007593 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7594 }
7595 }
7596}
7597
Eric Laurent6bffdb82011-09-23 08:40:41 -07007598
7599// The volume effect is used for automated tests only
7600#ifndef OPENSL_ES_H_
7601static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7602 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7603const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7604#endif //OPENSL_ES_H_
7605
Eric Laurentdb7c0792011-08-10 10:37:50 -07007606bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7607{
7608 // auxiliary effects and visualizer are never suspended on output mix
7609 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7610 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007611 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7612 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007613 return false;
7614 }
7615 return true;
7616}
7617
Glenn Kastend0539712012-01-30 12:56:03 -08007618void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007619{
Glenn Kastend0539712012-01-30 12:56:03 -08007620 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007621 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007622 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7623 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007624 }
Eric Laurent59255e42011-07-27 19:49:51 -07007625 }
Eric Laurent59255e42011-07-27 19:49:51 -07007626}
7627
7628sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7629 const effect_uuid_t *type)
7630{
7631 sp<EffectModule> effect;
7632 effect = getEffectFromType_l(type);
7633 if (effect != 0 && !effect->isEnabled()) {
7634 effect.clear();
7635 }
7636 return effect;
7637}
7638
7639void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7640 bool enabled)
7641{
7642 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7643 if (enabled) {
7644 if (index < 0) {
7645 // if the effect is not suspend check if all effects are suspended
7646 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7647 if (index < 0) {
7648 return;
7649 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007650 if (!isEffectEligibleForSuspend(effect->desc())) {
7651 return;
7652 }
Eric Laurent59255e42011-07-27 19:49:51 -07007653 setEffectSuspended_l(&effect->desc().type, enabled);
7654 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007655 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007656 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007657 return;
7658 }
Eric Laurent59255e42011-07-27 19:49:51 -07007659 }
Steve Block3856b092011-10-20 11:56:00 +01007660 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007661 effect->desc().type.timeLow);
7662 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7663 // if effect is requested to suspended but was not yet enabled, supend it now.
7664 if (desc->mEffect == 0) {
7665 desc->mEffect = effect;
7666 effect->setEnabled(false);
7667 effect->setSuspended(true);
7668 }
7669 } else {
7670 if (index < 0) {
7671 return;
7672 }
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007674 effect->desc().type.timeLow);
7675 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7676 desc->mEffect.clear();
7677 effect->setSuspended(false);
7678 }
7679}
7680
Mathias Agopian65ab4712010-07-14 17:59:35 -07007681#undef LOG_TAG
7682#define LOG_TAG "AudioFlinger"
7683
7684// ----------------------------------------------------------------------------
7685
7686status_t AudioFlinger::onTransact(
7687 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7688{
7689 return BnAudioFlinger::onTransact(code, data, reply, flags);
7690}
7691
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692}; // namespace android