blob: d96624bebbd78f398367d720dfd9b158b0698ec1 [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
40#include <media/AudioTrack.h>
41#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080042#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080043#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include <private/media/AudioTrackShared.h>
46#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070047
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070049#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
51#include "AudioMixer.h"
52#include "AudioFlinger.h"
53
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070055#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070056#include <audio_effects/effect_ns.h>
57#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070063// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
64
Mathias Agopian65ab4712010-07-14 17:59:35 -070065// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Eric Laurentde070132010-07-13 04:45:46 -070067
Mathias Agopian65ab4712010-07-14 17:59:35 -070068namespace android {
69
Glenn Kastenec1d6b52011-12-12 09:04:45 -080070static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
71static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
74static const float MAX_GAIN = 4096.0f;
75static const float MAX_GAIN_INT = 0x1000;
76
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
81// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
85
86static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080087static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Glenn Kasten7dede872011-12-13 11:04:14 -080089// don't warn about blocked writes or record buffer overflows more often than this
90static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070091
Eric Laurent7c7f10b2011-06-17 21:29:58 -070092// RecordThread loop sleep time upon application overrun or audio HAL read error
93static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
Glenn Kasten7dede872011-12-13 11:04:14 -080095// maximum time to wait for setParameters to complete
96static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070097
Eric Laurent7cafbb32011-11-22 18:50:29 -080098// minimum sleep time for the mixer thread loop when tracks are active but in underrun
99static const uint32_t kMinThreadSleepTimeUs = 5000;
100// maximum divider applied to the active sleep time in the mixer thread loop
101static const uint32_t kMaxThreadSleepTimeShift = 2;
102
103
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104// ----------------------------------------------------------------------------
105
106static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
108 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000109 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111}
112
113static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
115 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000116 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118}
119
Gloria Wang9ee159b2011-02-24 14:51:45 -0800120// To collect the amplifier usage
121static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800122 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
123 if (service == NULL) {
124 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800125 return;
126 }
127
128 service->addBatteryData(params);
129}
130
Dima Zavin799a70e2011-04-18 16:57:27 -0700131static int load_audio_interface(const char *if_name, const hw_module_t **mod,
132 audio_hw_device_t **dev)
133{
134 int rc;
135
136 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
137 if (rc)
138 goto out;
139
140 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000141 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700142 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
143 if (rc)
144 goto out;
145
146 return 0;
147
148out:
149 *mod = NULL;
150 *dev = NULL;
151 return rc;
152}
153
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800154static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700155 "primary",
156 "a2dp",
157 "usb",
158};
159#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
160
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161// ----------------------------------------------------------------------------
162
163AudioFlinger::AudioFlinger()
164 : BnAudioFlinger(),
Glenn Kastene0feee32011-12-13 11:53:26 -0800165 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700166 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin799a70e2011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700173
Eric Laurent93575202011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin799a70e2011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177 mHardwareStatus = AUDIO_HW_IDLE;
178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Dima Zavin799a70e2011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261
262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800297 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298
299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328 }
329 return locked;
330}
331
332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
334 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
335 dumpPermissionDenial(fd, args);
336 } else {
337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
352 }
353
354 dumpClients(fd, args);
355 dumpInternals(fd, args);
356
357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
359 mPlaybackThreads.valueAt(i)->dump(fd, args);
360 }
361
362 // dump record threads
363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
364 mRecordThreads.valueAt(i)->dump(fd, args);
365 }
366
Dima Zavin799a70e2011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 if (locked) mLock.unlock();
373 }
374 return NO_ERROR;
375}
376
377
378// IAudioFlinger interface
379
380
381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800383 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700385 uint32_t format,
386 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
390 int output,
391 int *sessionId,
392 status_t *status)
393{
394 sp<PlaybackThread::Track> track;
395 sp<TrackHandle> trackHandle;
396 sp<Client> client;
397 wp<Client> wclient;
398 status_t lStatus;
399 int lSessionId;
400
Dima Zavinfce7a472011-04-19 22:30:36 -0700401 if (streamType >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000402 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
407 {
408 Mutex::Autolock _l(mLock);
409 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700410 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000412 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
416
417 wclient = mClients.valueFor(pid);
418
419 if (wclient != NULL) {
420 client = wclient.promote();
421 } else {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
425
Steve Block3856b092011-10-20 11:56:00 +0100426 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700427 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700429 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
430 if (mPlaybackThreads.keyAt(i) != output) {
431 // prevent same audio session on different output threads
432 uint32_t sessions = t->hasAudioSession(*sessionId);
433 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000434 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700435 lStatus = BAD_VALUE;
436 goto Exit;
437 }
438 // check if an effect with same session ID is waiting for a track to be created
439 if (sessions & PlaybackThread::EFFECT_SESSION) {
440 effectThread = t.get();
441 }
Eric Laurentde070132010-07-13 04:45:46 -0700442 }
443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 lSessionId = *sessionId;
445 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700446 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700447 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 if (sessionId != NULL) {
449 *sessionId = lSessionId;
450 }
451 }
Steve Block3856b092011-10-20 11:56:00 +0100452 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453
454 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700455 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700456
457 // move effect chain to this output thread if an effect on same session was waiting
458 // for a track to be created
459 if (lStatus == NO_ERROR && effectThread != NULL) {
460 Mutex::Autolock _dl(thread->mLock);
461 Mutex::Autolock _sl(effectThread->mLock);
462 moveEffectChain_l(lSessionId, effectThread, thread, true);
463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 }
465 if (lStatus == NO_ERROR) {
466 trackHandle = new TrackHandle(track);
467 } else {
468 // remove local strong reference to Client before deleting the Track so that the Client
469 // destructor is called by the TrackBase destructor with mLock held
470 client.clear();
471 track.clear();
472 }
473
474Exit:
475 if(status) {
476 *status = lStatus;
477 }
478 return trackHandle;
479}
480
481uint32_t AudioFlinger::sampleRate(int output) const
482{
483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000486 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487 return 0;
488 }
489 return thread->sampleRate();
490}
491
492int AudioFlinger::channelCount(int output) const
493{
494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000497 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498 return 0;
499 }
500 return thread->channelCount();
501}
502
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700503uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504{
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000508 ALOGW("format() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509 return 0;
510 }
511 return thread->format();
512}
513
514size_t AudioFlinger::frameCount(int output) const
515{
516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000519 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700520 return 0;
521 }
522 return thread->frameCount();
523}
524
525uint32_t AudioFlinger::latency(int output) const
526{
527 Mutex::Autolock _l(mLock);
528 PlaybackThread *thread = checkPlaybackThread_l(output);
529 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000530 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 return 0;
532 }
533 return thread->latency();
534}
535
536status_t AudioFlinger::setMasterVolume(float value)
537{
Eric Laurenta1884f92011-08-23 08:25:03 -0700538 status_t ret = initCheck();
539 if (ret != NO_ERROR) {
540 return ret;
541 }
542
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
547
548 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700552 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800553 value = 1.0f;
554 }
555 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557
Eric Laurent93575202011-01-18 18:39:02 -0800558 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 mMasterVolume = value;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
561 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
562
563 return NO_ERROR;
564}
565
566status_t AudioFlinger::setMode(int mode)
567{
Eric Laurenta1884f92011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572
573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800577 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000578 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return BAD_VALUE;
580 }
581
582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 }
588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 }
595
596 return ret;
597}
598
599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurenta1884f92011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavinfce7a472011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
638
Eric Laurent93575202011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
643
644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
Glenn Kasten98067102011-12-13 11:47:54 -0800649 Mutex::Autolock _l(mLock);
650 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651}
652
653bool AudioFlinger::masterMute() const
654{
Glenn Kasten98067102011-12-13 11:47:54 -0800655 Mutex::Autolock _l(mLock);
656 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657}
658
Glenn Kastenfff6d712012-01-12 16:38:12 -0800659status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660{
661 // check calling permissions
662 if (!settingsAllowed()) {
663 return PERMISSION_DENIED;
664 }
665
Dima Zavinfce7a472011-04-19 22:30:36 -0700666 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000667 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 return BAD_VALUE;
669 }
670
671 AutoMutex lock(mLock);
672 PlaybackThread *thread = NULL;
673 if (output) {
674 thread = checkPlaybackThread_l(output);
675 if (thread == NULL) {
676 return BAD_VALUE;
677 }
678 }
679
680 mStreamTypes[stream].volume = value;
681
682 if (thread == NULL) {
683 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
684 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
685 }
686 } else {
687 thread->setStreamVolume(stream, value);
688 }
689
690 return NO_ERROR;
691}
692
Glenn Kastenfff6d712012-01-12 16:38:12 -0800693status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694{
695 // check calling permissions
696 if (!settingsAllowed()) {
697 return PERMISSION_DENIED;
698 }
699
Dima Zavinfce7a472011-04-19 22:30:36 -0700700 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
701 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000702 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 return BAD_VALUE;
704 }
705
Eric Laurent93575202011-01-18 18:39:02 -0800706 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mStreamTypes[stream].mute = muted;
708 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
709 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
710
711 return NO_ERROR;
712}
713
Glenn Kastenfff6d712012-01-12 16:38:12 -0800714float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715{
Dima Zavinfce7a472011-04-19 22:30:36 -0700716 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 return 0.0f;
718 }
719
720 AutoMutex lock(mLock);
721 float volume;
722 if (output) {
723 PlaybackThread *thread = checkPlaybackThread_l(output);
724 if (thread == NULL) {
725 return 0.0f;
726 }
727 volume = thread->streamVolume(stream);
728 } else {
729 volume = mStreamTypes[stream].volume;
730 }
731
732 return volume;
733}
734
Glenn Kastenfff6d712012-01-12 16:38:12 -0800735bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736{
Dima Zavinfce7a472011-04-19 22:30:36 -0700737 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738 return true;
739 }
740
741 return mStreamTypes[stream].mute;
742}
743
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
745{
746 status_t result;
747
Steve Block3856b092011-10-20 11:56:00 +0100748 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
750 // check calling permissions
751 if (!settingsAllowed()) {
752 return PERMISSION_DENIED;
753 }
754
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 // ioHandle == 0 means the parameters are global to the audio hardware interface
756 if (ioHandle == 0) {
757 AutoMutex lock(mHardwareLock);
758 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700759 status_t final_result = NO_ERROR;
760 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
761 audio_hw_device_t *dev = mAudioHwDevs[i];
762 result = dev->set_parameters(dev, keyValuePairs.string());
763 final_result = result ?: final_result;
764 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700766 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
767 AudioParameter param = AudioParameter(keyValuePairs);
768 String8 value;
769 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
770 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700771 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
772 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700773 for (size_t i = 0; i < mRecordThreads.size(); i++) {
774 sp<RecordThread> thread = mRecordThreads.valueAt(i);
775 RecordThread::RecordTrack *track = thread->track();
776 if (track != NULL) {
777 audio_devices_t device = (audio_devices_t)(
778 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700779 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700780 thread->setEffectSuspended(FX_IID_AEC,
781 suspend,
782 track->sessionId());
783 thread->setEffectSuspended(FX_IID_NS,
784 suspend,
785 track->sessionId());
786 }
787 }
Eric Laurentbee53372011-08-29 12:42:48 -0700788 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700789 }
790 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700791 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 }
793
794 // hold a strong ref on thread in case closeOutput() or closeInput() is called
795 // and the thread is exited once the lock is released
796 sp<ThreadBase> thread;
797 {
798 Mutex::Autolock _l(mLock);
799 thread = checkPlaybackThread_l(ioHandle);
800 if (thread == NULL) {
801 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700802 } else if (thread.get() == primaryPlaybackThread_l()) {
803 // indicate output device change to all input threads for pre processing
804 AudioParameter param = AudioParameter(keyValuePairs);
805 int value;
806 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
807 for (size_t i = 0; i < mRecordThreads.size(); i++) {
808 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
809 }
810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
812 }
813 if (thread != NULL) {
814 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return result;
816 }
817 return BAD_VALUE;
818}
819
820String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
821{
Steve Block3856b092011-10-20 11:56:00 +0100822// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
824
825 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700826 String8 out_s8;
827
Dima Zavin799a70e2011-04-18 16:57:27 -0700828 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
829 audio_hw_device_t *dev = mAudioHwDevs[i];
830 char *s = dev->get_parameters(dev, keys.string());
831 out_s8 += String8(s);
832 free(s);
833 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700834 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 }
836
837 Mutex::Autolock _l(mLock);
838
839 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
840 if (playbackThread != NULL) {
841 return playbackThread->getParameters(keys);
842 }
843 RecordThread *recordThread = checkRecordThread_l(ioHandle);
844 if (recordThread != NULL) {
845 return recordThread->getParameters(keys);
846 }
847 return String8("");
848}
849
850size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
851{
Eric Laurenta1884f92011-08-23 08:25:03 -0700852 status_t ret = initCheck();
853 if (ret != NO_ERROR) {
854 return 0;
855 }
856
Dima Zavin799a70e2011-04-18 16:57:27 -0700857 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858}
859
860unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
861{
862 if (ioHandle == 0) {
863 return 0;
864 }
865
866 Mutex::Autolock _l(mLock);
867
868 RecordThread *recordThread = checkRecordThread_l(ioHandle);
869 if (recordThread != NULL) {
870 return recordThread->getInputFramesLost();
871 }
872 return 0;
873}
874
875status_t AudioFlinger::setVoiceVolume(float value)
876{
Eric Laurenta1884f92011-08-23 08:25:03 -0700877 status_t ret = initCheck();
878 if (ret != NO_ERROR) {
879 return ret;
880 }
881
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 // check calling permissions
883 if (!settingsAllowed()) {
884 return PERMISSION_DENIED;
885 }
886
887 AutoMutex lock(mHardwareLock);
888 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700889 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890 mHardwareStatus = AUDIO_HW_IDLE;
891
892 return ret;
893}
894
895status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
896{
897 status_t status;
898
899 Mutex::Autolock _l(mLock);
900
901 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
902 if (playbackThread != NULL) {
903 return playbackThread->getRenderPosition(halFrames, dspFrames);
904 }
905
906 return BAD_VALUE;
907}
908
909void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
910{
911
912 Mutex::Autolock _l(mLock);
913
914 int pid = IPCThreadState::self()->getCallingPid();
915 if (mNotificationClients.indexOfKey(pid) < 0) {
916 sp<NotificationClient> notificationClient = new NotificationClient(this,
917 client,
918 pid);
Steve Block3856b092011-10-20 11:56:00 +0100919 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920
921 mNotificationClients.add(pid, notificationClient);
922
923 sp<IBinder> binder = client->asBinder();
924 binder->linkToDeath(notificationClient);
925
926 // the config change is always sent from playback or record threads to avoid deadlock
927 // with AudioSystem::gLock
928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
929 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
930 }
931
932 for (size_t i = 0; i < mRecordThreads.size(); i++) {
933 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
934 }
935 }
936}
937
938void AudioFlinger::removeNotificationClient(pid_t pid)
939{
940 Mutex::Autolock _l(mLock);
941
942 int index = mNotificationClients.indexOfKey(pid);
943 if (index >= 0) {
944 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100945 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 mNotificationClients.removeItem(pid);
947 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950 int num = mAudioSessionRefs.size();
951 bool removed = false;
952 for (int i = 0; i< num; i++) {
953 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100954 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700955 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700957 mAudioSessionRefs.removeAt(i);
958 delete ref;
959 removed = true;
960 i--;
961 num--;
962 }
963 }
964 if (removed) {
965 purgeStaleEffects_l();
966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967}
968
969// audioConfigChanged_l() must be called with AudioFlinger::mLock held
970void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
971{
972 size_t size = mNotificationClients.size();
973 for (size_t i = 0; i < size; i++) {
974 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
975 }
976}
977
978// removeClient_l() must be called with AudioFlinger::mLock held
979void AudioFlinger::removeClient_l(pid_t pid)
980{
Steve Block3856b092011-10-20 11:56:00 +0100981 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 mClients.removeItem(pid);
983}
984
985
986// ----------------------------------------------------------------------------
987
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 : Thread(false),
990 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700991 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
992 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700994 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995}
996
997AudioFlinger::ThreadBase::~ThreadBase()
998{
999 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001000 // do not lock the mutex in destructor
1001 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001002 if (mPowerManager != 0) {
1003 sp<IBinder> binder = mPowerManager->asBinder();
1004 binder->unlinkToDeath(mDeathRecipient);
1005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006}
1007
1008void AudioFlinger::ThreadBase::exit()
1009{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001010 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011 // destroyed in the middle of requestExitAndWait()
1012 sp <ThreadBase> strongMe = this;
1013
Steve Block3856b092011-10-20 11:56:00 +01001014 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001016 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 mExiting = true;
1018 requestExit();
1019 mWaitWorkCV.signal();
1020 }
1021 requestExitAndWait();
1022}
1023
1024uint32_t AudioFlinger::ThreadBase::sampleRate() const
1025{
1026 return mSampleRate;
1027}
1028
1029int AudioFlinger::ThreadBase::channelCount() const
1030{
1031 return (int)mChannelCount;
1032}
1033
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001034uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035{
1036 return mFormat;
1037}
1038
1039size_t AudioFlinger::ThreadBase::frameCount() const
1040{
1041 return mFrameCount;
1042}
1043
1044status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1045{
1046 status_t status;
1047
Steve Block3856b092011-10-20 11:56:00 +01001048 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001049 Mutex::Autolock _l(mLock);
1050
1051 mNewParameters.add(keyValuePairs);
1052 mWaitWorkCV.signal();
1053 // wait condition with timeout in case the thread loop has exited
1054 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001055 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056 status = mParamStatus;
1057 mWaitWorkCV.signal();
1058 } else {
1059 status = TIMED_OUT;
1060 }
1061 return status;
1062}
1063
1064void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1065{
1066 Mutex::Autolock _l(mLock);
1067 sendConfigEvent_l(event, param);
1068}
1069
1070// sendConfigEvent_l() must be called with ThreadBase::mLock held
1071void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1072{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001073 ConfigEvent configEvent;
1074 configEvent.mEvent = event;
1075 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001077 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mWaitWorkCV.signal();
1079}
1080
1081void AudioFlinger::ThreadBase::processConfigEvents()
1082{
1083 mLock.lock();
1084 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001085 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001086 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087 mConfigEvents.removeAt(0);
1088 // release mLock before locking AudioFlinger mLock: lock order is always
1089 // AudioFlinger then ThreadBase to avoid cross deadlock
1090 mLock.unlock();
1091 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001092 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001094 mLock.lock();
1095 }
1096 mLock.unlock();
1097}
1098
1099status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1100{
1101 const size_t SIZE = 256;
1102 char buffer[SIZE];
1103 String8 result;
1104
1105 bool locked = tryLock(mLock);
1106 if (!locked) {
1107 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1108 write(fd, buffer, strlen(buffer));
1109 }
1110
1111 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1116 result.append(buffer);
1117 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1118 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001119 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1120 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001121 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1122 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001123 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001124 result.append(buffer);
1125
1126 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1127 result.append(buffer);
1128 result.append(" Index Command");
1129 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1130 snprintf(buffer, SIZE, "\n %02d ", i);
1131 result.append(buffer);
1132 result.append(mNewParameters[i]);
1133 }
1134
1135 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1136 result.append(buffer);
1137 snprintf(buffer, SIZE, " Index event param\n");
1138 result.append(buffer);
1139 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001140 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001141 result.append(buffer);
1142 }
1143 result.append("\n");
1144
1145 write(fd, result.string(), result.size());
1146
1147 if (locked) {
1148 mLock.unlock();
1149 }
1150 return NO_ERROR;
1151}
1152
Eric Laurent1d2bff02011-07-24 17:49:51 -07001153status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1154{
1155 const size_t SIZE = 256;
1156 char buffer[SIZE];
1157 String8 result;
1158
1159 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1160 write(fd, buffer, strlen(buffer));
1161
1162 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1163 sp<EffectChain> chain = mEffectChains[i];
1164 if (chain != 0) {
1165 chain->dump(fd, args);
1166 }
1167 }
1168 return NO_ERROR;
1169}
1170
Eric Laurentfeb0db62011-07-22 09:04:31 -07001171void AudioFlinger::ThreadBase::acquireWakeLock()
1172{
1173 Mutex::Autolock _l(mLock);
1174 acquireWakeLock_l();
1175}
1176
1177void AudioFlinger::ThreadBase::acquireWakeLock_l()
1178{
1179 if (mPowerManager == 0) {
1180 // use checkService() to avoid blocking if power service is not up yet
1181 sp<IBinder> binder =
1182 defaultServiceManager()->checkService(String16("power"));
1183 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001184 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001185 } else {
1186 mPowerManager = interface_cast<IPowerManager>(binder);
1187 binder->linkToDeath(mDeathRecipient);
1188 }
1189 }
1190 if (mPowerManager != 0) {
1191 sp<IBinder> binder = new BBinder();
1192 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1193 binder,
1194 String16(mName));
1195 if (status == NO_ERROR) {
1196 mWakeLockToken = binder;
1197 }
Steve Block3856b092011-10-20 11:56:00 +01001198 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001199 }
1200}
1201
1202void AudioFlinger::ThreadBase::releaseWakeLock()
1203{
1204 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001205 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001206}
1207
1208void AudioFlinger::ThreadBase::releaseWakeLock_l()
1209{
1210 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001211 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001212 if (mPowerManager != 0) {
1213 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1214 }
1215 mWakeLockToken.clear();
1216 }
1217}
1218
1219void AudioFlinger::ThreadBase::clearPowerManager()
1220{
1221 Mutex::Autolock _l(mLock);
1222 releaseWakeLock_l();
1223 mPowerManager.clear();
1224}
1225
1226void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1227{
1228 sp<ThreadBase> thread = mThread.promote();
1229 if (thread != 0) {
1230 thread->clearPowerManager();
1231 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001232 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001233}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001234
Eric Laurent59255e42011-07-27 19:49:51 -07001235void AudioFlinger::ThreadBase::setEffectSuspended(
1236 const effect_uuid_t *type, bool suspend, int sessionId)
1237{
1238 Mutex::Autolock _l(mLock);
1239 setEffectSuspended_l(type, suspend, sessionId);
1240}
1241
1242void AudioFlinger::ThreadBase::setEffectSuspended_l(
1243 const effect_uuid_t *type, bool suspend, int sessionId)
1244{
1245 sp<EffectChain> chain;
1246 chain = getEffectChain_l(sessionId);
1247 if (chain != 0) {
1248 if (type != NULL) {
1249 chain->setEffectSuspended_l(type, suspend);
1250 } else {
1251 chain->setEffectSuspendedAll_l(suspend);
1252 }
1253 }
1254
1255 updateSuspendedSessions_l(type, suspend, sessionId);
1256}
1257
1258void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1259{
1260 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1261 if (index < 0) {
1262 return;
1263 }
1264
1265 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1266 mSuspendedSessions.editValueAt(index);
1267
1268 for (size_t i = 0; i < sessionEffects.size(); i++) {
1269 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1270 for (int j = 0; j < desc->mRefCount; j++) {
1271 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1272 chain->setEffectSuspendedAll_l(true);
1273 } else {
Steve Block3856b092011-10-20 11:56:00 +01001274 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001275 desc->mType.timeLow);
1276 chain->setEffectSuspended_l(&desc->mType, true);
1277 }
1278 }
1279 }
1280}
1281
Eric Laurent59255e42011-07-27 19:49:51 -07001282void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1283 bool suspend,
1284 int sessionId)
1285{
1286 int index = mSuspendedSessions.indexOfKey(sessionId);
1287
1288 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1289
1290 if (suspend) {
1291 if (index >= 0) {
1292 sessionEffects = mSuspendedSessions.editValueAt(index);
1293 } else {
1294 mSuspendedSessions.add(sessionId, sessionEffects);
1295 }
1296 } else {
1297 if (index < 0) {
1298 return;
1299 }
1300 sessionEffects = mSuspendedSessions.editValueAt(index);
1301 }
1302
1303
1304 int key = EffectChain::kKeyForSuspendAll;
1305 if (type != NULL) {
1306 key = type->timeLow;
1307 }
1308 index = sessionEffects.indexOfKey(key);
1309
1310 sp <SuspendedSessionDesc> desc;
1311 if (suspend) {
1312 if (index >= 0) {
1313 desc = sessionEffects.valueAt(index);
1314 } else {
1315 desc = new SuspendedSessionDesc();
1316 if (type != NULL) {
1317 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1318 }
1319 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001320 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001321 }
1322 desc->mRefCount++;
1323 } else {
1324 if (index < 0) {
1325 return;
1326 }
1327 desc = sessionEffects.valueAt(index);
1328 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001329 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001330 sessionEffects.removeItemsAt(index);
1331 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001332 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001333 sessionId);
1334 mSuspendedSessions.removeItem(sessionId);
1335 }
1336 }
1337 }
1338 if (!sessionEffects.isEmpty()) {
1339 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1340 }
1341}
1342
1343void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1344 bool enabled,
1345 int sessionId)
1346{
1347 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001348 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1349}
Eric Laurent59255e42011-07-27 19:49:51 -07001350
Eric Laurenta85a74a2011-10-19 11:44:54 -07001351void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1352 bool enabled,
1353 int sessionId)
1354{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001355 if (mType != RECORD) {
1356 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1357 // another session. This gives the priority to well behaved effect control panels
1358 // and applications not using global effects.
1359 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1360 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1361 }
1362 }
Eric Laurent59255e42011-07-27 19:49:51 -07001363
1364 sp<EffectChain> chain = getEffectChain_l(sessionId);
1365 if (chain != 0) {
1366 chain->checkSuspendOnEffectEnabled(effect, enabled);
1367 }
1368}
1369
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370// ----------------------------------------------------------------------------
1371
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001372AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1373 AudioStreamOut* output,
1374 int id,
1375 uint32_t device)
1376 : ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001377 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001378 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001379{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001380 snprintf(mName, kNameLength, "AudioOut_%d", id);
1381
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382 readOutputParameters();
1383
Glenn Kasten98067102011-12-13 11:47:54 -08001384 // Assumes constructor is called by AudioFlinger with it's mLock held,
1385 // but it would be safer to explicitly pass these as parameters
1386 mMasterVolume = mAudioFlinger->masterVolume_l();
1387 mMasterMute = mAudioFlinger->masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001388
Glenn Kastenfff6d712012-01-12 16:38:12 -08001389 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1390 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1391 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1393 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001394 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 }
1396}
1397
1398AudioFlinger::PlaybackThread::~PlaybackThread()
1399{
1400 delete [] mMixBuffer;
1401}
1402
1403status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1404{
1405 dumpInternals(fd, args);
1406 dumpTracks(fd, args);
1407 dumpEffectChains(fd, args);
1408 return NO_ERROR;
1409}
1410
1411status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1412{
1413 const size_t SIZE = 256;
1414 char buffer[SIZE];
1415 String8 result;
1416
1417 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1418 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001419 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 for (size_t i = 0; i < mTracks.size(); ++i) {
1421 sp<Track> track = mTracks[i];
1422 if (track != 0) {
1423 track->dump(buffer, SIZE);
1424 result.append(buffer);
1425 }
1426 }
1427
1428 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1429 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001430 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 -07001431 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1432 wp<Track> wTrack = mActiveTracks[i];
1433 if (wTrack != 0) {
1434 sp<Track> track = wTrack.promote();
1435 if (track != 0) {
1436 track->dump(buffer, SIZE);
1437 result.append(buffer);
1438 }
1439 }
1440 }
1441 write(fd, result.string(), result.size());
1442 return NO_ERROR;
1443}
1444
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1446{
1447 const size_t SIZE = 256;
1448 char buffer[SIZE];
1449 String8 result;
1450
1451 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1456 result.append(buffer);
1457 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1458 result.append(buffer);
1459 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1460 result.append(buffer);
1461 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1462 result.append(buffer);
1463 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1464 result.append(buffer);
1465 write(fd, result.string(), result.size());
1466
1467 dumpBase(fd, args);
1468
1469 return NO_ERROR;
1470}
1471
1472// Thread virtuals
1473status_t AudioFlinger::PlaybackThread::readyToRun()
1474{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001475 status_t status = initCheck();
1476 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001477 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001478 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001479 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001481 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482}
1483
1484void AudioFlinger::PlaybackThread::onFirstRef()
1485{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001486 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487}
1488
1489// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1490sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1491 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001492 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001493 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001494 uint32_t format,
1495 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 int frameCount,
1497 const sp<IMemory>& sharedBuffer,
1498 int sessionId,
1499 status_t *status)
1500{
1501 sp<Track> track;
1502 status_t lStatus;
1503
1504 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001505 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1506 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001507 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001508 "for output %p with format %d",
1509 sampleRate, format, channelMask, mOutput, mFormat);
1510 lStatus = BAD_VALUE;
1511 goto Exit;
1512 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 }
1514 } else {
1515 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1516 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001517 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 lStatus = BAD_VALUE;
1519 goto Exit;
1520 }
1521 }
1522
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001523 lStatus = initCheck();
1524 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001525 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 goto Exit;
1527 }
1528
1529 { // scope for mLock
1530 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001531
1532 // all tracks in same audio session must share the same routing strategy otherwise
1533 // conflicts will happen when tracks are moved from one output to another by audio policy
1534 // manager
1535 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001536 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001537 for (size_t i = 0; i < mTracks.size(); ++i) {
1538 sp<Track> t = mTracks[i];
1539 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001540 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1541 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001542 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001543 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001544 lStatus = BAD_VALUE;
1545 goto Exit;
1546 }
1547 }
1548 }
1549
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001551 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 if (track->getCblk() == NULL || track->name() < 0) {
1553 lStatus = NO_MEMORY;
1554 goto Exit;
1555 }
1556 mTracks.add(track);
1557
1558 sp<EffectChain> chain = getEffectChain_l(sessionId);
1559 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001560 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001562 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001563 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001565
1566 // invalidate track immediately if the stream type was moved to another thread since
1567 // createTrack() was called by the client process.
1568 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001569 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001570 this, streamType);
1571 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001573 }
1574 lStatus = NO_ERROR;
1575
1576Exit:
1577 if(status) {
1578 *status = lStatus;
1579 }
1580 return track;
1581}
1582
1583uint32_t AudioFlinger::PlaybackThread::latency() const
1584{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001585 Mutex::Autolock _l(mLock);
1586 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001587 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001588 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 return 0;
1590 }
1591}
1592
1593status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1594{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 mMasterVolume = value;
1596 return NO_ERROR;
1597}
1598
1599status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1600{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 mMasterMute = muted;
1602 return NO_ERROR;
1603}
1604
1605float AudioFlinger::PlaybackThread::masterVolume() const
1606{
1607 return mMasterVolume;
1608}
1609
1610bool AudioFlinger::PlaybackThread::masterMute() const
1611{
1612 return mMasterMute;
1613}
1614
Glenn Kastenfff6d712012-01-12 16:38:12 -08001615status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617 mStreamTypes[stream].volume = value;
1618 return NO_ERROR;
1619}
1620
Glenn Kastenfff6d712012-01-12 16:38:12 -08001621status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001623 mStreamTypes[stream].mute = muted;
1624 return NO_ERROR;
1625}
1626
Glenn Kastenfff6d712012-01-12 16:38:12 -08001627float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628{
1629 return mStreamTypes[stream].volume;
1630}
1631
Glenn Kastenfff6d712012-01-12 16:38:12 -08001632bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633{
1634 return mStreamTypes[stream].mute;
1635}
1636
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637// addTrack_l() must be called with ThreadBase::mLock held
1638status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1639{
1640 status_t status = ALREADY_EXISTS;
1641
1642 // set retry count for buffer fill
1643 track->mRetryCount = kMaxTrackStartupRetries;
1644 if (mActiveTracks.indexOf(track) < 0) {
1645 // the track is newly added, make sure it fills up all its
1646 // buffers before playing. This is to ensure the client will
1647 // effectively get the latency it requested.
1648 track->mFillingUpStatus = Track::FS_FILLING;
1649 track->mResetDone = false;
1650 mActiveTracks.add(track);
1651 if (track->mainBuffer() != mMixBuffer) {
1652 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1653 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001654 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001655 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 }
1657 }
1658
1659 status = NO_ERROR;
1660 }
1661
Steve Block3856b092011-10-20 11:56:00 +01001662 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 mWaitWorkCV.broadcast();
1664
1665 return status;
1666}
1667
1668// destroyTrack_l() must be called with ThreadBase::mLock held
1669void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1670{
1671 track->mState = TrackBase::TERMINATED;
1672 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001673 removeTrack_l(track);
1674 }
1675}
1676
1677void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1678{
1679 mTracks.remove(track);
1680 deleteTrackName_l(track->name());
1681 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1682 if (chain != 0) {
1683 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001684 }
1685}
1686
1687String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1688{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001689 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001690 char *s;
1691
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001692 Mutex::Autolock _l(mLock);
1693 if (initCheck() != NO_ERROR) {
1694 return out_s8;
1695 }
1696
Dima Zavin799a70e2011-04-18 16:57:27 -07001697 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001698 out_s8 = String8(s);
1699 free(s);
1700 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701}
1702
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001703// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1705 AudioSystem::OutputDescriptor desc;
1706 void *param2 = 0;
1707
Steve Block3856b092011-10-20 11:56:00 +01001708 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709
1710 switch (event) {
1711 case AudioSystem::OUTPUT_OPENED:
1712 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001713 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 desc.samplingRate = mSampleRate;
1715 desc.format = mFormat;
1716 desc.frameCount = mFrameCount;
1717 desc.latency = latency();
1718 param2 = &desc;
1719 break;
1720
1721 case AudioSystem::STREAM_CONFIG_CHANGED:
1722 param2 = &param;
1723 case AudioSystem::OUTPUT_CLOSED:
1724 default:
1725 break;
1726 }
1727 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1728}
1729
1730void AudioFlinger::PlaybackThread::readOutputParameters()
1731{
Dima Zavin799a70e2011-04-18 16:57:27 -07001732 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001733 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1734 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001735 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001736 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001737 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738
1739 // FIXME - Current mixer implementation only supports stereo output: Always
1740 // Allocate a stereo buffer even if HW output is mono.
1741 if (mMixBuffer != NULL) delete[] mMixBuffer;
1742 mMixBuffer = new int16_t[mFrameCount * 2];
1743 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1744
Eric Laurentde070132010-07-13 04:45:46 -07001745 // force reconfiguration of effect chains and engines to take new buffer size and audio
1746 // parameters into account
1747 // Note that mLock is not held when readOutputParameters() is called from the constructor
1748 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1749 // matter.
1750 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1751 Vector< sp<EffectChain> > effectChains = mEffectChains;
1752 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001753 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755}
1756
1757status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1758{
1759 if (halFrames == 0 || dspFrames == 0) {
1760 return BAD_VALUE;
1761 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001762 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001763 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 return INVALID_OPERATION;
1765 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001766 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767
Dima Zavin799a70e2011-04-18 16:57:27 -07001768 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769}
1770
Eric Laurent39e94f82010-07-28 01:32:47 -07001771uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772{
1773 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001774 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001776 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 }
1778
1779 for (size_t i = 0; i < mTracks.size(); ++i) {
1780 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001781 if (sessionId == track->sessionId() &&
1782 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001783 result |= TRACK_SESSION;
1784 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 }
1786 }
1787
Eric Laurent39e94f82010-07-28 01:32:47 -07001788 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789}
1790
Eric Laurentde070132010-07-13 04:45:46 -07001791uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1792{
Dima Zavinfce7a472011-04-19 22:30:36 -07001793 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001794 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001795 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1796 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001797 }
1798 for (size_t i = 0; i < mTracks.size(); i++) {
1799 sp<Track> track = mTracks[i];
1800 if (sessionId == track->sessionId() &&
1801 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001802 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001803 }
1804 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001805 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001806}
1807
Mathias Agopian65ab4712010-07-14 17:59:35 -07001808
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001809AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1810{
1811 Mutex::Autolock _l(mLock);
1812 return mOutput;
1813}
1814
1815AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1816{
1817 Mutex::Autolock _l(mLock);
1818 AudioStreamOut *output = mOutput;
1819 mOutput = NULL;
1820 return output;
1821}
1822
1823// this method must always be called either with ThreadBase mLock held or inside the thread loop
1824audio_stream_t* AudioFlinger::PlaybackThread::stream()
1825{
1826 if (mOutput == NULL) {
1827 return NULL;
1828 }
1829 return &mOutput->stream->common;
1830}
1831
Eric Laurent162b40b2011-12-05 09:47:19 -08001832uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1833{
1834 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1835 // decoding and transfer time. So sleeping for half of the latency would likely cause
1836 // underruns
1837 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1838 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1839 } else {
1840 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1841 }
1842}
1843
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844// ----------------------------------------------------------------------------
1845
Dima Zavin799a70e2011-04-18 16:57:27 -07001846AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001848 mAudioMixer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001850 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1852
1853 // FIXME - Current mixer implementation only supports stereo output
1854 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001855 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 }
1857}
1858
1859AudioFlinger::MixerThread::~MixerThread()
1860{
1861 delete mAudioMixer;
1862}
1863
1864bool AudioFlinger::MixerThread::threadLoop()
1865{
1866 Vector< sp<Track> > tracksToRemove;
1867 uint32_t mixerStatus = MIXER_IDLE;
1868 nsecs_t standbyTime = systemTime();
1869 size_t mixBufferSize = mFrameCount * mFrameSize;
1870 // FIXME: Relaxed timing because of a certain device that can't meet latency
1871 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001872 // increase threshold again due to low power audio mode. The way this warning threshold is
1873 // calculated and its usefulness should be reconsidered anyway.
1874 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 nsecs_t lastWarning = 0;
1876 bool longStandbyExit = false;
1877 uint32_t activeSleepTime = activeSleepTimeUs();
1878 uint32_t idleSleepTime = idleSleepTimeUs();
1879 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001880 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001882#ifdef DEBUG_CPU_USAGE
1883 ThreadCpuUsage cpu;
1884 const CentralTendencyStatistics& stats = cpu.statistics();
1885#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886
Eric Laurentfeb0db62011-07-22 09:04:31 -07001887 acquireWakeLock();
1888
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 while (!exitPending())
1890 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001891#ifdef DEBUG_CPU_USAGE
1892 cpu.sampleAndEnable();
1893 unsigned n = stats.n();
1894 // cpu.elapsed() is expensive, so don't call it every loop
1895 if ((n & 127) == 1) {
1896 long long elapsed = cpu.elapsed();
1897 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1898 double perLoop = elapsed / (double) n;
1899 double perLoop100 = perLoop * 0.01;
1900 double mean = stats.mean();
1901 double stddev = stats.stddev();
1902 double minimum = stats.minimum();
1903 double maximum = stats.maximum();
1904 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001905 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 -07001906 elapsed * .000000001, n, perLoop * .000001,
1907 mean * .001,
1908 stddev * .001,
1909 minimum * .001,
1910 maximum * .001,
1911 mean / perLoop100,
1912 stddev / perLoop100,
1913 minimum / perLoop100,
1914 maximum / perLoop100);
1915 }
1916 }
1917#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 processConfigEvents();
1919
1920 mixerStatus = MIXER_IDLE;
1921 { // scope for mLock
1922
1923 Mutex::Autolock _l(mLock);
1924
1925 if (checkForNewParameters_l()) {
1926 mixBufferSize = mFrameCount * mFrameSize;
1927 // FIXME: Relaxed timing because of a certain device that can't meet latency
1928 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001929 // increase threshold again due to low power audio mode. The way this warning
1930 // threshold is calculated and its usefulness should be reconsidered anyway.
1931 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 activeSleepTime = activeSleepTimeUs();
1933 idleSleepTime = idleSleepTimeUs();
1934 }
1935
1936 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1937
1938 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001939 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1940 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001942 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001943 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 mStandby = true;
1945 mBytesWritten = 0;
1946 }
1947
1948 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1949 // we're about to wait, flush the binder command buffer
1950 IPCThreadState::self()->flushCommands();
1951
1952 if (exitPending()) break;
1953
Eric Laurentfeb0db62011-07-22 09:04:31 -07001954 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001956 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001958 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001959 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960
1961 if (mMasterMute == false) {
1962 char value[PROPERTY_VALUE_MAX];
1963 property_get("ro.audio.silent", value, "0");
1964 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001965 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 setMasterMute(true);
1967 }
1968 }
1969
1970 standbyTime = systemTime() + kStandbyTimeInNsecs;
1971 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001972 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 continue;
1974 }
1975 }
1976
1977 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1978
1979 // prevent any changes in effect chain list and in each effect chain
1980 // during mixing and effect process as the audio buffers could be deleted
1981 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001982 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001983 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984
Glenn Kastenf6b16782011-12-15 09:51:17 -08001985 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001986 // mix buffers...
1987 mAudioMixer->process();
1988 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001989 // increase sleep time progressively when application underrun condition clears
1990 if (sleepTimeShift > 0) {
1991 sleepTimeShift--;
1992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 standbyTime = systemTime() + kStandbyTimeInNsecs;
1994 //TODO: delay standby when effects have a tail
1995 } else {
1996 // If no tracks are ready, sleep once for the duration of an output
1997 // buffer size, then write 0s to the output
1998 if (sleepTime == 0) {
1999 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002000 sleepTime = activeSleepTime >> sleepTimeShift;
2001 if (sleepTime < kMinThreadSleepTimeUs) {
2002 sleepTime = kMinThreadSleepTimeUs;
2003 }
2004 // reduce sleep time in case of consecutive application underruns to avoid
2005 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2006 // duration we would end up writing less data than needed by the audio HAL if
2007 // the condition persists.
2008 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2009 sleepTimeShift++;
2010 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 } else {
2012 sleepTime = idleSleepTime;
2013 }
2014 } else if (mBytesWritten != 0 ||
2015 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2016 memset (mMixBuffer, 0, mixBufferSize);
2017 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002018 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 }
2020 // TODO add standby time extension fct of effect tail
2021 }
2022
2023 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002024 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 }
2026 // sleepTime == 0 means we must write to audio hardware
2027 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002028 for (size_t i = 0; i < effectChains.size(); i ++) {
2029 effectChains[i]->process_l();
2030 }
2031 // enable changes in effect chain
2032 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 mLastWriteTime = systemTime();
2034 mInWrite = true;
2035 mBytesWritten += mixBufferSize;
2036
Dima Zavin799a70e2011-04-18 16:57:27 -07002037 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2039 mNumWrites++;
2040 mInWrite = false;
2041 nsecs_t now = systemTime();
2042 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002043 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002045 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002046 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 ns2ms(delta), mNumDelayedWrites, this);
2048 lastWarning = now;
2049 }
2050 if (mStandby) {
2051 longStandbyExit = true;
2052 }
2053 }
2054 mStandby = false;
2055 } else {
2056 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002057 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 usleep(sleepTime);
2059 }
2060
2061 // finally let go of all our tracks, without the lock held
2062 // since we can't guarantee the destructors won't acquire that
2063 // same lock.
2064 tracksToRemove.clear();
2065
2066 // Effect chains will be actually deleted here if they were removed from
2067 // mEffectChains list during mixing or effects processing
2068 effectChains.clear();
2069 }
2070
2071 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002072 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 }
2074
Eric Laurentfeb0db62011-07-22 09:04:31 -07002075 releaseWakeLock();
2076
Steve Block3856b092011-10-20 11:56:00 +01002077 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 return false;
2079}
2080
2081// prepareTracks_l() must be called with ThreadBase::mLock held
2082uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2083{
2084
2085 uint32_t mixerStatus = MIXER_IDLE;
2086 // find out which tracks need to be processed
2087 size_t count = activeTracks.size();
2088 size_t mixedTracks = 0;
2089 size_t tracksWithEffect = 0;
2090
2091 float masterVolume = mMasterVolume;
2092 bool masterMute = mMasterMute;
2093
Eric Laurent571d49c2010-08-11 05:20:11 -07002094 if (masterMute) {
2095 masterVolume = 0;
2096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002098 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002100 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002101 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 masterVolume = (float)((v + (1 << 23)) >> 24);
2103 chain.clear();
2104 }
2105
2106 for (size_t i=0 ; i<count ; i++) {
2107 sp<Track> t = activeTracks[i].promote();
2108 if (t == 0) continue;
2109
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002110 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 Track* const track = t.get();
2112 audio_track_cblk_t* cblk = track->cblk();
2113
2114 // The first time a track is added we wait
2115 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002116 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002117 // make sure that we have enough frames to mix one full buffer.
2118 // enforce this condition only once to enable draining the buffer in case the client
2119 // app does not call stop() and relies on underrun to stop:
2120 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2121 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002122 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002123 if (!track->isStopped() && !track->isPausing() &&
2124 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002125 if (t->sampleRate() == (int)mSampleRate) {
2126 minFrames = mFrameCount;
2127 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002128 // +1 for rounding and +1 for additional sample needed for interpolation
2129 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2130 // add frames already consumed but not yet released by the resampler
2131 // because cblk->framesReady() will include these frames
2132 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2133 // the minimum track buffer size is normally twice the number of frames necessary
2134 // to fill one buffer and the resampler should not leave more than one buffer worth
2135 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002136 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002137 }
2138 }
2139 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 !track->isPaused() && !track->isTerminated())
2141 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002142 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143
2144 mixedTracks++;
2145
2146 // track->mainBuffer() != mMixBuffer means there is an effect chain
2147 // connected to the track
2148 chain.clear();
2149 if (track->mainBuffer() != mMixBuffer) {
2150 chain = getEffectChain_l(track->sessionId());
2151 // Delegate volume control to effect in track effect chain if needed
2152 if (chain != 0) {
2153 tracksWithEffect++;
2154 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002155 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002156 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 }
2158 }
2159
2160
2161 int param = AudioMixer::VOLUME;
2162 if (track->mFillingUpStatus == Track::FS_FILLED) {
2163 // no ramp for the first volume setting
2164 track->mFillingUpStatus = Track::FS_ACTIVE;
2165 if (track->mState == TrackBase::RESUMING) {
2166 track->mState = TrackBase::ACTIVE;
2167 param = AudioMixer::RAMP_VOLUME;
2168 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002169 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170 } else if (cblk->server != 0) {
2171 // If the track is stopped before the first frame was mixed,
2172 // do not apply ramp
2173 param = AudioMixer::RAMP_VOLUME;
2174 }
2175
2176 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002177 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002178 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002180 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002181 if (track->isPausing()) {
2182 track->setPaused();
2183 }
2184 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002185
Mathias Agopian65ab4712010-07-14 17:59:35 -07002186 // read original volumes with volume control
2187 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002189 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2190 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191
Glenn Kasten05632a52012-01-03 14:22:33 -08002192 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2193 // send level comes from shared memory and so may be corrupt
2194 if (sendLevel >= 0x1000) {
2195 ALOGV("Track send level out of range: %04X", sendLevel);
2196 sendLevel = 0x1000;
2197 }
2198 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002200 // Delegate volume control to effect in track effect chain if needed
2201 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2202 // Do not ramp volume if volume is controlled by effect
2203 param = AudioMixer::VOLUME;
2204 track->mHasVolumeController = true;
2205 } else {
2206 // force no volume ramp when volume controller was just disabled or removed
2207 // from effect chain to avoid volume spike
2208 if (track->mHasVolumeController) {
2209 param = AudioMixer::VOLUME;
2210 }
2211 track->mHasVolumeController = false;
2212 }
2213
2214 // Convert volumes from 8.24 to 4.12 format
2215 int16_t left, right, aux;
2216 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2217 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2218 left = int16_t(v_clamped);
2219 v_clamped = (vr + (1 << 11)) >> 12;
2220 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2221 right = int16_t(v_clamped);
2222
2223 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2224 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002227 mAudioMixer->setBufferProvider(name, track);
2228 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002230 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2231 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2232 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002234 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 AudioMixer::TRACK,
2236 AudioMixer::FORMAT, (void *)track->format());
2237 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002238 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002240 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002242 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 AudioMixer::RESAMPLE,
2244 AudioMixer::SAMPLE_RATE,
2245 (void *)(cblk->sampleRate));
2246 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002247 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 AudioMixer::TRACK,
2249 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2250 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002251 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 AudioMixer::TRACK,
2253 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2254
2255 // reset retry count
2256 track->mRetryCount = kMaxTrackRetries;
2257 mixerStatus = MIXER_TRACKS_READY;
2258 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002259 //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 -07002260 if (track->isStopped()) {
2261 track->reset();
2262 }
2263 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2264 // We have consumed all the buffers of this track.
2265 // Remove it from the list of active tracks.
2266 tracksToRemove->add(track);
2267 } else {
2268 // No buffers for this track. Give it a few chances to
2269 // fill a buffer, then remove it from active list.
2270 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002271 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002273 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002274 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 } else if (mixerStatus != MIXER_TRACKS_READY) {
2276 mixerStatus = MIXER_TRACKS_ENABLED;
2277 }
2278 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002279 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 }
2281 }
2282
2283 // remove all the tracks that need to be...
2284 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002285 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 for (size_t i=0 ; i<count ; i++) {
2287 const sp<Track>& track = tracksToRemove->itemAt(i);
2288 mActiveTracks.remove(track);
2289 if (track->mainBuffer() != mMixBuffer) {
2290 chain = getEffectChain_l(track->sessionId());
2291 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002292 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002293 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002294 }
2295 }
2296 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002297 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 }
2299 }
2300 }
2301
2302 // mix buffer must be cleared if all tracks are connected to an
2303 // effect chain as in this case the mixer will not write to
2304 // mix buffer and track effects will accumulate into it
2305 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2306 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2307 }
2308
2309 return mixerStatus;
2310}
2311
Glenn Kastenfff6d712012-01-12 16:38:12 -08002312void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313{
Steve Block3856b092011-10-20 11:56:00 +01002314 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002315 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002317
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 size_t size = mTracks.size();
2319 for (size_t i = 0; i < size; i++) {
2320 sp<Track> t = mTracks[i];
2321 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002322 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 }
2325 }
2326}
2327
Glenn Kastenfff6d712012-01-12 16:38:12 -08002328void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002329{
Steve Block3856b092011-10-20 11:56:00 +01002330 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002331 this, streamType, valid);
2332 Mutex::Autolock _l(mLock);
2333
2334 mStreamTypes[streamType].valid = valid;
2335}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336
2337// getTrackName_l() must be called with ThreadBase::mLock held
2338int AudioFlinger::MixerThread::getTrackName_l()
2339{
2340 return mAudioMixer->getTrackName();
2341}
2342
2343// deleteTrackName_l() must be called with ThreadBase::mLock held
2344void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2345{
Steve Block3856b092011-10-20 11:56:00 +01002346 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002347 mAudioMixer->deleteTrackName(name);
2348}
2349
2350// checkForNewParameters_l() must be called with ThreadBase::mLock held
2351bool AudioFlinger::MixerThread::checkForNewParameters_l()
2352{
2353 bool reconfig = false;
2354
2355 while (!mNewParameters.isEmpty()) {
2356 status_t status = NO_ERROR;
2357 String8 keyValuePair = mNewParameters[0];
2358 AudioParameter param = AudioParameter(keyValuePair);
2359 int value;
2360
2361 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2362 reconfig = true;
2363 }
2364 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002365 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002366 status = BAD_VALUE;
2367 } else {
2368 reconfig = true;
2369 }
2370 }
2371 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002372 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373 status = BAD_VALUE;
2374 } else {
2375 reconfig = true;
2376 }
2377 }
2378 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2379 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002380 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381 // if frame count is changed after track creation
2382 if (!mTracks.isEmpty()) {
2383 status = INVALID_OPERATION;
2384 } else {
2385 reconfig = true;
2386 }
2387 }
2388 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002389 // when changing the audio output device, call addBatteryData to notify
2390 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002391 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002392 uint32_t params = 0;
2393 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002394 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002395 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2396 }
2397
2398 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002399 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002400 // check if any other device (except speaker) is on
2401 if (value & deviceWithoutSpeaker ) {
2402 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2403 }
2404
2405 if (params != 0) {
2406 addBatteryData(params);
2407 }
2408 }
2409
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 // forward device change to effects that have requested to be
2411 // aware of attached audio device.
2412 mDevice = (uint32_t)value;
2413 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002414 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 }
2416 }
2417
2418 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002419 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002420 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002422 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423 mStandby = true;
2424 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002425 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002426 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 }
2428 if (status == NO_ERROR && reconfig) {
2429 delete mAudioMixer;
2430 readOutputParameters();
2431 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2432 for (size_t i = 0; i < mTracks.size() ; i++) {
2433 int name = getTrackName_l();
2434 if (name < 0) break;
2435 mTracks[i]->mName = name;
2436 // limit track sample rate to 2 x new output sample rate
2437 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2438 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2439 }
2440 }
2441 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2442 }
2443 }
2444
2445 mNewParameters.removeAt(0);
2446
2447 mParamStatus = status;
2448 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002449 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2450 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002451 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 }
2453 return reconfig;
2454}
2455
2456status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2457{
2458 const size_t SIZE = 256;
2459 char buffer[SIZE];
2460 String8 result;
2461
2462 PlaybackThread::dumpInternals(fd, args);
2463
2464 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2465 result.append(buffer);
2466 write(fd, result.string(), result.size());
2467 return NO_ERROR;
2468}
2469
Mathias Agopian65ab4712010-07-14 17:59:35 -07002470uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2471{
Eric Laurent60e18242010-07-29 06:50:24 -07002472 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002473}
2474
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002475uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2476{
2477 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2478}
2479
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002481AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482 : PlaybackThread(audioFlinger, output, id, device)
2483{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002484 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485}
2486
2487AudioFlinger::DirectOutputThread::~DirectOutputThread()
2488{
2489}
2490
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491static inline
2492int32_t mul(int16_t in, int16_t v)
2493{
2494#if defined(__arm__) && !defined(__thumb__)
2495 int32_t out;
2496 asm( "smulbb %[out], %[in], %[v] \n"
2497 : [out]"=r"(out)
2498 : [in]"%r"(in), [v]"r"(v)
2499 : );
2500 return out;
2501#else
2502 return in * int32_t(v);
2503#endif
2504}
2505
2506void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2507{
2508 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002509 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 return;
2511 }
2512
2513 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002514 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515 size_t count = mFrameCount * mChannelCount;
2516 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2517 int16_t *dst = mMixBuffer + count-1;
2518 while(count--) {
2519 *dst-- = (int16_t)(*src--^0x80) << 8;
2520 }
2521 }
2522
2523 size_t frameCount = mFrameCount;
2524 int16_t *out = mMixBuffer;
2525 if (ramp) {
2526 if (mChannelCount == 1) {
2527 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2528 int32_t vlInc = d / (int32_t)frameCount;
2529 int32_t vl = ((int32_t)mLeftVolShort << 16);
2530 do {
2531 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2532 out++;
2533 vl += vlInc;
2534 } while (--frameCount);
2535
2536 } else {
2537 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2538 int32_t vlInc = d / (int32_t)frameCount;
2539 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2540 int32_t vrInc = d / (int32_t)frameCount;
2541 int32_t vl = ((int32_t)mLeftVolShort << 16);
2542 int32_t vr = ((int32_t)mRightVolShort << 16);
2543 do {
2544 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2545 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2546 out += 2;
2547 vl += vlInc;
2548 vr += vrInc;
2549 } while (--frameCount);
2550 }
2551 } else {
2552 if (mChannelCount == 1) {
2553 do {
2554 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2555 out++;
2556 } while (--frameCount);
2557 } else {
2558 do {
2559 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2560 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2561 out += 2;
2562 } while (--frameCount);
2563 }
2564 }
2565
2566 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002567 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002568 size_t count = mFrameCount * mChannelCount;
2569 int16_t *src = mMixBuffer;
2570 uint8_t *dst = (uint8_t *)mMixBuffer;
2571 while(count--) {
2572 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2573 }
2574 }
2575
2576 mLeftVolShort = leftVol;
2577 mRightVolShort = rightVol;
2578}
2579
2580bool AudioFlinger::DirectOutputThread::threadLoop()
2581{
2582 uint32_t mixerStatus = MIXER_IDLE;
2583 sp<Track> trackToRemove;
2584 sp<Track> activeTrack;
2585 nsecs_t standbyTime = systemTime();
2586 int8_t *curBuf;
2587 size_t mixBufferSize = mFrameCount*mFrameSize;
2588 uint32_t activeSleepTime = activeSleepTimeUs();
2589 uint32_t idleSleepTime = idleSleepTimeUs();
2590 uint32_t sleepTime = idleSleepTime;
2591 // use shorter standby delay as on normal output to release
2592 // hardware resources as soon as possible
2593 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2594
Eric Laurentfeb0db62011-07-22 09:04:31 -07002595 acquireWakeLock();
2596
Mathias Agopian65ab4712010-07-14 17:59:35 -07002597 while (!exitPending())
2598 {
2599 bool rampVolume;
2600 uint16_t leftVol;
2601 uint16_t rightVol;
2602 Vector< sp<EffectChain> > effectChains;
2603
2604 processConfigEvents();
2605
2606 mixerStatus = MIXER_IDLE;
2607
2608 { // scope for the mLock
2609
2610 Mutex::Autolock _l(mLock);
2611
2612 if (checkForNewParameters_l()) {
2613 mixBufferSize = mFrameCount*mFrameSize;
2614 activeSleepTime = activeSleepTimeUs();
2615 idleSleepTime = idleSleepTimeUs();
2616 standbyDelay = microseconds(activeSleepTime*2);
2617 }
2618
2619 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002620 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2621 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002622 // wait until we have something to do...
2623 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002624 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002625 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626 mStandby = true;
2627 mBytesWritten = 0;
2628 }
2629
2630 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2631 // we're about to wait, flush the binder command buffer
2632 IPCThreadState::self()->flushCommands();
2633
2634 if (exitPending()) break;
2635
Eric Laurentfeb0db62011-07-22 09:04:31 -07002636 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002637 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002639 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002640 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641
2642 if (mMasterMute == false) {
2643 char value[PROPERTY_VALUE_MAX];
2644 property_get("ro.audio.silent", value, "0");
2645 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002646 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 setMasterMute(true);
2648 }
2649 }
2650
2651 standbyTime = systemTime() + standbyDelay;
2652 sleepTime = idleSleepTime;
2653 continue;
2654 }
2655 }
2656
2657 effectChains = mEffectChains;
2658
2659 // find out which tracks need to be processed
2660 if (mActiveTracks.size() != 0) {
2661 sp<Track> t = mActiveTracks[0].promote();
2662 if (t == 0) continue;
2663
2664 Track* const track = t.get();
2665 audio_track_cblk_t* cblk = track->cblk();
2666
2667 // The first time a track is added we wait
2668 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002669 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002670 !track->isPaused() && !track->isTerminated())
2671 {
Steve Block3856b092011-10-20 11:56:00 +01002672 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002673
2674 if (track->mFillingUpStatus == Track::FS_FILLED) {
2675 track->mFillingUpStatus = Track::FS_ACTIVE;
2676 mLeftVolFloat = mRightVolFloat = 0;
2677 mLeftVolShort = mRightVolShort = 0;
2678 if (track->mState == TrackBase::RESUMING) {
2679 track->mState = TrackBase::ACTIVE;
2680 rampVolume = true;
2681 }
2682 } else if (cblk->server != 0) {
2683 // If the track is stopped before the first frame was mixed,
2684 // do not apply ramp
2685 rampVolume = true;
2686 }
2687 // compute volume for this track
2688 float left, right;
2689 if (track->isMuted() || mMasterMute || track->isPausing() ||
2690 mStreamTypes[track->type()].mute) {
2691 left = right = 0;
2692 if (track->isPausing()) {
2693 track->setPaused();
2694 }
2695 } else {
2696 float typeVolume = mStreamTypes[track->type()].volume;
2697 float v = mMasterVolume * typeVolume;
2698 float v_clamped = v * cblk->volume[0];
2699 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2700 left = v_clamped/MAX_GAIN;
2701 v_clamped = v * cblk->volume[1];
2702 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2703 right = v_clamped/MAX_GAIN;
2704 }
2705
2706 if (left != mLeftVolFloat || right != mRightVolFloat) {
2707 mLeftVolFloat = left;
2708 mRightVolFloat = right;
2709
2710 // If audio HAL implements volume control,
2711 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002712 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 left = 1.0f;
2714 right = 1.0f;
2715 }
2716
2717 // Convert volumes from float to 8.24
2718 uint32_t vl = (uint32_t)(left * (1 << 24));
2719 uint32_t vr = (uint32_t)(right * (1 << 24));
2720
2721 // Delegate volume control to effect in track effect chain if needed
2722 // only one effect chain can be present on DirectOutputThread, so if
2723 // there is one, the track is connected to it
2724 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002725 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002726 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 rampVolume = false;
2728 }
2729 }
2730
2731 // Convert volumes from 8.24 to 4.12 format
2732 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2733 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2734 leftVol = (uint16_t)v_clamped;
2735 v_clamped = (vr + (1 << 11)) >> 12;
2736 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2737 rightVol = (uint16_t)v_clamped;
2738 } else {
2739 leftVol = mLeftVolShort;
2740 rightVol = mRightVolShort;
2741 rampVolume = false;
2742 }
2743
2744 // reset retry count
2745 track->mRetryCount = kMaxTrackRetriesDirect;
2746 activeTrack = t;
2747 mixerStatus = MIXER_TRACKS_READY;
2748 } else {
Steve Block3856b092011-10-20 11:56:00 +01002749 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002750 if (track->isStopped()) {
2751 track->reset();
2752 }
2753 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2754 // We have consumed all the buffers of this track.
2755 // Remove it from the list of active tracks.
2756 trackToRemove = track;
2757 } else {
2758 // No buffers for this track. Give it a few chances to
2759 // fill a buffer, then remove it from active list.
2760 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002761 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002762 trackToRemove = track;
2763 } else {
2764 mixerStatus = MIXER_TRACKS_ENABLED;
2765 }
2766 }
2767 }
2768 }
2769
2770 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002771 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772 mActiveTracks.remove(trackToRemove);
2773 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002774 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002775 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002776 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 }
2778 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002779 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 }
2781 }
2782
Eric Laurentde070132010-07-13 04:45:46 -07002783 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 }
2785
Glenn Kastenf6b16782011-12-15 09:51:17 -08002786 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787 AudioBufferProvider::Buffer buffer;
2788 size_t frameCount = mFrameCount;
2789 curBuf = (int8_t *)mMixBuffer;
2790 // output audio to hardware
2791 while (frameCount) {
2792 buffer.frameCount = frameCount;
2793 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002794 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 memset(curBuf, 0, frameCount * mFrameSize);
2796 break;
2797 }
2798 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2799 frameCount -= buffer.frameCount;
2800 curBuf += buffer.frameCount * mFrameSize;
2801 activeTrack->releaseBuffer(&buffer);
2802 }
2803 sleepTime = 0;
2804 standbyTime = systemTime() + standbyDelay;
2805 } else {
2806 if (sleepTime == 0) {
2807 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2808 sleepTime = activeSleepTime;
2809 } else {
2810 sleepTime = idleSleepTime;
2811 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002812 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2814 sleepTime = 0;
2815 }
2816 }
2817
2818 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002819 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 }
2821 // sleepTime == 0 means we must write to audio hardware
2822 if (sleepTime == 0) {
2823 if (mixerStatus == MIXER_TRACKS_READY) {
2824 applyVolume(leftVol, rightVol, rampVolume);
2825 }
2826 for (size_t i = 0; i < effectChains.size(); i ++) {
2827 effectChains[i]->process_l();
2828 }
Eric Laurentde070132010-07-13 04:45:46 -07002829 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830
2831 mLastWriteTime = systemTime();
2832 mInWrite = true;
2833 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002834 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2836 mNumWrites++;
2837 mInWrite = false;
2838 mStandby = false;
2839 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002840 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841 usleep(sleepTime);
2842 }
2843
2844 // finally let go of removed track, without the lock held
2845 // since we can't guarantee the destructors won't acquire that
2846 // same lock.
2847 trackToRemove.clear();
2848 activeTrack.clear();
2849
2850 // Effect chains will be actually deleted here if they were removed from
2851 // mEffectChains list during mixing or effects processing
2852 effectChains.clear();
2853 }
2854
2855 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002856 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 }
2858
Eric Laurentfeb0db62011-07-22 09:04:31 -07002859 releaseWakeLock();
2860
Steve Block3856b092011-10-20 11:56:00 +01002861 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862 return false;
2863}
2864
2865// getTrackName_l() must be called with ThreadBase::mLock held
2866int AudioFlinger::DirectOutputThread::getTrackName_l()
2867{
2868 return 0;
2869}
2870
2871// deleteTrackName_l() must be called with ThreadBase::mLock held
2872void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2873{
2874}
2875
2876// checkForNewParameters_l() must be called with ThreadBase::mLock held
2877bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2878{
2879 bool reconfig = false;
2880
2881 while (!mNewParameters.isEmpty()) {
2882 status_t status = NO_ERROR;
2883 String8 keyValuePair = mNewParameters[0];
2884 AudioParameter param = AudioParameter(keyValuePair);
2885 int value;
2886
2887 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2888 // do not accept frame count changes if tracks are open as the track buffer
2889 // size depends on frame count and correct behavior would not be garantied
2890 // if frame count is changed after track creation
2891 if (!mTracks.isEmpty()) {
2892 status = INVALID_OPERATION;
2893 } else {
2894 reconfig = true;
2895 }
2896 }
2897 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002898 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002899 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002901 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002902 mStandby = true;
2903 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002904 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002905 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 }
2907 if (status == NO_ERROR && reconfig) {
2908 readOutputParameters();
2909 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2910 }
2911 }
2912
2913 mNewParameters.removeAt(0);
2914
2915 mParamStatus = status;
2916 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002917 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2918 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002919 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 }
2921 return reconfig;
2922}
2923
2924uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2925{
2926 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002927 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002928 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929 } else {
2930 time = 10000;
2931 }
2932 return time;
2933}
2934
2935uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2936{
2937 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002938 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002939 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002940 } else {
2941 time = 10000;
2942 }
2943 return time;
2944}
2945
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002946uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2947{
2948 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002949 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002950 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2951 } else {
2952 time = 10000;
2953 }
2954 return time;
2955}
2956
2957
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958// ----------------------------------------------------------------------------
2959
2960AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2961 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2962{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002963 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002964 addOutputTrack(mainThread);
2965}
2966
2967AudioFlinger::DuplicatingThread::~DuplicatingThread()
2968{
2969 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2970 mOutputTracks[i]->destroy();
2971 }
2972 mOutputTracks.clear();
2973}
2974
2975bool AudioFlinger::DuplicatingThread::threadLoop()
2976{
2977 Vector< sp<Track> > tracksToRemove;
2978 uint32_t mixerStatus = MIXER_IDLE;
2979 nsecs_t standbyTime = systemTime();
2980 size_t mixBufferSize = mFrameCount*mFrameSize;
2981 SortedVector< sp<OutputTrack> > outputTracks;
2982 uint32_t writeFrames = 0;
2983 uint32_t activeSleepTime = activeSleepTimeUs();
2984 uint32_t idleSleepTime = idleSleepTimeUs();
2985 uint32_t sleepTime = idleSleepTime;
2986 Vector< sp<EffectChain> > effectChains;
2987
Eric Laurentfeb0db62011-07-22 09:04:31 -07002988 acquireWakeLock();
2989
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990 while (!exitPending())
2991 {
2992 processConfigEvents();
2993
2994 mixerStatus = MIXER_IDLE;
2995 { // scope for the mLock
2996
2997 Mutex::Autolock _l(mLock);
2998
2999 if (checkForNewParameters_l()) {
3000 mixBufferSize = mFrameCount*mFrameSize;
3001 updateWaitTime();
3002 activeSleepTime = activeSleepTimeUs();
3003 idleSleepTime = idleSleepTimeUs();
3004 }
3005
3006 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3007
3008 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3009 outputTracks.add(mOutputTracks[i]);
3010 }
3011
3012 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003013 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3014 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 if (!mStandby) {
3016 for (size_t i = 0; i < outputTracks.size(); i++) {
3017 outputTracks[i]->stop();
3018 }
3019 mStandby = true;
3020 mBytesWritten = 0;
3021 }
3022
3023 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3024 // we're about to wait, flush the binder command buffer
3025 IPCThreadState::self()->flushCommands();
3026 outputTracks.clear();
3027
3028 if (exitPending()) break;
3029
Eric Laurentfeb0db62011-07-22 09:04:31 -07003030 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003031 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003033 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003034 acquireWakeLock_l();
3035
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 if (mMasterMute == false) {
3037 char value[PROPERTY_VALUE_MAX];
3038 property_get("ro.audio.silent", value, "0");
3039 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003040 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003041 setMasterMute(true);
3042 }
3043 }
3044
3045 standbyTime = systemTime() + kStandbyTimeInNsecs;
3046 sleepTime = idleSleepTime;
3047 continue;
3048 }
3049 }
3050
3051 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3052
3053 // prevent any changes in effect chain list and in each effect chain
3054 // during mixing and effect process as the audio buffers could be deleted
3055 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003056 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 }
3058
Glenn Kastenf6b16782011-12-15 09:51:17 -08003059 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 // mix buffers...
3061 if (outputsReady(outputTracks)) {
3062 mAudioMixer->process();
3063 } else {
3064 memset(mMixBuffer, 0, mixBufferSize);
3065 }
3066 sleepTime = 0;
3067 writeFrames = mFrameCount;
3068 } else {
3069 if (sleepTime == 0) {
3070 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3071 sleepTime = activeSleepTime;
3072 } else {
3073 sleepTime = idleSleepTime;
3074 }
3075 } else if (mBytesWritten != 0) {
3076 // flush remaining overflow buffers in output tracks
3077 for (size_t i = 0; i < outputTracks.size(); i++) {
3078 if (outputTracks[i]->isActive()) {
3079 sleepTime = 0;
3080 writeFrames = 0;
3081 memset(mMixBuffer, 0, mixBufferSize);
3082 break;
3083 }
3084 }
3085 }
3086 }
3087
3088 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003089 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 }
3091 // sleepTime == 0 means we must write to audio hardware
3092 if (sleepTime == 0) {
3093 for (size_t i = 0; i < effectChains.size(); i ++) {
3094 effectChains[i]->process_l();
3095 }
3096 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003097 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098
3099 standbyTime = systemTime() + kStandbyTimeInNsecs;
3100 for (size_t i = 0; i < outputTracks.size(); i++) {
3101 outputTracks[i]->write(mMixBuffer, writeFrames);
3102 }
3103 mStandby = false;
3104 mBytesWritten += mixBufferSize;
3105 } else {
3106 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003107 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 usleep(sleepTime);
3109 }
3110
3111 // finally let go of all our tracks, without the lock held
3112 // since we can't guarantee the destructors won't acquire that
3113 // same lock.
3114 tracksToRemove.clear();
3115 outputTracks.clear();
3116
3117 // Effect chains will be actually deleted here if they were removed from
3118 // mEffectChains list during mixing or effects processing
3119 effectChains.clear();
3120 }
3121
Eric Laurentfeb0db62011-07-22 09:04:31 -07003122 releaseWakeLock();
3123
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124 return false;
3125}
3126
3127void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3128{
3129 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3130 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3131 this,
3132 mSampleRate,
3133 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003134 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 frameCount);
3136 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003137 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003138 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003139 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 updateWaitTime();
3141 }
3142}
3143
3144void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3145{
3146 Mutex::Autolock _l(mLock);
3147 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3148 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3149 mOutputTracks[i]->destroy();
3150 mOutputTracks.removeAt(i);
3151 updateWaitTime();
3152 return;
3153 }
3154 }
Steve Block3856b092011-10-20 11:56:00 +01003155 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156}
3157
3158void AudioFlinger::DuplicatingThread::updateWaitTime()
3159{
3160 mWaitTimeMs = UINT_MAX;
3161 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3162 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3163 if (strong != NULL) {
3164 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3165 if (waitTimeMs < mWaitTimeMs) {
3166 mWaitTimeMs = waitTimeMs;
3167 }
3168 }
3169 }
3170}
3171
3172
3173bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3174{
3175 for (size_t i = 0; i < outputTracks.size(); i++) {
3176 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3177 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003178 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 return false;
3180 }
3181 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3182 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003183 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 return false;
3185 }
3186 }
3187 return true;
3188}
3189
3190uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3191{
3192 return (mWaitTimeMs * 1000) / 2;
3193}
3194
3195// ----------------------------------------------------------------------------
3196
3197// TrackBase constructor must be called with AudioFlinger::mLock held
3198AudioFlinger::ThreadBase::TrackBase::TrackBase(
3199 const wp<ThreadBase>& thread,
3200 const sp<Client>& client,
3201 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003202 uint32_t format,
3203 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 int frameCount,
3205 uint32_t flags,
3206 const sp<IMemory>& sharedBuffer,
3207 int sessionId)
3208 : RefBase(),
3209 mThread(thread),
3210 mClient(client),
3211 mCblk(0),
3212 mFrameCount(0),
3213 mState(IDLE),
3214 mClientTid(-1),
3215 mFormat(format),
3216 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3217 mSessionId(sessionId)
3218{
Steve Block3856b092011-10-20 11:56:00 +01003219 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220
Steve Blockb8a80522011-12-20 16:23:08 +00003221 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003223 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3225 if (sharedBuffer == 0) {
3226 size += bufferSize;
3227 }
3228
3229 if (client != NULL) {
3230 mCblkMemory = client->heap()->allocate(size);
3231 if (mCblkMemory != 0) {
3232 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3233 if (mCblk) { // construct the shared structure in-place.
3234 new(mCblk) audio_track_cblk_t();
3235 // clear all buffers
3236 mCblk->frameCount = frameCount;
3237 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003238 mChannelCount = channelCount;
3239 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240 if (sharedBuffer == 0) {
3241 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3242 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3243 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003244 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 mCblk->flags = CBLK_UNDERRUN_ON;
3246 } else {
3247 mBuffer = sharedBuffer->pointer();
3248 }
3249 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3250 }
3251 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003252 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 client->heap()->dump("AudioTrack");
3254 return;
3255 }
3256 } else {
3257 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003258 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 new(mCblk) audio_track_cblk_t();
3260 // clear all buffers
3261 mCblk->frameCount = frameCount;
3262 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003263 mChannelCount = channelCount;
3264 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3266 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3267 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003268 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 mCblk->flags = CBLK_UNDERRUN_ON;
3270 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 }
3272}
3273
3274AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3275{
3276 if (mCblk) {
3277 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3278 if (mClient == NULL) {
3279 delete mCblk;
3280 }
3281 }
3282 mCblkMemory.clear(); // and free the shared memory
3283 if (mClient != NULL) {
3284 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3285 mClient.clear();
3286 }
3287}
3288
3289void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3290{
Glenn Kastene0feee32011-12-13 11:53:26 -08003291 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 mFrameCount = buffer->frameCount;
3293 step();
3294 buffer->frameCount = 0;
3295}
3296
3297bool AudioFlinger::ThreadBase::TrackBase::step() {
3298 bool result;
3299 audio_track_cblk_t* cblk = this->cblk();
3300
3301 result = cblk->stepServer(mFrameCount);
3302 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003303 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003304 mFlags |= STEPSERVER_FAILED;
3305 }
3306 return result;
3307}
3308
3309void AudioFlinger::ThreadBase::TrackBase::reset() {
3310 audio_track_cblk_t* cblk = this->cblk();
3311
3312 cblk->user = 0;
3313 cblk->server = 0;
3314 cblk->userBase = 0;
3315 cblk->serverBase = 0;
3316 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003317 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318}
3319
3320sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3321{
3322 return mCblkMemory;
3323}
3324
3325int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3326 return (int)mCblk->sampleRate;
3327}
3328
3329int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003330 return (const int)mChannelCount;
3331}
3332
3333uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3334 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335}
3336
3337void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3338 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003339 size_t frameSize = cblk->frameSize;
3340 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3341 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003342
3343 // Check validity of returned pointer in case the track control block would have been corrupted.
3344 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003345 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003346 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 -07003347 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003349 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 return 0;
3351 }
3352
3353 return bufferStart;
3354}
3355
3356// ----------------------------------------------------------------------------
3357
3358// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3359AudioFlinger::PlaybackThread::Track::Track(
3360 const wp<ThreadBase>& thread,
3361 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003362 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003364 uint32_t format,
3365 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003366 int frameCount,
3367 const sp<IMemory>& sharedBuffer,
3368 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003369 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003370 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3371 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372{
3373 if (mCblk != NULL) {
3374 sp<ThreadBase> baseThread = thread.promote();
3375 if (baseThread != 0) {
3376 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3377 mName = playbackThread->getTrackName_l();
3378 mMainBuffer = playbackThread->mixBuffer();
3379 }
Steve Block3856b092011-10-20 11:56:00 +01003380 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003381 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003382 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 }
3384 mVolume[0] = 1.0f;
3385 mVolume[1] = 1.0f;
3386 mStreamType = streamType;
3387 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3388 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003389 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003390 }
3391}
3392
3393AudioFlinger::PlaybackThread::Track::~Track()
3394{
Steve Block3856b092011-10-20 11:56:00 +01003395 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 sp<ThreadBase> thread = mThread.promote();
3397 if (thread != 0) {
3398 Mutex::Autolock _l(thread->mLock);
3399 mState = TERMINATED;
3400 }
3401}
3402
3403void AudioFlinger::PlaybackThread::Track::destroy()
3404{
3405 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3406 // by removing it from mTracks vector, so there is a risk that this Tracks's
3407 // desctructor is called. As the destructor needs to lock mLock,
3408 // we must acquire a strong reference on this Track before locking mLock
3409 // here so that the destructor is called only when exiting this function.
3410 // On the other hand, as long as Track::destroy() is only called by
3411 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3412 // this Track with its member mTrack.
3413 sp<Track> keep(this);
3414 { // scope for mLock
3415 sp<ThreadBase> thread = mThread.promote();
3416 if (thread != 0) {
3417 if (!isOutputTrack()) {
3418 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003419 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003420 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003421 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003422
3423 // to track the speaker usage
3424 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 }
3426 AudioSystem::releaseOutput(thread->id());
3427 }
3428 Mutex::Autolock _l(thread->mLock);
3429 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3430 playbackThread->destroyTrack_l(this);
3431 }
3432 }
3433}
3434
3435void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3436{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003437 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 -07003438 mName - AudioMixer::TRACK0,
3439 (mClient == NULL) ? getpid() : mClient->pid(),
3440 mStreamType,
3441 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003442 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003443 mSessionId,
3444 mFrameCount,
3445 mState,
3446 mMute,
3447 mFillingUpStatus,
3448 mCblk->sampleRate,
3449 mCblk->volume[0],
3450 mCblk->volume[1],
3451 mCblk->server,
3452 mCblk->user,
3453 (int)mMainBuffer,
3454 (int)mAuxBuffer);
3455}
3456
3457status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3458{
3459 audio_track_cblk_t* cblk = this->cblk();
3460 uint32_t framesReady;
3461 uint32_t framesReq = buffer->frameCount;
3462
3463 // Check if last stepServer failed, try to step now
3464 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3465 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003466 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003467 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3468 }
3469
3470 framesReady = cblk->framesReady();
3471
Glenn Kastenf6b16782011-12-15 09:51:17 -08003472 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 uint32_t s = cblk->server;
3474 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3475
3476 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3477 if (framesReq > framesReady) {
3478 framesReq = framesReady;
3479 }
3480 if (s + framesReq > bufferEnd) {
3481 framesReq = bufferEnd - s;
3482 }
3483
3484 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003485 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486
3487 buffer->frameCount = framesReq;
3488 return NO_ERROR;
3489 }
3490
3491getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003492 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003494 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 return NOT_ENOUGH_DATA;
3496}
3497
3498bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003499 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500
3501 if (mCblk->framesReady() >= mCblk->frameCount ||
3502 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3503 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003504 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 return true;
3506 }
3507 return false;
3508}
3509
3510status_t AudioFlinger::PlaybackThread::Track::start()
3511{
3512 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003513 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003514 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 sp<ThreadBase> thread = mThread.promote();
3516 if (thread != 0) {
3517 Mutex::Autolock _l(thread->mLock);
3518 int state = mState;
3519 // here the track could be either new, or restarted
3520 // in both cases "unstop" the track
3521 if (mState == PAUSED) {
3522 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003523 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003524 } else {
3525 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003526 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 }
3528
3529 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3530 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003531 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003532 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003533 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003535
3536 // to track the speaker usage
3537 if (status == NO_ERROR) {
3538 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 }
3541 if (status == NO_ERROR) {
3542 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3543 playbackThread->addTrack_l(this);
3544 } else {
3545 mState = state;
3546 }
3547 } else {
3548 status = BAD_VALUE;
3549 }
3550 return status;
3551}
3552
3553void AudioFlinger::PlaybackThread::Track::stop()
3554{
Steve Block3856b092011-10-20 11:56:00 +01003555 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 sp<ThreadBase> thread = mThread.promote();
3557 if (thread != 0) {
3558 Mutex::Autolock _l(thread->mLock);
3559 int state = mState;
3560 if (mState > STOPPED) {
3561 mState = STOPPED;
3562 // If the track is not active (PAUSED and buffers full), flush buffers
3563 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3564 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3565 reset();
3566 }
Steve Block3856b092011-10-20 11:56:00 +01003567 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 }
3569 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3570 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003571 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003572 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003573 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003575
3576 // to track the speaker usage
3577 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 }
3579 }
3580}
3581
3582void AudioFlinger::PlaybackThread::Track::pause()
3583{
Steve Block3856b092011-10-20 11:56:00 +01003584 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 sp<ThreadBase> thread = mThread.promote();
3586 if (thread != 0) {
3587 Mutex::Autolock _l(thread->mLock);
3588 if (mState == ACTIVE || mState == RESUMING) {
3589 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003590 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 if (!isOutputTrack()) {
3592 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003593 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003594 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003595 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003597
3598 // to track the speaker usage
3599 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 }
3601 }
3602 }
3603}
3604
3605void AudioFlinger::PlaybackThread::Track::flush()
3606{
Steve Block3856b092011-10-20 11:56:00 +01003607 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 sp<ThreadBase> thread = mThread.promote();
3609 if (thread != 0) {
3610 Mutex::Autolock _l(thread->mLock);
3611 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3612 return;
3613 }
3614 // No point remaining in PAUSED state after a flush => go to
3615 // STOPPED state
3616 mState = STOPPED;
3617
Eric Laurent38ccae22011-03-28 18:37:07 -07003618 // do not reset the track if it is still in the process of being stopped or paused.
3619 // this will be done by prepareTracks_l() when the track is stopped.
3620 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3621 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3622 reset();
3623 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624 }
3625}
3626
3627void AudioFlinger::PlaybackThread::Track::reset()
3628{
3629 // Do not reset twice to avoid discarding data written just after a flush and before
3630 // the audioflinger thread detects the track is stopped.
3631 if (!mResetDone) {
3632 TrackBase::reset();
3633 // Force underrun condition to avoid false underrun callback until first data is
3634 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003635 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3636 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 mFillingUpStatus = FS_FILLING;
3638 mResetDone = true;
3639 }
3640}
3641
3642void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3643{
3644 mMute = muted;
3645}
3646
3647void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3648{
3649 mVolume[0] = left;
3650 mVolume[1] = right;
3651}
3652
3653status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3654{
3655 status_t status = DEAD_OBJECT;
3656 sp<ThreadBase> thread = mThread.promote();
3657 if (thread != 0) {
3658 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3659 status = playbackThread->attachAuxEffect(this, EffectId);
3660 }
3661 return status;
3662}
3663
3664void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3665{
3666 mAuxEffectId = EffectId;
3667 mAuxBuffer = buffer;
3668}
3669
3670// ----------------------------------------------------------------------------
3671
3672// RecordTrack constructor must be called with AudioFlinger::mLock held
3673AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3674 const wp<ThreadBase>& thread,
3675 const sp<Client>& client,
3676 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003677 uint32_t format,
3678 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003679 int frameCount,
3680 uint32_t flags,
3681 int sessionId)
3682 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003683 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684 mOverflow(false)
3685{
3686 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003687 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003688 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003689 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003690 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003691 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692 } else {
3693 mCblk->frameSize = sizeof(int8_t);
3694 }
3695 }
3696}
3697
3698AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3699{
3700 sp<ThreadBase> thread = mThread.promote();
3701 if (thread != 0) {
3702 AudioSystem::releaseInput(thread->id());
3703 }
3704}
3705
3706status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3707{
3708 audio_track_cblk_t* cblk = this->cblk();
3709 uint32_t framesAvail;
3710 uint32_t framesReq = buffer->frameCount;
3711
3712 // Check if last stepServer failed, try to step now
3713 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3714 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003715 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3717 }
3718
3719 framesAvail = cblk->framesAvailable_l();
3720
Glenn Kastenf6b16782011-12-15 09:51:17 -08003721 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722 uint32_t s = cblk->server;
3723 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3724
3725 if (framesReq > framesAvail) {
3726 framesReq = framesAvail;
3727 }
3728 if (s + framesReq > bufferEnd) {
3729 framesReq = bufferEnd - s;
3730 }
3731
3732 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003733 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734
3735 buffer->frameCount = framesReq;
3736 return NO_ERROR;
3737 }
3738
3739getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003740 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741 buffer->frameCount = 0;
3742 return NOT_ENOUGH_DATA;
3743}
3744
3745status_t AudioFlinger::RecordThread::RecordTrack::start()
3746{
3747 sp<ThreadBase> thread = mThread.promote();
3748 if (thread != 0) {
3749 RecordThread *recordThread = (RecordThread *)thread.get();
3750 return recordThread->start(this);
3751 } else {
3752 return BAD_VALUE;
3753 }
3754}
3755
3756void AudioFlinger::RecordThread::RecordTrack::stop()
3757{
3758 sp<ThreadBase> thread = mThread.promote();
3759 if (thread != 0) {
3760 RecordThread *recordThread = (RecordThread *)thread.get();
3761 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003762 TrackBase::reset();
3763 // Force overerrun condition to avoid false overrun callback until first data is
3764 // read from buffer
3765 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003766 }
3767}
3768
3769void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3770{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003771 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 (mClient == NULL) ? getpid() : mClient->pid(),
3773 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003774 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 mSessionId,
3776 mFrameCount,
3777 mState,
3778 mCblk->sampleRate,
3779 mCblk->server,
3780 mCblk->user);
3781}
3782
3783
3784// ----------------------------------------------------------------------------
3785
3786AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3787 const wp<ThreadBase>& thread,
3788 DuplicatingThread *sourceThread,
3789 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003790 uint32_t format,
3791 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003793 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003794 mActive(false), mSourceThread(sourceThread)
3795{
3796
3797 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3798 if (mCblk != NULL) {
3799 mCblk->flags |= CBLK_DIRECTION_OUT;
3800 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3801 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3802 mOutBuffer.frameCount = 0;
3803 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003804 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003805 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3806 mCblk, mBuffer, mCblk->buffers,
3807 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003809 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810 }
3811}
3812
3813AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3814{
3815 clearBufferQueue();
3816}
3817
3818status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3819{
3820 status_t status = Track::start();
3821 if (status != NO_ERROR) {
3822 return status;
3823 }
3824
3825 mActive = true;
3826 mRetryCount = 127;
3827 return status;
3828}
3829
3830void AudioFlinger::PlaybackThread::OutputTrack::stop()
3831{
3832 Track::stop();
3833 clearBufferQueue();
3834 mOutBuffer.frameCount = 0;
3835 mActive = false;
3836}
3837
3838bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3839{
3840 Buffer *pInBuffer;
3841 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003842 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 bool outputBufferFull = false;
3844 inBuffer.frameCount = frames;
3845 inBuffer.i16 = data;
3846
3847 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3848
3849 if (!mActive && frames != 0) {
3850 start();
3851 sp<ThreadBase> thread = mThread.promote();
3852 if (thread != 0) {
3853 MixerThread *mixerThread = (MixerThread *)thread.get();
3854 if (mCblk->frameCount > frames){
3855 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3856 uint32_t startFrames = (mCblk->frameCount - frames);
3857 pInBuffer = new Buffer;
3858 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3859 pInBuffer->frameCount = startFrames;
3860 pInBuffer->i16 = pInBuffer->mBuffer;
3861 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3862 mBufferQueue.add(pInBuffer);
3863 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003864 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 }
3866 }
3867 }
3868 }
3869
3870 while (waitTimeLeftMs) {
3871 // First write pending buffers, then new data
3872 if (mBufferQueue.size()) {
3873 pInBuffer = mBufferQueue.itemAt(0);
3874 } else {
3875 pInBuffer = &inBuffer;
3876 }
3877
3878 if (pInBuffer->frameCount == 0) {
3879 break;
3880 }
3881
3882 if (mOutBuffer.frameCount == 0) {
3883 mOutBuffer.frameCount = pInBuffer->frameCount;
3884 nsecs_t startTime = systemTime();
3885 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003886 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 outputBufferFull = true;
3888 break;
3889 }
3890 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3891 if (waitTimeLeftMs >= waitTimeMs) {
3892 waitTimeLeftMs -= waitTimeMs;
3893 } else {
3894 waitTimeLeftMs = 0;
3895 }
3896 }
3897
3898 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3899 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3900 mCblk->stepUser(outFrames);
3901 pInBuffer->frameCount -= outFrames;
3902 pInBuffer->i16 += outFrames * channelCount;
3903 mOutBuffer.frameCount -= outFrames;
3904 mOutBuffer.i16 += outFrames * channelCount;
3905
3906 if (pInBuffer->frameCount == 0) {
3907 if (mBufferQueue.size()) {
3908 mBufferQueue.removeAt(0);
3909 delete [] pInBuffer->mBuffer;
3910 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003911 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912 } else {
3913 break;
3914 }
3915 }
3916 }
3917
3918 // If we could not write all frames, allocate a buffer and queue it for next time.
3919 if (inBuffer.frameCount) {
3920 sp<ThreadBase> thread = mThread.promote();
3921 if (thread != 0 && !thread->standby()) {
3922 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3923 pInBuffer = new Buffer;
3924 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3925 pInBuffer->frameCount = inBuffer.frameCount;
3926 pInBuffer->i16 = pInBuffer->mBuffer;
3927 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3928 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003929 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003931 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 }
3933 }
3934 }
3935
3936 // Calling write() with a 0 length buffer, means that no more data will be written:
3937 // If no more buffers are pending, fill output track buffer to make sure it is started
3938 // by output mixer.
3939 if (frames == 0 && mBufferQueue.size() == 0) {
3940 if (mCblk->user < mCblk->frameCount) {
3941 frames = mCblk->frameCount - mCblk->user;
3942 pInBuffer = new Buffer;
3943 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3944 pInBuffer->frameCount = frames;
3945 pInBuffer->i16 = pInBuffer->mBuffer;
3946 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3947 mBufferQueue.add(pInBuffer);
3948 } else if (mActive) {
3949 stop();
3950 }
3951 }
3952
3953 return outputBufferFull;
3954}
3955
3956status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3957{
3958 int active;
3959 status_t result;
3960 audio_track_cblk_t* cblk = mCblk;
3961 uint32_t framesReq = buffer->frameCount;
3962
Steve Block3856b092011-10-20 11:56:00 +01003963// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 buffer->frameCount = 0;
3965
3966 uint32_t framesAvail = cblk->framesAvailable();
3967
3968
3969 if (framesAvail == 0) {
3970 Mutex::Autolock _l(cblk->lock);
3971 goto start_loop_here;
3972 while (framesAvail == 0) {
3973 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003974 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003975 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 return AudioTrack::NO_MORE_BUFFERS;
3977 }
3978 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3979 if (result != NO_ERROR) {
3980 return AudioTrack::NO_MORE_BUFFERS;
3981 }
3982 // read the server count again
3983 start_loop_here:
3984 framesAvail = cblk->framesAvailable_l();
3985 }
3986 }
3987
3988// if (framesAvail < framesReq) {
3989// return AudioTrack::NO_MORE_BUFFERS;
3990// }
3991
3992 if (framesReq > framesAvail) {
3993 framesReq = framesAvail;
3994 }
3995
3996 uint32_t u = cblk->user;
3997 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3998
3999 if (u + framesReq > bufferEnd) {
4000 framesReq = bufferEnd - u;
4001 }
4002
4003 buffer->frameCount = framesReq;
4004 buffer->raw = (void *)cblk->buffer(u);
4005 return NO_ERROR;
4006}
4007
4008
4009void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4010{
4011 size_t size = mBufferQueue.size();
4012 Buffer *pBuffer;
4013
4014 for (size_t i = 0; i < size; i++) {
4015 pBuffer = mBufferQueue.itemAt(i);
4016 delete [] pBuffer->mBuffer;
4017 delete pBuffer;
4018 }
4019 mBufferQueue.clear();
4020}
4021
4022// ----------------------------------------------------------------------------
4023
4024AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4025 : RefBase(),
4026 mAudioFlinger(audioFlinger),
4027 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4028 mPid(pid)
4029{
4030 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4031}
4032
4033// Client destructor must be called with AudioFlinger::mLock held
4034AudioFlinger::Client::~Client()
4035{
4036 mAudioFlinger->removeClient_l(mPid);
4037}
4038
4039const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4040{
4041 return mMemoryDealer;
4042}
4043
4044// ----------------------------------------------------------------------------
4045
4046AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4047 const sp<IAudioFlingerClient>& client,
4048 pid_t pid)
4049 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4050{
4051}
4052
4053AudioFlinger::NotificationClient::~NotificationClient()
4054{
4055 mClient.clear();
4056}
4057
4058void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4059{
4060 sp<NotificationClient> keep(this);
4061 {
4062 mAudioFlinger->removeNotificationClient(mPid);
4063 }
4064}
4065
4066// ----------------------------------------------------------------------------
4067
4068AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4069 : BnAudioTrack(),
4070 mTrack(track)
4071{
4072}
4073
4074AudioFlinger::TrackHandle::~TrackHandle() {
4075 // just stop the track on deletion, associated resources
4076 // will be freed from the main thread once all pending buffers have
4077 // been played. Unless it's not in the active track list, in which
4078 // case we free everything now...
4079 mTrack->destroy();
4080}
4081
4082status_t AudioFlinger::TrackHandle::start() {
4083 return mTrack->start();
4084}
4085
4086void AudioFlinger::TrackHandle::stop() {
4087 mTrack->stop();
4088}
4089
4090void AudioFlinger::TrackHandle::flush() {
4091 mTrack->flush();
4092}
4093
4094void AudioFlinger::TrackHandle::mute(bool e) {
4095 mTrack->mute(e);
4096}
4097
4098void AudioFlinger::TrackHandle::pause() {
4099 mTrack->pause();
4100}
4101
4102void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4103 mTrack->setVolume(left, right);
4104}
4105
4106sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4107 return mTrack->getCblk();
4108}
4109
4110status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4111{
4112 return mTrack->attachAuxEffect(EffectId);
4113}
4114
4115status_t AudioFlinger::TrackHandle::onTransact(
4116 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4117{
4118 return BnAudioTrack::onTransact(code, data, reply, flags);
4119}
4120
4121// ----------------------------------------------------------------------------
4122
4123sp<IAudioRecord> AudioFlinger::openRecord(
4124 pid_t pid,
4125 int input,
4126 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004127 uint32_t format,
4128 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 int frameCount,
4130 uint32_t flags,
4131 int *sessionId,
4132 status_t *status)
4133{
4134 sp<RecordThread::RecordTrack> recordTrack;
4135 sp<RecordHandle> recordHandle;
4136 sp<Client> client;
4137 wp<Client> wclient;
4138 status_t lStatus;
4139 RecordThread *thread;
4140 size_t inFrameCount;
4141 int lSessionId;
4142
4143 // check calling permissions
4144 if (!recordingAllowed()) {
4145 lStatus = PERMISSION_DENIED;
4146 goto Exit;
4147 }
4148
4149 // add client to list
4150 { // scope for mLock
4151 Mutex::Autolock _l(mLock);
4152 thread = checkRecordThread_l(input);
4153 if (thread == NULL) {
4154 lStatus = BAD_VALUE;
4155 goto Exit;
4156 }
4157
4158 wclient = mClients.valueFor(pid);
4159 if (wclient != NULL) {
4160 client = wclient.promote();
4161 } else {
4162 client = new Client(this, pid);
4163 mClients.add(pid, client);
4164 }
4165
4166 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004167 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 lSessionId = *sessionId;
4169 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004170 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 if (sessionId != NULL) {
4172 *sessionId = lSessionId;
4173 }
4174 }
4175 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004176 recordTrack = thread->createRecordTrack_l(client,
4177 sampleRate,
4178 format,
4179 channelMask,
4180 frameCount,
4181 flags,
4182 lSessionId,
4183 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004185 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4187 // destructor is called by the TrackBase destructor with mLock held
4188 client.clear();
4189 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 goto Exit;
4191 }
4192
4193 // return to handle to client
4194 recordHandle = new RecordHandle(recordTrack);
4195 lStatus = NO_ERROR;
4196
4197Exit:
4198 if (status) {
4199 *status = lStatus;
4200 }
4201 return recordHandle;
4202}
4203
4204// ----------------------------------------------------------------------------
4205
4206AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4207 : BnAudioRecord(),
4208 mRecordTrack(recordTrack)
4209{
4210}
4211
4212AudioFlinger::RecordHandle::~RecordHandle() {
4213 stop();
4214}
4215
4216status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004217 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218 return mRecordTrack->start();
4219}
4220
4221void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004222 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 mRecordTrack->stop();
4224}
4225
4226sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4227 return mRecordTrack->getCblk();
4228}
4229
4230status_t AudioFlinger::RecordHandle::onTransact(
4231 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4232{
4233 return BnAudioRecord::onTransact(code, data, reply, flags);
4234}
4235
4236// ----------------------------------------------------------------------------
4237
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004238AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4239 AudioStreamIn *input,
4240 uint32_t sampleRate,
4241 uint32_t channels,
4242 int id,
4243 uint32_t device) :
4244 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004245 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004247 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004248
4249 snprintf(mName, kNameLength, "AudioIn_%d", id);
4250
Dima Zavinfce7a472011-04-19 22:30:36 -07004251 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 mReqSampleRate = sampleRate;
4253 readInputParameters();
4254}
4255
4256
4257AudioFlinger::RecordThread::~RecordThread()
4258{
4259 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004260 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261 delete mResampler;
4262 delete[] mRsmpOutBuffer;
4263 }
4264}
4265
4266void AudioFlinger::RecordThread::onFirstRef()
4267{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004268 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269}
4270
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004271status_t AudioFlinger::RecordThread::readyToRun()
4272{
4273 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004274 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004275 return status;
4276}
4277
Mathias Agopian65ab4712010-07-14 17:59:35 -07004278bool AudioFlinger::RecordThread::threadLoop()
4279{
4280 AudioBufferProvider::Buffer buffer;
4281 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004282 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283
Eric Laurent44d98482010-09-30 16:12:31 -07004284 nsecs_t lastWarning = 0;
4285
Eric Laurentfeb0db62011-07-22 09:04:31 -07004286 acquireWakeLock();
4287
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 // start recording
4289 while (!exitPending()) {
4290
4291 processConfigEvents();
4292
4293 { // scope for mLock
4294 Mutex::Autolock _l(mLock);
4295 checkForNewParameters_l();
4296 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4297 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004298 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 mStandby = true;
4300 }
4301
4302 if (exitPending()) break;
4303
Eric Laurentfeb0db62011-07-22 09:04:31 -07004304 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004305 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 // go to sleep
4307 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004308 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004309 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 continue;
4311 }
4312 if (mActiveTrack != 0) {
4313 if (mActiveTrack->mState == TrackBase::PAUSING) {
4314 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004315 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 mStandby = true;
4317 }
4318 mActiveTrack.clear();
4319 mStartStopCond.broadcast();
4320 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4321 if (mReqChannelCount != mActiveTrack->channelCount()) {
4322 mActiveTrack.clear();
4323 mStartStopCond.broadcast();
4324 } else if (mBytesRead != 0) {
4325 // record start succeeds only if first read from audio input
4326 // succeeds
4327 if (mBytesRead > 0) {
4328 mActiveTrack->mState = TrackBase::ACTIVE;
4329 } else {
4330 mActiveTrack.clear();
4331 }
4332 mStartStopCond.broadcast();
4333 }
4334 mStandby = false;
4335 }
4336 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004337 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 }
4339
4340 if (mActiveTrack != 0) {
4341 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4342 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004343 unlockEffectChains(effectChains);
4344 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345 continue;
4346 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004347 for (size_t i = 0; i < effectChains.size(); i ++) {
4348 effectChains[i]->process_l();
4349 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004350
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004352 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004353 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004354 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 // no resampling
4356 while (framesOut) {
4357 size_t framesIn = mFrameCount - mRsmpInIndex;
4358 if (framesIn) {
4359 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4360 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4361 if (framesIn > framesOut)
4362 framesIn = framesOut;
4363 mRsmpInIndex += framesIn;
4364 framesOut -= framesIn;
4365 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004366 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004367 memcpy(dst, src, framesIn * mFrameSize);
4368 } else {
4369 int16_t *src16 = (int16_t *)src;
4370 int16_t *dst16 = (int16_t *)dst;
4371 if (mChannelCount == 1) {
4372 while (framesIn--) {
4373 *dst16++ = *src16;
4374 *dst16++ = *src16++;
4375 }
4376 } else {
4377 while (framesIn--) {
4378 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4379 src16 += 2;
4380 }
4381 }
4382 }
4383 }
4384 if (framesOut && mFrameCount == mRsmpInIndex) {
4385 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004386 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004387 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 framesOut = 0;
4389 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004390 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391 mRsmpInIndex = 0;
4392 }
4393 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004394 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4396 // Force input into standby so that it tries to
4397 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004398 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004399 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 }
4401 mRsmpInIndex = mFrameCount;
4402 framesOut = 0;
4403 buffer.frameCount = 0;
4404 }
4405 }
4406 }
4407 } else {
4408 // resampling
4409
4410 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4411 // alter output frame count as if we were expecting stereo samples
4412 if (mChannelCount == 1 && mReqChannelCount == 1) {
4413 framesOut >>= 1;
4414 }
4415 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4416 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4417 // are 32 bit aligned which should be always true.
4418 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004419 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 // the resampler always outputs stereo samples: do post stereo to mono conversion
4421 int16_t *src = (int16_t *)mRsmpOutBuffer;
4422 int16_t *dst = buffer.i16;
4423 while (framesOut--) {
4424 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4425 src += 2;
4426 }
4427 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004428 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004429 }
4430
4431 }
4432 mActiveTrack->releaseBuffer(&buffer);
4433 mActiveTrack->overflow();
4434 }
4435 // client isn't retrieving buffers fast enough
4436 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004437 if (!mActiveTrack->setOverflow()) {
4438 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004439 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004440 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004441 lastWarning = now;
4442 }
4443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 // Release the processor for a while before asking for a new buffer.
4445 // This will give the application more chance to read from the buffer and
4446 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004447 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 }
4449 }
Eric Laurentec437d82011-07-26 20:54:46 -07004450 // enable changes in effect chain
4451 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004452 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 }
4454
4455 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004456 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 }
4458 mActiveTrack.clear();
4459
4460 mStartStopCond.broadcast();
4461
Eric Laurentfeb0db62011-07-22 09:04:31 -07004462 releaseWakeLock();
4463
Steve Block3856b092011-10-20 11:56:00 +01004464 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465 return false;
4466}
4467
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004468
4469sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4470 const sp<AudioFlinger::Client>& client,
4471 uint32_t sampleRate,
4472 int format,
4473 int channelMask,
4474 int frameCount,
4475 uint32_t flags,
4476 int sessionId,
4477 status_t *status)
4478{
4479 sp<RecordTrack> track;
4480 status_t lStatus;
4481
4482 lStatus = initCheck();
4483 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004484 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004485 goto Exit;
4486 }
4487
4488 { // scope for mLock
4489 Mutex::Autolock _l(mLock);
4490
4491 track = new RecordTrack(this, client, sampleRate,
4492 format, channelMask, frameCount, flags, sessionId);
4493
4494 if (track->getCblk() == NULL) {
4495 lStatus = NO_MEMORY;
4496 goto Exit;
4497 }
4498
4499 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004500 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4501 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004502 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004503 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4504 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004505 }
4506 lStatus = NO_ERROR;
4507
4508Exit:
4509 if (status) {
4510 *status = lStatus;
4511 }
4512 return track;
4513}
4514
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4516{
Steve Block3856b092011-10-20 11:56:00 +01004517 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518 sp <ThreadBase> strongMe = this;
4519 status_t status = NO_ERROR;
4520 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004521 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 if (mActiveTrack != 0) {
4523 if (recordTrack != mActiveTrack.get()) {
4524 status = -EBUSY;
4525 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4526 mActiveTrack->mState = TrackBase::ACTIVE;
4527 }
4528 return status;
4529 }
4530
4531 recordTrack->mState = TrackBase::IDLE;
4532 mActiveTrack = recordTrack;
4533 mLock.unlock();
4534 status_t status = AudioSystem::startInput(mId);
4535 mLock.lock();
4536 if (status != NO_ERROR) {
4537 mActiveTrack.clear();
4538 return status;
4539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 mRsmpInIndex = mFrameCount;
4541 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004542 if (mResampler != NULL) {
4543 mResampler->reset();
4544 }
4545 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004547 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 mWaitWorkCV.signal();
4549 // do not wait for mStartStopCond if exiting
4550 if (mExiting) {
4551 mActiveTrack.clear();
4552 status = INVALID_OPERATION;
4553 goto startError;
4554 }
4555 mStartStopCond.wait(mLock);
4556 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004557 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 status = BAD_VALUE;
4559 goto startError;
4560 }
Steve Block3856b092011-10-20 11:56:00 +01004561 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 return status;
4563 }
4564startError:
4565 AudioSystem::stopInput(mId);
4566 return status;
4567}
4568
4569void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004570 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571 sp <ThreadBase> strongMe = this;
4572 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004573 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4575 mActiveTrack->mState = TrackBase::PAUSING;
4576 // do not wait for mStartStopCond if exiting
4577 if (mExiting) {
4578 return;
4579 }
4580 mStartStopCond.wait(mLock);
4581 // if we have been restarted, recordTrack == mActiveTrack.get() here
4582 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4583 mLock.unlock();
4584 AudioSystem::stopInput(mId);
4585 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004586 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 }
4588 }
4589 }
4590}
4591
4592status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4593{
4594 const size_t SIZE = 256;
4595 char buffer[SIZE];
4596 String8 result;
4597 pid_t pid = 0;
4598
4599 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4600 result.append(buffer);
4601
4602 if (mActiveTrack != 0) {
4603 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004604 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 mActiveTrack->dump(buffer, SIZE);
4606 result.append(buffer);
4607
4608 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4609 result.append(buffer);
4610 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4611 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004612 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 result.append(buffer);
4614 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4615 result.append(buffer);
4616 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4617 result.append(buffer);
4618
4619
4620 } else {
4621 result.append("No record client\n");
4622 }
4623 write(fd, result.string(), result.size());
4624
4625 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004626 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627
4628 return NO_ERROR;
4629}
4630
4631status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4632{
4633 size_t framesReq = buffer->frameCount;
4634 size_t framesReady = mFrameCount - mRsmpInIndex;
4635 int channelCount;
4636
4637 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004638 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004640 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4642 // Force input into standby so that it tries to
4643 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004644 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004645 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004646 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004647 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 buffer->frameCount = 0;
4649 return NOT_ENOUGH_DATA;
4650 }
4651 mRsmpInIndex = 0;
4652 framesReady = mFrameCount;
4653 }
4654
4655 if (framesReq > framesReady) {
4656 framesReq = framesReady;
4657 }
4658
4659 if (mChannelCount == 1 && mReqChannelCount == 2) {
4660 channelCount = 1;
4661 } else {
4662 channelCount = 2;
4663 }
4664 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4665 buffer->frameCount = framesReq;
4666 return NO_ERROR;
4667}
4668
4669void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4670{
4671 mRsmpInIndex += buffer->frameCount;
4672 buffer->frameCount = 0;
4673}
4674
4675bool AudioFlinger::RecordThread::checkForNewParameters_l()
4676{
4677 bool reconfig = false;
4678
4679 while (!mNewParameters.isEmpty()) {
4680 status_t status = NO_ERROR;
4681 String8 keyValuePair = mNewParameters[0];
4682 AudioParameter param = AudioParameter(keyValuePair);
4683 int value;
4684 int reqFormat = mFormat;
4685 int reqSamplingRate = mReqSampleRate;
4686 int reqChannelCount = mReqChannelCount;
4687
4688 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4689 reqSamplingRate = value;
4690 reconfig = true;
4691 }
4692 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4693 reqFormat = value;
4694 reconfig = true;
4695 }
4696 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004697 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004698 reconfig = true;
4699 }
4700 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4701 // do not accept frame count changes if tracks are open as the track buffer
4702 // size depends on frame count and correct behavior would not be garantied
4703 // if frame count is changed after track creation
4704 if (mActiveTrack != 0) {
4705 status = INVALID_OPERATION;
4706 } else {
4707 reconfig = true;
4708 }
4709 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004710 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4711 // forward device change to effects that have requested to be
4712 // aware of attached audio device.
4713 for (size_t i = 0; i < mEffectChains.size(); i++) {
4714 mEffectChains[i]->setDevice_l(value);
4715 }
4716 // store input device and output device but do not forward output device to audio HAL.
4717 // Note that status is ignored by the caller for output device
4718 // (see AudioFlinger::setParameters()
4719 if (value & AUDIO_DEVICE_OUT_ALL) {
4720 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4721 status = BAD_VALUE;
4722 } else {
4723 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004724 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4725 if (mTrack != NULL) {
4726 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004727 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004728 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4729 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4730 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004731 }
4732 mDevice |= (uint32_t)value;
4733 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004734 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004735 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004737 mInput->stream->common.standby(&mInput->stream->common);
4738 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739 }
4740 if (reconfig) {
4741 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004742 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004743 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004744 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4745 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004746 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004747 status = NO_ERROR;
4748 }
4749 if (status == NO_ERROR) {
4750 readInputParameters();
4751 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4752 }
4753 }
4754 }
4755
4756 mNewParameters.removeAt(0);
4757
4758 mParamStatus = status;
4759 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004760 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4761 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004762 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004763 }
4764 return reconfig;
4765}
4766
4767String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4768{
Dima Zavinfce7a472011-04-19 22:30:36 -07004769 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004770 String8 out_s8 = String8();
4771
4772 Mutex::Autolock _l(mLock);
4773 if (initCheck() != NO_ERROR) {
4774 return out_s8;
4775 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004776
Dima Zavin799a70e2011-04-18 16:57:27 -07004777 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004778 out_s8 = String8(s);
4779 free(s);
4780 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004781}
4782
4783void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4784 AudioSystem::OutputDescriptor desc;
4785 void *param2 = 0;
4786
4787 switch (event) {
4788 case AudioSystem::INPUT_OPENED:
4789 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004790 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791 desc.samplingRate = mSampleRate;
4792 desc.format = mFormat;
4793 desc.frameCount = mFrameCount;
4794 desc.latency = 0;
4795 param2 = &desc;
4796 break;
4797
4798 case AudioSystem::INPUT_CLOSED:
4799 default:
4800 break;
4801 }
4802 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4803}
4804
4805void AudioFlinger::RecordThread::readInputParameters()
4806{
4807 if (mRsmpInBuffer) delete mRsmpInBuffer;
4808 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4809 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004810 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811
Dima Zavin799a70e2011-04-18 16:57:27 -07004812 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004813 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4814 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004815 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004816 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004817 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818 mFrameCount = mInputBytes / mFrameSize;
4819 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4820
4821 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4822 {
4823 int channelCount;
4824 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4825 // stereo to mono post process as the resampler always outputs stereo.
4826 if (mChannelCount == 1 && mReqChannelCount == 2) {
4827 channelCount = 1;
4828 } else {
4829 channelCount = 2;
4830 }
4831 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4832 mResampler->setSampleRate(mSampleRate);
4833 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4834 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4835
4836 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4837 if (mChannelCount == 1 && mReqChannelCount == 1) {
4838 mFrameCount >>= 1;
4839 }
4840
4841 }
4842 mRsmpInIndex = mFrameCount;
4843}
4844
4845unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4846{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004847 Mutex::Autolock _l(mLock);
4848 if (initCheck() != NO_ERROR) {
4849 return 0;
4850 }
4851
Dima Zavin799a70e2011-04-18 16:57:27 -07004852 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004853}
4854
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004855uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4856{
4857 Mutex::Autolock _l(mLock);
4858 uint32_t result = 0;
4859 if (getEffectChain_l(sessionId) != 0) {
4860 result = EFFECT_SESSION;
4861 }
4862
4863 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4864 result |= TRACK_SESSION;
4865 }
4866
4867 return result;
4868}
4869
Eric Laurent59bd0da2011-08-01 09:52:20 -07004870AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4871{
4872 Mutex::Autolock _l(mLock);
4873 return mTrack;
4874}
4875
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004876AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4877{
4878 Mutex::Autolock _l(mLock);
4879 return mInput;
4880}
4881
4882AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4883{
4884 Mutex::Autolock _l(mLock);
4885 AudioStreamIn *input = mInput;
4886 mInput = NULL;
4887 return input;
4888}
4889
4890// this method must always be called either with ThreadBase mLock held or inside the thread loop
4891audio_stream_t* AudioFlinger::RecordThread::stream()
4892{
4893 if (mInput == NULL) {
4894 return NULL;
4895 }
4896 return &mInput->stream->common;
4897}
4898
4899
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900// ----------------------------------------------------------------------------
4901
4902int AudioFlinger::openOutput(uint32_t *pDevices,
4903 uint32_t *pSamplingRate,
4904 uint32_t *pFormat,
4905 uint32_t *pChannels,
4906 uint32_t *pLatencyMs,
4907 uint32_t flags)
4908{
4909 status_t status;
4910 PlaybackThread *thread = NULL;
4911 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4912 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4913 uint32_t format = pFormat ? *pFormat : 0;
4914 uint32_t channels = pChannels ? *pChannels : 0;
4915 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004916 audio_stream_out_t *outStream;
4917 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918
Steve Block3856b092011-10-20 11:56:00 +01004919 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 pDevices ? *pDevices : 0,
4921 samplingRate,
4922 format,
4923 channels,
4924 flags);
4925
4926 if (pDevices == NULL || *pDevices == 0) {
4927 return 0;
4928 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004929
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930 Mutex::Autolock _l(mLock);
4931
Dima Zavin799a70e2011-04-18 16:57:27 -07004932 outHwDev = findSuitableHwDev_l(*pDevices);
4933 if (outHwDev == NULL)
4934 return 0;
4935
4936 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4937 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004938 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004939 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 samplingRate,
4941 format,
4942 channels,
4943 status);
4944
4945 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004946 if (outStream != NULL) {
4947 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004948 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004949
Dima Zavinfce7a472011-04-19 22:30:36 -07004950 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4951 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4952 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004953 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004954 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 } else {
4956 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004957 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958 }
4959 mPlaybackThreads.add(id, thread);
4960
4961 if (pSamplingRate) *pSamplingRate = samplingRate;
4962 if (pFormat) *pFormat = format;
4963 if (pChannels) *pChannels = channels;
4964 if (pLatencyMs) *pLatencyMs = thread->latency();
4965
4966 // notify client processes of the new output creation
4967 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4968 return id;
4969 }
4970
4971 return 0;
4972}
4973
4974int AudioFlinger::openDuplicateOutput(int output1, int output2)
4975{
4976 Mutex::Autolock _l(mLock);
4977 MixerThread *thread1 = checkMixerThread_l(output1);
4978 MixerThread *thread2 = checkMixerThread_l(output2);
4979
4980 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004981 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 return 0;
4983 }
4984
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004985 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4987 thread->addOutputTrack(thread2);
4988 mPlaybackThreads.add(id, thread);
4989 // notify client processes of the new output creation
4990 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4991 return id;
4992}
4993
4994status_t AudioFlinger::closeOutput(int output)
4995{
4996 // keep strong reference on the playback thread so that
4997 // it is not destroyed while exit() is executed
4998 sp <PlaybackThread> thread;
4999 {
5000 Mutex::Autolock _l(mLock);
5001 thread = checkPlaybackThread_l(output);
5002 if (thread == NULL) {
5003 return BAD_VALUE;
5004 }
5005
Steve Block3856b092011-10-20 11:56:00 +01005006 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005008 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005010 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5012 dupThread->removeOutputTrack((MixerThread *)thread.get());
5013 }
5014 }
5015 }
5016 void *param2 = 0;
5017 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5018 mPlaybackThreads.removeItem(output);
5019 }
5020 thread->exit();
5021
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005022 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005023 AudioStreamOut *out = thread->clearOutput();
5024 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005025 out->hwDev->close_output_stream(out->hwDev, out->stream);
5026 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 }
5028 return NO_ERROR;
5029}
5030
5031status_t AudioFlinger::suspendOutput(int output)
5032{
5033 Mutex::Autolock _l(mLock);
5034 PlaybackThread *thread = checkPlaybackThread_l(output);
5035
5036 if (thread == NULL) {
5037 return BAD_VALUE;
5038 }
5039
Steve Block3856b092011-10-20 11:56:00 +01005040 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 thread->suspend();
5042
5043 return NO_ERROR;
5044}
5045
5046status_t AudioFlinger::restoreOutput(int output)
5047{
5048 Mutex::Autolock _l(mLock);
5049 PlaybackThread *thread = checkPlaybackThread_l(output);
5050
5051 if (thread == NULL) {
5052 return BAD_VALUE;
5053 }
5054
Steve Block3856b092011-10-20 11:56:00 +01005055 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005056
5057 thread->restore();
5058
5059 return NO_ERROR;
5060}
5061
5062int AudioFlinger::openInput(uint32_t *pDevices,
5063 uint32_t *pSamplingRate,
5064 uint32_t *pFormat,
5065 uint32_t *pChannels,
5066 uint32_t acoustics)
5067{
5068 status_t status;
5069 RecordThread *thread = NULL;
5070 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5071 uint32_t format = pFormat ? *pFormat : 0;
5072 uint32_t channels = pChannels ? *pChannels : 0;
5073 uint32_t reqSamplingRate = samplingRate;
5074 uint32_t reqFormat = format;
5075 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005076 audio_stream_in_t *inStream;
5077 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078
5079 if (pDevices == NULL || *pDevices == 0) {
5080 return 0;
5081 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005082
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 Mutex::Autolock _l(mLock);
5084
Dima Zavin799a70e2011-04-18 16:57:27 -07005085 inHwDev = findSuitableHwDev_l(*pDevices);
5086 if (inHwDev == NULL)
5087 return 0;
5088
5089 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5090 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005091 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005092 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005093 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005094 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 samplingRate,
5096 format,
5097 channels,
5098 acoustics,
5099 status);
5100
5101 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5102 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5103 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005104 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005105 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005107 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005108 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005109 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5110 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005111 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005112 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 }
5114
Dima Zavin799a70e2011-04-18 16:57:27 -07005115 if (inStream != NULL) {
5116 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5117
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005118 int id = nextUniqueId();
5119 // Start record thread
5120 // RecorThread require both input and output device indication to forward to audio
5121 // pre processing modules
5122 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5123 thread = new RecordThread(this,
5124 input,
5125 reqSamplingRate,
5126 reqChannels,
5127 id,
5128 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005130 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5132 if (pFormat) *pFormat = format;
5133 if (pChannels) *pChannels = reqChannels;
5134
Dima Zavin799a70e2011-04-18 16:57:27 -07005135 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136
5137 // notify client processes of the new input creation
5138 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5139 return id;
5140 }
5141
5142 return 0;
5143}
5144
5145status_t AudioFlinger::closeInput(int input)
5146{
5147 // keep strong reference on the record thread so that
5148 // it is not destroyed while exit() is executed
5149 sp <RecordThread> thread;
5150 {
5151 Mutex::Autolock _l(mLock);
5152 thread = checkRecordThread_l(input);
5153 if (thread == NULL) {
5154 return BAD_VALUE;
5155 }
5156
Steve Block3856b092011-10-20 11:56:00 +01005157 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158 void *param2 = 0;
5159 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5160 mRecordThreads.removeItem(input);
5161 }
5162 thread->exit();
5163
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005164 AudioStreamIn *in = thread->clearInput();
5165 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005166 in->hwDev->close_input_stream(in->hwDev, in->stream);
5167 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168
5169 return NO_ERROR;
5170}
5171
Glenn Kastenfff6d712012-01-12 16:38:12 -08005172status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173{
5174 Mutex::Autolock _l(mLock);
5175 MixerThread *dstThread = checkMixerThread_l(output);
5176 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005177 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 return BAD_VALUE;
5179 }
5180
Steve Block3856b092011-10-20 11:56:00 +01005181 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5183
Eric Laurent9f6530f2011-08-30 10:18:54 -07005184 dstThread->setStreamValid(stream, true);
5185
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5187 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5188 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005189 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005191 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005193 }
Eric Laurentde070132010-07-13 04:45:46 -07005194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005195
5196 return NO_ERROR;
5197}
5198
5199
5200int AudioFlinger::newAudioSessionId()
5201{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005202 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203}
5204
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005205void AudioFlinger::acquireAudioSessionId(int audioSession)
5206{
5207 Mutex::Autolock _l(mLock);
5208 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005209 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005210 int num = mAudioSessionRefs.size();
5211 for (int i = 0; i< num; i++) {
5212 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5213 if (ref->sessionid == audioSession && ref->pid == caller) {
5214 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005215 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005216 return;
5217 }
5218 }
5219 AudioSessionRef *ref = new AudioSessionRef();
5220 ref->sessionid = audioSession;
5221 ref->pid = caller;
5222 ref->cnt = 1;
5223 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005224 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005225}
5226
5227void AudioFlinger::releaseAudioSessionId(int audioSession)
5228{
5229 Mutex::Autolock _l(mLock);
5230 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005231 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005232 int num = mAudioSessionRefs.size();
5233 for (int i = 0; i< num; i++) {
5234 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5235 if (ref->sessionid == audioSession && ref->pid == caller) {
5236 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005237 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005238 if (ref->cnt == 0) {
5239 mAudioSessionRefs.removeAt(i);
5240 delete ref;
5241 purgeStaleEffects_l();
5242 }
5243 return;
5244 }
5245 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005246 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005247}
5248
5249void AudioFlinger::purgeStaleEffects_l() {
5250
Steve Block3856b092011-10-20 11:56:00 +01005251 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005252
5253 Vector< sp<EffectChain> > chains;
5254
5255 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5256 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5257 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5258 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005259 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5260 chains.push(ec);
5261 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005262 }
5263 }
5264 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5265 sp<RecordThread> t = mRecordThreads.valueAt(i);
5266 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5267 sp<EffectChain> ec = t->mEffectChains[j];
5268 chains.push(ec);
5269 }
5270 }
5271
5272 for (size_t i = 0; i < chains.size(); i++) {
5273 sp<EffectChain> ec = chains[i];
5274 int sessionid = ec->sessionId();
5275 sp<ThreadBase> t = ec->mThread.promote();
5276 if (t == 0) {
5277 continue;
5278 }
5279 size_t numsessionrefs = mAudioSessionRefs.size();
5280 bool found = false;
5281 for (size_t k = 0; k < numsessionrefs; k++) {
5282 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5283 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005284 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005285 sessionid, ref->pid, ref->cnt);
5286 found = true;
5287 break;
5288 }
5289 }
5290 if (!found) {
5291 // remove all effects from the chain
5292 while (ec->mEffects.size()) {
5293 sp<EffectModule> effect = ec->mEffects[0];
5294 effect->unPin();
5295 Mutex::Autolock _l (t->mLock);
5296 t->removeEffect_l(effect);
5297 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5298 sp<EffectHandle> handle = effect->mHandles[j].promote();
5299 if (handle != 0) {
5300 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005301 if (handle->mHasControl && handle->mEnabled) {
5302 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5303 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005304 }
5305 }
5306 AudioSystem::unregisterEffect(effect->id());
5307 }
5308 }
5309 }
5310 return;
5311}
5312
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5314AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5315{
5316 PlaybackThread *thread = NULL;
5317 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5318 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5319 }
5320 return thread;
5321}
5322
5323// checkMixerThread_l() must be called with AudioFlinger::mLock held
5324AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5325{
5326 PlaybackThread *thread = checkPlaybackThread_l(output);
5327 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005328 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 thread = NULL;
5330 }
5331 }
5332 return (MixerThread *)thread;
5333}
5334
5335// checkRecordThread_l() must be called with AudioFlinger::mLock held
5336AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5337{
5338 RecordThread *thread = NULL;
5339 if (mRecordThreads.indexOfKey(input) >= 0) {
5340 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5341 }
5342 return thread;
5343}
5344
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005345uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005347 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348}
5349
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005350AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5351{
5352 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5353 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005354 AudioStreamOut *output = thread->getOutput();
5355 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005356 return thread;
5357 }
5358 }
5359 return NULL;
5360}
5361
5362uint32_t AudioFlinger::primaryOutputDevice_l()
5363{
5364 PlaybackThread *thread = primaryPlaybackThread_l();
5365
5366 if (thread == NULL) {
5367 return 0;
5368 }
5369
5370 return thread->device();
5371}
5372
5373
Mathias Agopian65ab4712010-07-14 17:59:35 -07005374// ----------------------------------------------------------------------------
5375// Effect management
5376// ----------------------------------------------------------------------------
5377
5378
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5380{
5381 Mutex::Autolock _l(mLock);
5382 return EffectQueryNumberEffects(numEffects);
5383}
5384
5385status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5386{
5387 Mutex::Autolock _l(mLock);
5388 return EffectQueryEffect(index, descriptor);
5389}
5390
5391status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5392{
5393 Mutex::Autolock _l(mLock);
5394 return EffectGetDescriptor(pUuid, descriptor);
5395}
5396
5397
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5399 effect_descriptor_t *pDesc,
5400 const sp<IEffectClient>& effectClient,
5401 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005402 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 int sessionId,
5404 status_t *status,
5405 int *id,
5406 int *enabled)
5407{
5408 status_t lStatus = NO_ERROR;
5409 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 effect_descriptor_t desc;
5411 sp<Client> client;
5412 wp<Client> wclient;
5413
Steve Block3856b092011-10-20 11:56:00 +01005414 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005415 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416
5417 if (pDesc == NULL) {
5418 lStatus = BAD_VALUE;
5419 goto Exit;
5420 }
5421
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005423 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 lStatus = PERMISSION_DENIED;
5425 goto Exit;
5426 }
5427
Dima Zavinfce7a472011-04-19 22:30:36 -07005428 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005429 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005430 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005431 lStatus = PERMISSION_DENIED;
5432 goto Exit;
5433 }
5434
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005435 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005436 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005437 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005438 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005439 lStatus = BAD_VALUE;
5440 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005441 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005442 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005443 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005444 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005445 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005446 }
5447 }
5448
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 {
5450 Mutex::Autolock _l(mLock);
5451
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452
5453 if (!EffectIsNullUuid(&pDesc->uuid)) {
5454 // if uuid is specified, request effect descriptor
5455 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5456 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005457 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 goto Exit;
5459 }
5460 } else {
5461 // if uuid is not specified, look for an available implementation
5462 // of the required type in effect factory
5463 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005464 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 lStatus = BAD_VALUE;
5466 goto Exit;
5467 }
5468 uint32_t numEffects = 0;
5469 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005470 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 bool found = false;
5472
5473 lStatus = EffectQueryNumberEffects(&numEffects);
5474 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005475 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 goto Exit;
5477 }
5478 for (uint32_t i = 0; i < numEffects; i++) {
5479 lStatus = EffectQueryEffect(i, &desc);
5480 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005481 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 continue;
5483 }
5484 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5485 // If matching type found save effect descriptor. If the session is
5486 // 0 and the effect is not auxiliary, continue enumeration in case
5487 // an auxiliary version of this effect type is available
5488 found = true;
5489 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005490 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5492 break;
5493 }
5494 }
5495 }
5496 if (!found) {
5497 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005498 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005499 goto Exit;
5500 }
5501 // For same effect type, chose auxiliary version over insert version if
5502 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005503 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5505 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5506 }
5507 }
5508
5509 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005510 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5512 lStatus = INVALID_OPERATION;
5513 goto Exit;
5514 }
5515
Eric Laurent59255e42011-07-27 19:49:51 -07005516 // check recording permission for visualizer
5517 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5518 !recordingAllowed()) {
5519 lStatus = PERMISSION_DENIED;
5520 goto Exit;
5521 }
5522
Mathias Agopian65ab4712010-07-14 17:59:35 -07005523 // return effect descriptor
5524 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5525
5526 // If output is not specified try to find a matching audio session ID in one of the
5527 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005528 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5529 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005530 // Note: io is never 0 when creating an effect on an input
5531 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005532 // look for the thread where the specified audio session is present
5533 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5534 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005535 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005536 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005539 if (io == 0) {
5540 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5541 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5542 io = mRecordThreads.keyAt(i);
5543 break;
5544 }
5545 }
5546 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005547 // If no output thread contains the requested session ID, default to
5548 // first output. The effect chain will be moved to the correct output
5549 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005550 if (io == 0 && mPlaybackThreads.size()) {
5551 io = mPlaybackThreads.keyAt(0);
5552 }
Steve Block3856b092011-10-20 11:56:00 +01005553 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005554 }
5555 ThreadBase *thread = checkRecordThread_l(io);
5556 if (thread == NULL) {
5557 thread = checkPlaybackThread_l(io);
5558 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005559 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005560 lStatus = BAD_VALUE;
5561 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005562 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005563 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005564
Mathias Agopian65ab4712010-07-14 17:59:35 -07005565 wclient = mClients.valueFor(pid);
5566
5567 if (wclient != NULL) {
5568 client = wclient.promote();
5569 } else {
5570 client = new Client(this, pid);
5571 mClients.add(pid, client);
5572 }
5573
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005574 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005575 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5576 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 if (handle != 0 && id != NULL) {
5578 *id = handle->id();
5579 }
5580 }
5581
5582Exit:
5583 if(status) {
5584 *status = lStatus;
5585 }
5586 return handle;
5587}
5588
Eric Laurent59255e42011-07-27 19:49:51 -07005589status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005590{
Steve Block3856b092011-10-20 11:56:00 +01005591 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005592 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005593 Mutex::Autolock _l(mLock);
5594 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005595 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005596 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005597 }
Eric Laurentde070132010-07-13 04:45:46 -07005598 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5599 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005600 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005601 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602 }
Eric Laurentde070132010-07-13 04:45:46 -07005603 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5604 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005605 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005606 return BAD_VALUE;
5607 }
5608
5609 Mutex::Autolock _dl(dstThread->mLock);
5610 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005611 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005612
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 return NO_ERROR;
5614}
5615
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005616// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005617status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005618 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005619 AudioFlinger::PlaybackThread *dstThread,
5620 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005621{
Steve Block3856b092011-10-20 11:56:00 +01005622 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005623 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005624
Eric Laurent59255e42011-07-27 19:49:51 -07005625 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005626 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005627 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005628 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005629 return INVALID_OPERATION;
5630 }
5631
Eric Laurent39e94f82010-07-28 01:32:47 -07005632 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005633 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005634 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005635 // removed.
5636 srcThread->removeEffectChain_l(chain);
5637
5638 // transfer all effects one by one so that new effect chain is created on new thread with
5639 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005640 int dstOutput = dstThread->id();
5641 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005642 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005643 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5644 while (effect != 0) {
5645 srcThread->removeEffect_l(effect);
5646 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005647 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5648 if (effect->state() == EffectModule::ACTIVE ||
5649 effect->state() == EffectModule::STOPPING) {
5650 effect->start();
5651 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005652 // if the move request is not received from audio policy manager, the effect must be
5653 // re-registered with the new strategy and output
5654 if (dstChain == 0) {
5655 dstChain = effect->chain().promote();
5656 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005657 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005658 srcThread->addEffect_l(effect);
5659 return NO_INIT;
5660 }
5661 strategy = dstChain->strategy();
5662 }
5663 if (reRegister) {
5664 AudioSystem::unregisterEffect(effect->id());
5665 AudioSystem::registerEffect(&effect->desc(),
5666 dstOutput,
5667 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005668 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005669 effect->id());
5670 }
Eric Laurentde070132010-07-13 04:45:46 -07005671 effect = chain->getEffectFromId_l(0);
5672 }
5673
5674 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675}
5676
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005677
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005679sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 const sp<AudioFlinger::Client>& client,
5681 const sp<IEffectClient>& effectClient,
5682 int32_t priority,
5683 int sessionId,
5684 effect_descriptor_t *desc,
5685 int *enabled,
5686 status_t *status
5687 )
5688{
5689 sp<EffectModule> effect;
5690 sp<EffectHandle> handle;
5691 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005693 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 bool effectCreated = false;
5695 bool effectRegistered = false;
5696
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005697 lStatus = initCheck();
5698 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005699 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700 goto Exit;
5701 }
5702
5703 // Do not allow effects with session ID 0 on direct output or duplicating threads
5704 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005705 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005706 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005707 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708 lStatus = BAD_VALUE;
5709 goto Exit;
5710 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005711 // Only Pre processor effects are allowed on input threads and only on input threads
5712 if ((mType == RECORD &&
5713 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5714 (mType != RECORD &&
5715 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005716 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005717 desc->name, desc->flags, mType);
5718 lStatus = BAD_VALUE;
5719 goto Exit;
5720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721
Steve Block3856b092011-10-20 11:56:00 +01005722 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723
5724 { // scope for mLock
5725 Mutex::Autolock _l(mLock);
5726
5727 // check for existing effect chain with the requested audio session
5728 chain = getEffectChain_l(sessionId);
5729 if (chain == 0) {
5730 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005731 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 chain = new EffectChain(this, sessionId);
5733 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005734 chain->setStrategy(getStrategyForSession_l(sessionId));
5735 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005737 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 }
5739
Steve Block3856b092011-10-20 11:56:00 +01005740 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741
5742 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005743 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005745 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 if (lStatus != NO_ERROR) {
5747 goto Exit;
5748 }
5749 effectRegistered = true;
5750 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005751 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752 lStatus = effect->status();
5753 if (lStatus != NO_ERROR) {
5754 goto Exit;
5755 }
Eric Laurentcab11242010-07-15 12:50:15 -07005756 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005757 if (lStatus != NO_ERROR) {
5758 goto Exit;
5759 }
5760 effectCreated = true;
5761
5762 effect->setDevice(mDevice);
5763 effect->setMode(mAudioFlinger->getMode());
5764 }
5765 // create effect handle and connect it to effect module
5766 handle = new EffectHandle(effect, client, effectClient, priority);
5767 lStatus = effect->addHandle(handle);
5768 if (enabled) {
5769 *enabled = (int)effect->isEnabled();
5770 }
5771 }
5772
5773Exit:
5774 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005775 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005777 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778 }
5779 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005780 AudioSystem::unregisterEffect(effect->id());
5781 }
5782 if (chainCreated) {
5783 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005784 }
5785 handle.clear();
5786 }
5787
5788 if(status) {
5789 *status = lStatus;
5790 }
5791 return handle;
5792}
5793
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005794sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5795{
5796 sp<EffectModule> effect;
5797
5798 sp<EffectChain> chain = getEffectChain_l(sessionId);
5799 if (chain != 0) {
5800 effect = chain->getEffectFromId_l(effectId);
5801 }
5802 return effect;
5803}
5804
Eric Laurentde070132010-07-13 04:45:46 -07005805// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5806// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005807status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005808{
5809 // check for existing effect chain with the requested audio session
5810 int sessionId = effect->sessionId();
5811 sp<EffectChain> chain = getEffectChain_l(sessionId);
5812 bool chainCreated = false;
5813
5814 if (chain == 0) {
5815 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005816 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005817 chain = new EffectChain(this, sessionId);
5818 addEffectChain_l(chain);
5819 chain->setStrategy(getStrategyForSession_l(sessionId));
5820 chainCreated = true;
5821 }
Steve Block3856b092011-10-20 11:56:00 +01005822 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005823
5824 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005825 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005826 this, effect->desc().name, chain.get());
5827 return BAD_VALUE;
5828 }
5829
5830 status_t status = chain->addEffect_l(effect);
5831 if (status != NO_ERROR) {
5832 if (chainCreated) {
5833 removeEffectChain_l(chain);
5834 }
5835 return status;
5836 }
5837
5838 effect->setDevice(mDevice);
5839 effect->setMode(mAudioFlinger->getMode());
5840 return NO_ERROR;
5841}
5842
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005843void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005844
Steve Block3856b092011-10-20 11:56:00 +01005845 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005846 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005847 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5848 detachAuxEffect_l(effect->id());
5849 }
5850
5851 sp<EffectChain> chain = effect->chain().promote();
5852 if (chain != 0) {
5853 // remove effect chain if removing last effect
5854 if (chain->removeEffect_l(effect) == 0) {
5855 removeEffectChain_l(chain);
5856 }
5857 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005858 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005859 }
5860}
5861
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005862void AudioFlinger::ThreadBase::lockEffectChains_l(
5863 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5864{
5865 effectChains = mEffectChains;
5866 for (size_t i = 0; i < mEffectChains.size(); i++) {
5867 mEffectChains[i]->lock();
5868 }
5869}
5870
5871void AudioFlinger::ThreadBase::unlockEffectChains(
5872 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5873{
5874 for (size_t i = 0; i < effectChains.size(); i++) {
5875 effectChains[i]->unlock();
5876 }
5877}
5878
5879sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5880{
5881 Mutex::Autolock _l(mLock);
5882 return getEffectChain_l(sessionId);
5883}
5884
5885sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5886{
5887 sp<EffectChain> chain;
5888
5889 size_t size = mEffectChains.size();
5890 for (size_t i = 0; i < size; i++) {
5891 if (mEffectChains[i]->sessionId() == sessionId) {
5892 chain = mEffectChains[i];
5893 break;
5894 }
5895 }
5896 return chain;
5897}
5898
5899void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5900{
5901 Mutex::Autolock _l(mLock);
5902 size_t size = mEffectChains.size();
5903 for (size_t i = 0; i < size; i++) {
5904 mEffectChains[i]->setMode_l(mode);
5905 }
5906}
5907
5908void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005909 const wp<EffectHandle>& handle,
5910 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005911
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005913 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 // delete the effect module if removing last handle on it
5915 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005916 if (!effect->isPinned() || unpiniflast) {
5917 removeEffect_l(effect);
5918 AudioSystem::unregisterEffect(effect->id());
5919 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 }
5921}
5922
5923status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5924{
5925 int session = chain->sessionId();
5926 int16_t *buffer = mMixBuffer;
5927 bool ownsBuffer = false;
5928
Steve Block3856b092011-10-20 11:56:00 +01005929 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 if (session > 0) {
5931 // Only one effect chain can be present in direct output thread and it uses
5932 // the mix buffer as input
5933 if (mType != DIRECT) {
5934 size_t numSamples = mFrameCount * mChannelCount;
5935 buffer = new int16_t[numSamples];
5936 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005937 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 ownsBuffer = true;
5939 }
5940
5941 // Attach all tracks with same session ID to this chain.
5942 for (size_t i = 0; i < mTracks.size(); ++i) {
5943 sp<Track> track = mTracks[i];
5944 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005945 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005947 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 }
5949 }
5950
5951 // indicate all active tracks in the chain
5952 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5953 sp<Track> track = mActiveTracks[i].promote();
5954 if (track == 0) continue;
5955 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005956 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005957 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 }
5959 }
5960 }
5961
5962 chain->setInBuffer(buffer, ownsBuffer);
5963 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005964 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005965 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005966 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5967 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005969 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5970 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005971 // Effect chain for other sessions are inserted at beginning of effect
5972 // chains list to be processed before output mix effects. Relative order between other
5973 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 size_t size = mEffectChains.size();
5975 size_t i = 0;
5976 for (i = 0; i < size; i++) {
5977 if (mEffectChains[i]->sessionId() < session) break;
5978 }
5979 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005980 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981
5982 return NO_ERROR;
5983}
5984
5985size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5986{
5987 int session = chain->sessionId();
5988
Steve Block3856b092011-10-20 11:56:00 +01005989 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990
5991 for (size_t i = 0; i < mEffectChains.size(); i++) {
5992 if (chain == mEffectChains[i]) {
5993 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005994 // detach all active tracks from the chain
5995 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5996 sp<Track> track = mActiveTracks[i].promote();
5997 if (track == 0) continue;
5998 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005999 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006000 chain.get(), session);
6001 chain->decActiveTrackCnt();
6002 }
6003 }
6004
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 // detach all tracks with same session ID from this chain
6006 for (size_t i = 0; i < mTracks.size(); ++i) {
6007 sp<Track> track = mTracks[i];
6008 if (session == track->sessionId()) {
6009 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006010 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 }
6012 }
Eric Laurentde070132010-07-13 04:45:46 -07006013 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 }
6015 }
6016 return mEffectChains.size();
6017}
6018
Eric Laurentde070132010-07-13 04:45:46 -07006019status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6020 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021{
6022 Mutex::Autolock _l(mLock);
6023 return attachAuxEffect_l(track, EffectId);
6024}
6025
Eric Laurentde070132010-07-13 04:45:46 -07006026status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6027 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006028{
6029 status_t status = NO_ERROR;
6030
6031 if (EffectId == 0) {
6032 track->setAuxBuffer(0, NULL);
6033 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006034 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6035 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006036 if (effect != 0) {
6037 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6038 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6039 } else {
6040 status = INVALID_OPERATION;
6041 }
6042 } else {
6043 status = BAD_VALUE;
6044 }
6045 }
6046 return status;
6047}
6048
6049void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6050{
6051 for (size_t i = 0; i < mTracks.size(); ++i) {
6052 sp<Track> track = mTracks[i];
6053 if (track->auxEffectId() == effectId) {
6054 attachAuxEffect_l(track, 0);
6055 }
6056 }
6057}
6058
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006059status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6060{
6061 // only one chain per input thread
6062 if (mEffectChains.size() != 0) {
6063 return INVALID_OPERATION;
6064 }
Steve Block3856b092011-10-20 11:56:00 +01006065 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006066
6067 chain->setInBuffer(NULL);
6068 chain->setOutBuffer(NULL);
6069
Eric Laurent59255e42011-07-27 19:49:51 -07006070 checkSuspendOnAddEffectChain_l(chain);
6071
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006072 mEffectChains.add(chain);
6073
6074 return NO_ERROR;
6075}
6076
6077size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6078{
Steve Block3856b092011-10-20 11:56:00 +01006079 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006080 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006081 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6082 chain.get(), mEffectChains.size(), this);
6083 if (mEffectChains.size() == 1) {
6084 mEffectChains.removeAt(0);
6085 }
6086 return 0;
6087}
6088
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089// ----------------------------------------------------------------------------
6090// EffectModule implementation
6091// ----------------------------------------------------------------------------
6092
6093#undef LOG_TAG
6094#define LOG_TAG "AudioFlinger::EffectModule"
6095
6096AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6097 const wp<AudioFlinger::EffectChain>& chain,
6098 effect_descriptor_t *desc,
6099 int id,
6100 int sessionId)
6101 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006102 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103{
Steve Block3856b092011-10-20 11:56:00 +01006104 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006105 int lStatus;
6106 sp<ThreadBase> thread = mThread.promote();
6107 if (thread == 0) {
6108 return;
6109 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006110
6111 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6112
6113 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006114 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115
6116 if (mStatus != NO_ERROR) {
6117 return;
6118 }
6119 lStatus = init();
6120 if (lStatus < 0) {
6121 mStatus = lStatus;
6122 goto Error;
6123 }
6124
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006125 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6126 mPinned = true;
6127 }
Steve Block3856b092011-10-20 11:56:00 +01006128 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 return;
6130Error:
6131 EffectRelease(mEffectInterface);
6132 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006133 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134}
6135
6136AudioFlinger::EffectModule::~EffectModule()
6137{
Steve Block3856b092011-10-20 11:56:00 +01006138 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006140 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6141 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6142 sp<ThreadBase> thread = mThread.promote();
6143 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006144 audio_stream_t *stream = thread->stream();
6145 if (stream != NULL) {
6146 stream->remove_audio_effect(stream, mEffectInterface);
6147 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006148 }
6149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 // release effect engine
6151 EffectRelease(mEffectInterface);
6152 }
6153}
6154
6155status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6156{
6157 status_t status;
6158
6159 Mutex::Autolock _l(mLock);
6160 // First handle in mHandles has highest priority and controls the effect module
6161 int priority = handle->priority();
6162 size_t size = mHandles.size();
6163 sp<EffectHandle> h;
6164 size_t i;
6165 for (i = 0; i < size; i++) {
6166 h = mHandles[i].promote();
6167 if (h == 0) continue;
6168 if (h->priority() <= priority) break;
6169 }
6170 // if inserted in first place, move effect control from previous owner to this handle
6171 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006172 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006174 enabled = h->enabled();
6175 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 }
Eric Laurent59255e42011-07-27 19:49:51 -07006177 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 status = NO_ERROR;
6179 } else {
6180 status = ALREADY_EXISTS;
6181 }
Steve Block3856b092011-10-20 11:56:00 +01006182 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 mHandles.insertAt(handle, i);
6184 return status;
6185}
6186
6187size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6188{
6189 Mutex::Autolock _l(mLock);
6190 size_t size = mHandles.size();
6191 size_t i;
6192 for (i = 0; i < size; i++) {
6193 if (mHandles[i] == handle) break;
6194 }
6195 if (i == size) {
6196 return size;
6197 }
Steve Block3856b092011-10-20 11:56:00 +01006198 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006199
6200 bool enabled = false;
6201 EffectHandle *hdl = handle.unsafe_get();
6202 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006203 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006204 enabled = hdl->enabled();
6205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 mHandles.removeAt(i);
6207 size = mHandles.size();
6208 // if removed from first place, move effect control from this handle to next in line
6209 if (i == 0 && size != 0) {
6210 sp<EffectHandle> h = mHandles[0].promote();
6211 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006212 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 }
6214 }
6215
Eric Laurentec437d82011-07-26 20:54:46 -07006216 // Prevent calls to process() and other functions on effect interface from now on.
6217 // The effect engine will be released by the destructor when the last strong reference on
6218 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006219 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006220 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006221 }
6222
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 return size;
6224}
6225
Eric Laurent59255e42011-07-27 19:49:51 -07006226sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6227{
6228 Mutex::Autolock _l(mLock);
6229 sp<EffectHandle> handle;
6230 if (mHandles.size() != 0) {
6231 handle = mHandles[0].promote();
6232 }
6233 return handle;
6234}
6235
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006236void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237{
Steve Block3856b092011-10-20 11:56:00 +01006238 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 // keep a strong reference on this EffectModule to avoid calling the
6240 // destructor before we exit
6241 sp<EffectModule> keep(this);
6242 {
6243 sp<ThreadBase> thread = mThread.promote();
6244 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006245 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 }
6247 }
6248}
6249
6250void AudioFlinger::EffectModule::updateState() {
6251 Mutex::Autolock _l(mLock);
6252
6253 switch (mState) {
6254 case RESTART:
6255 reset_l();
6256 // FALL THROUGH
6257
6258 case STARTING:
6259 // clear auxiliary effect input buffer for next accumulation
6260 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6261 memset(mConfig.inputCfg.buffer.raw,
6262 0,
6263 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6264 }
6265 start_l();
6266 mState = ACTIVE;
6267 break;
6268 case STOPPING:
6269 stop_l();
6270 mDisableWaitCnt = mMaxDisableWaitCnt;
6271 mState = STOPPED;
6272 break;
6273 case STOPPED:
6274 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6275 // turn off sequence.
6276 if (--mDisableWaitCnt == 0) {
6277 reset_l();
6278 mState = IDLE;
6279 }
6280 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006281 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 break;
6283 }
6284}
6285
6286void AudioFlinger::EffectModule::process()
6287{
6288 Mutex::Autolock _l(mLock);
6289
Eric Laurentec437d82011-07-26 20:54:46 -07006290 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 mConfig.inputCfg.buffer.raw == NULL ||
6292 mConfig.outputCfg.buffer.raw == NULL) {
6293 return;
6294 }
6295
Eric Laurent8f45bd72010-08-31 13:50:07 -07006296 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6298 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006299 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006301 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006302 }
6303
6304 // do the actual processing in the effect engine
6305 int ret = (*mEffectInterface)->process(mEffectInterface,
6306 &mConfig.inputCfg.buffer,
6307 &mConfig.outputCfg.buffer);
6308
6309 // force transition to IDLE state when engine is ready
6310 if (mState == STOPPED && ret == -ENODATA) {
6311 mDisableWaitCnt = 1;
6312 }
6313
6314 // clear auxiliary effect input buffer for next accumulation
6315 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006316 memset(mConfig.inputCfg.buffer.raw, 0,
6317 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 }
6319 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006320 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6321 // If an insert effect is idle and input buffer is different from output buffer,
6322 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006324 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006325 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6326 int16_t *in = mConfig.inputCfg.buffer.s16;
6327 int16_t *out = mConfig.outputCfg.buffer.s16;
6328 for (size_t i = 0; i < frameCnt; i++) {
6329 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 }
6332 }
6333}
6334
6335void AudioFlinger::EffectModule::reset_l()
6336{
6337 if (mEffectInterface == NULL) {
6338 return;
6339 }
6340 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6341}
6342
6343status_t AudioFlinger::EffectModule::configure()
6344{
6345 uint32_t channels;
6346 if (mEffectInterface == NULL) {
6347 return NO_INIT;
6348 }
6349
6350 sp<ThreadBase> thread = mThread.promote();
6351 if (thread == 0) {
6352 return DEAD_OBJECT;
6353 }
6354
6355 // TODO: handle configuration of effects replacing track process
6356 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006357 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006359 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 }
6361
6362 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006363 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 } else {
6365 mConfig.inputCfg.channels = channels;
6366 }
6367 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006368 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6369 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 mConfig.inputCfg.samplingRate = thread->sampleRate();
6371 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6372 mConfig.inputCfg.bufferProvider.cookie = NULL;
6373 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6374 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6375 mConfig.outputCfg.bufferProvider.cookie = NULL;
6376 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6377 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6378 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6379 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006380 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006381 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 // - in other sessions:
6383 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6384 // other effect: overwrites output buffer: input buffer == output buffer
6385 // Auxiliary effect:
6386 // accumulates in output buffer: input buffer != output buffer
6387 // Therefore: accumulate <=> input buffer != output buffer
6388 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6389 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6390 } else {
6391 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6392 }
6393 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6394 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6395 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6396 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6397
Steve Block3856b092011-10-20 11:56:00 +01006398 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006399 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6400
Mathias Agopian65ab4712010-07-14 17:59:35 -07006401 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006402 uint32_t size = sizeof(int);
6403 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006404 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006405 sizeof(effect_config_t),
6406 &mConfig,
6407 &size,
6408 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409 if (status == 0) {
6410 status = cmdStatus;
6411 }
6412
6413 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6414 (1000 * mConfig.outputCfg.buffer.frameCount);
6415
6416 return status;
6417}
6418
6419status_t AudioFlinger::EffectModule::init()
6420{
6421 Mutex::Autolock _l(mLock);
6422 if (mEffectInterface == NULL) {
6423 return NO_INIT;
6424 }
6425 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006426 uint32_t size = sizeof(status_t);
6427 status_t status = (*mEffectInterface)->command(mEffectInterface,
6428 EFFECT_CMD_INIT,
6429 0,
6430 NULL,
6431 &size,
6432 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 if (status == 0) {
6434 status = cmdStatus;
6435 }
6436 return status;
6437}
6438
Eric Laurentec35a142011-10-05 17:42:25 -07006439status_t AudioFlinger::EffectModule::start()
6440{
6441 Mutex::Autolock _l(mLock);
6442 return start_l();
6443}
6444
Mathias Agopian65ab4712010-07-14 17:59:35 -07006445status_t AudioFlinger::EffectModule::start_l()
6446{
6447 if (mEffectInterface == NULL) {
6448 return NO_INIT;
6449 }
6450 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006451 uint32_t size = sizeof(status_t);
6452 status_t status = (*mEffectInterface)->command(mEffectInterface,
6453 EFFECT_CMD_ENABLE,
6454 0,
6455 NULL,
6456 &size,
6457 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458 if (status == 0) {
6459 status = cmdStatus;
6460 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006461 if (status == 0 &&
6462 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6463 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6464 sp<ThreadBase> thread = mThread.promote();
6465 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006466 audio_stream_t *stream = thread->stream();
6467 if (stream != NULL) {
6468 stream->add_audio_effect(stream, mEffectInterface);
6469 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006470 }
6471 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 return status;
6473}
6474
Eric Laurentec437d82011-07-26 20:54:46 -07006475status_t AudioFlinger::EffectModule::stop()
6476{
6477 Mutex::Autolock _l(mLock);
6478 return stop_l();
6479}
6480
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481status_t AudioFlinger::EffectModule::stop_l()
6482{
6483 if (mEffectInterface == NULL) {
6484 return NO_INIT;
6485 }
6486 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006487 uint32_t size = sizeof(status_t);
6488 status_t status = (*mEffectInterface)->command(mEffectInterface,
6489 EFFECT_CMD_DISABLE,
6490 0,
6491 NULL,
6492 &size,
6493 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 if (status == 0) {
6495 status = cmdStatus;
6496 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006497 if (status == 0 &&
6498 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6499 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6500 sp<ThreadBase> thread = mThread.promote();
6501 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006502 audio_stream_t *stream = thread->stream();
6503 if (stream != NULL) {
6504 stream->remove_audio_effect(stream, mEffectInterface);
6505 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006506 }
6507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 return status;
6509}
6510
Eric Laurent25f43952010-07-28 05:40:18 -07006511status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6512 uint32_t cmdSize,
6513 void *pCmdData,
6514 uint32_t *replySize,
6515 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006516{
6517 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006518// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519
Eric Laurentec437d82011-07-26 20:54:46 -07006520 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006521 return NO_INIT;
6522 }
Eric Laurent25f43952010-07-28 05:40:18 -07006523 status_t status = (*mEffectInterface)->command(mEffectInterface,
6524 cmdCode,
6525 cmdSize,
6526 pCmdData,
6527 replySize,
6528 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006530 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531 for (size_t i = 1; i < mHandles.size(); i++) {
6532 sp<EffectHandle> h = mHandles[i].promote();
6533 if (h != 0) {
6534 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6535 }
6536 }
6537 }
6538 return status;
6539}
6540
6541status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6542{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006543
Mathias Agopian65ab4712010-07-14 17:59:35 -07006544 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006545 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546
6547 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006548 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6549 if (enabled && status != NO_ERROR) {
6550 return status;
6551 }
6552
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 switch (mState) {
6554 // going from disabled to enabled
6555 case IDLE:
6556 mState = STARTING;
6557 break;
6558 case STOPPED:
6559 mState = RESTART;
6560 break;
6561 case STOPPING:
6562 mState = ACTIVE;
6563 break;
6564
6565 // going from enabled to disabled
6566 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006567 mState = STOPPED;
6568 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 case STARTING:
6570 mState = IDLE;
6571 break;
6572 case ACTIVE:
6573 mState = STOPPING;
6574 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006575 case DESTROYED:
6576 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006577 }
6578 for (size_t i = 1; i < mHandles.size(); i++) {
6579 sp<EffectHandle> h = mHandles[i].promote();
6580 if (h != 0) {
6581 h->setEnabled(enabled);
6582 }
6583 }
6584 }
6585 return NO_ERROR;
6586}
6587
6588bool AudioFlinger::EffectModule::isEnabled()
6589{
6590 switch (mState) {
6591 case RESTART:
6592 case STARTING:
6593 case ACTIVE:
6594 return true;
6595 case IDLE:
6596 case STOPPING:
6597 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006598 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 default:
6600 return false;
6601 }
6602}
6603
Eric Laurent8f45bd72010-08-31 13:50:07 -07006604bool AudioFlinger::EffectModule::isProcessEnabled()
6605{
6606 switch (mState) {
6607 case RESTART:
6608 case ACTIVE:
6609 case STOPPING:
6610 case STOPPED:
6611 return true;
6612 case IDLE:
6613 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006614 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006615 default:
6616 return false;
6617 }
6618}
6619
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6621{
6622 Mutex::Autolock _l(mLock);
6623 status_t status = NO_ERROR;
6624
6625 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6626 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006627 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006628 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6629 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006630 status_t cmdStatus;
6631 uint32_t volume[2];
6632 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006633 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 volume[0] = *left;
6635 volume[1] = *right;
6636 if (controller) {
6637 pVolume = volume;
6638 }
Eric Laurent25f43952010-07-28 05:40:18 -07006639 status = (*mEffectInterface)->command(mEffectInterface,
6640 EFFECT_CMD_SET_VOLUME,
6641 size,
6642 volume,
6643 &size,
6644 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6646 *left = volume[0];
6647 *right = volume[1];
6648 }
6649 }
6650 return status;
6651}
6652
6653status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6654{
6655 Mutex::Autolock _l(mLock);
6656 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006657 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6658 // audio pre processing modules on RecordThread can receive both output and
6659 // input device indication in the same call
6660 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6661 if (dev) {
6662 status_t cmdStatus;
6663 uint32_t size = sizeof(status_t);
6664
6665 status = (*mEffectInterface)->command(mEffectInterface,
6666 EFFECT_CMD_SET_DEVICE,
6667 sizeof(uint32_t),
6668 &dev,
6669 &size,
6670 &cmdStatus);
6671 if (status == NO_ERROR) {
6672 status = cmdStatus;
6673 }
6674 }
6675 dev = device & AUDIO_DEVICE_IN_ALL;
6676 if (dev) {
6677 status_t cmdStatus;
6678 uint32_t size = sizeof(status_t);
6679
6680 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6681 EFFECT_CMD_SET_INPUT_DEVICE,
6682 sizeof(uint32_t),
6683 &dev,
6684 &size,
6685 &cmdStatus);
6686 if (status2 == NO_ERROR) {
6687 status2 = cmdStatus;
6688 }
6689 if (status == NO_ERROR) {
6690 status = status2;
6691 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006692 }
6693 }
6694 return status;
6695}
6696
6697status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6698{
6699 Mutex::Autolock _l(mLock);
6700 status_t status = NO_ERROR;
6701 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006703 uint32_t size = sizeof(status_t);
6704 status = (*mEffectInterface)->command(mEffectInterface,
6705 EFFECT_CMD_SET_AUDIO_MODE,
6706 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006707 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006708 &size,
6709 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710 if (status == NO_ERROR) {
6711 status = cmdStatus;
6712 }
6713 }
6714 return status;
6715}
6716
Eric Laurent59255e42011-07-27 19:49:51 -07006717void AudioFlinger::EffectModule::setSuspended(bool suspended)
6718{
6719 Mutex::Autolock _l(mLock);
6720 mSuspended = suspended;
6721}
Glenn Kastena3a85482012-01-04 11:01:11 -08006722
6723bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006724{
6725 Mutex::Autolock _l(mLock);
6726 return mSuspended;
6727}
6728
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6730{
6731 const size_t SIZE = 256;
6732 char buffer[SIZE];
6733 String8 result;
6734
6735 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6736 result.append(buffer);
6737
6738 bool locked = tryLock(mLock);
6739 // failed to lock - AudioFlinger is probably deadlocked
6740 if (!locked) {
6741 result.append("\t\tCould not lock Fx mutex:\n");
6742 }
6743
6744 result.append("\t\tSession Status State Engine:\n");
6745 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6746 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6747 result.append(buffer);
6748
6749 result.append("\t\tDescriptor:\n");
6750 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6751 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6752 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6753 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6754 result.append(buffer);
6755 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6756 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6757 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6758 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6759 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006760 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 mDescriptor.apiVersion,
6762 mDescriptor.flags);
6763 result.append(buffer);
6764 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6765 mDescriptor.name);
6766 result.append(buffer);
6767 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6768 mDescriptor.implementor);
6769 result.append(buffer);
6770
6771 result.append("\t\t- Input configuration:\n");
6772 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6773 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6774 (uint32_t)mConfig.inputCfg.buffer.raw,
6775 mConfig.inputCfg.buffer.frameCount,
6776 mConfig.inputCfg.samplingRate,
6777 mConfig.inputCfg.channels,
6778 mConfig.inputCfg.format);
6779 result.append(buffer);
6780
6781 result.append("\t\t- Output configuration:\n");
6782 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6783 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6784 (uint32_t)mConfig.outputCfg.buffer.raw,
6785 mConfig.outputCfg.buffer.frameCount,
6786 mConfig.outputCfg.samplingRate,
6787 mConfig.outputCfg.channels,
6788 mConfig.outputCfg.format);
6789 result.append(buffer);
6790
6791 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6792 result.append(buffer);
6793 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6794 for (size_t i = 0; i < mHandles.size(); ++i) {
6795 sp<EffectHandle> handle = mHandles[i].promote();
6796 if (handle != 0) {
6797 handle->dump(buffer, SIZE);
6798 result.append(buffer);
6799 }
6800 }
6801
6802 result.append("\n");
6803
6804 write(fd, result.string(), result.length());
6805
6806 if (locked) {
6807 mLock.unlock();
6808 }
6809
6810 return NO_ERROR;
6811}
6812
6813// ----------------------------------------------------------------------------
6814// EffectHandle implementation
6815// ----------------------------------------------------------------------------
6816
6817#undef LOG_TAG
6818#define LOG_TAG "AudioFlinger::EffectHandle"
6819
6820AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6821 const sp<AudioFlinger::Client>& client,
6822 const sp<IEffectClient>& effectClient,
6823 int32_t priority)
6824 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006825 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006826 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827{
Steve Block3856b092011-10-20 11:56:00 +01006828 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006830 if (client == 0) {
6831 return;
6832 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6834 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6835 if (mCblkMemory != 0) {
6836 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6837
6838 if (mCblk) {
6839 new(mCblk) effect_param_cblk_t();
6840 mBuffer = (uint8_t *)mCblk + bufOffset;
6841 }
6842 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006843 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006844 return;
6845 }
6846}
6847
6848AudioFlinger::EffectHandle::~EffectHandle()
6849{
Steve Block3856b092011-10-20 11:56:00 +01006850 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006851 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006852 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853}
6854
6855status_t AudioFlinger::EffectHandle::enable()
6856{
Steve Block3856b092011-10-20 11:56:00 +01006857 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 if (!mHasControl) return INVALID_OPERATION;
6859 if (mEffect == 0) return DEAD_OBJECT;
6860
Eric Laurentdb7c0792011-08-10 10:37:50 -07006861 if (mEnabled) {
6862 return NO_ERROR;
6863 }
6864
Eric Laurent59255e42011-07-27 19:49:51 -07006865 mEnabled = true;
6866
6867 sp<ThreadBase> thread = mEffect->thread().promote();
6868 if (thread != 0) {
6869 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6870 }
6871
6872 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6873 if (mEffect->suspended()) {
6874 return NO_ERROR;
6875 }
6876
Eric Laurentdb7c0792011-08-10 10:37:50 -07006877 status_t status = mEffect->setEnabled(true);
6878 if (status != NO_ERROR) {
6879 if (thread != 0) {
6880 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6881 }
6882 mEnabled = false;
6883 }
6884 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885}
6886
6887status_t AudioFlinger::EffectHandle::disable()
6888{
Steve Block3856b092011-10-20 11:56:00 +01006889 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006890 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006891 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892
Eric Laurentdb7c0792011-08-10 10:37:50 -07006893 if (!mEnabled) {
6894 return NO_ERROR;
6895 }
Eric Laurent59255e42011-07-27 19:49:51 -07006896 mEnabled = false;
6897
6898 if (mEffect->suspended()) {
6899 return NO_ERROR;
6900 }
6901
6902 status_t status = mEffect->setEnabled(false);
6903
6904 sp<ThreadBase> thread = mEffect->thread().promote();
6905 if (thread != 0) {
6906 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6907 }
6908
6909 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910}
6911
6912void AudioFlinger::EffectHandle::disconnect()
6913{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006914 disconnect(true);
6915}
6916
6917void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6918{
Steve Block3856b092011-10-20 11:56:00 +01006919 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920 if (mEffect == 0) {
6921 return;
6922 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006923 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006924
Eric Laurenta85a74a2011-10-19 11:44:54 -07006925 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006926 sp<ThreadBase> thread = mEffect->thread().promote();
6927 if (thread != 0) {
6928 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6929 }
Eric Laurent59255e42011-07-27 19:49:51 -07006930 }
6931
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 // release sp on module => module destructor can be called now
6933 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006935 if (mCblk) {
6936 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6937 }
6938 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6940 mClient.clear();
6941 }
6942}
6943
Eric Laurent25f43952010-07-28 05:40:18 -07006944status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6945 uint32_t cmdSize,
6946 void *pCmdData,
6947 uint32_t *replySize,
6948 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949{
Steve Block3856b092011-10-20 11:56:00 +01006950// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006951// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952
6953 // only get parameter command is permitted for applications not controlling the effect
6954 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6955 return INVALID_OPERATION;
6956 }
6957 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006958 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959
6960 // handle commands that are not forwarded transparently to effect engine
6961 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6962 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6963 // no risk to block the whole media server process or mixer threads is we are stuck here
6964 Mutex::Autolock _l(mCblk->lock);
6965 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6966 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6967 mCblk->serverIndex = 0;
6968 mCblk->clientIndex = 0;
6969 return BAD_VALUE;
6970 }
6971 status_t status = NO_ERROR;
6972 while (mCblk->serverIndex < mCblk->clientIndex) {
6973 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006974 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 int *p = (int *)(mBuffer + mCblk->serverIndex);
6976 int size = *p++;
6977 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006978 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 break;
6980 }
6981 effect_param_t *param = (effect_param_t *)p;
6982 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006983 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 mCblk->serverIndex += size;
6985 continue;
6986 }
Eric Laurent25f43952010-07-28 05:40:18 -07006987 uint32_t psize = sizeof(effect_param_t) +
6988 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6989 param->vsize;
6990 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6991 psize,
6992 p,
6993 &rsize,
6994 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006995 // stop at first error encountered
6996 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006998 *(int *)pReplyData = reply;
6999 break;
7000 } else if (reply != NO_ERROR) {
7001 *(int *)pReplyData = reply;
7002 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 }
7004 mCblk->serverIndex += size;
7005 }
7006 mCblk->serverIndex = 0;
7007 mCblk->clientIndex = 0;
7008 return status;
7009 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007010 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011 return enable();
7012 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007013 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 return disable();
7015 }
7016
7017 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7018}
7019
7020sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7021 return mCblkMemory;
7022}
7023
Eric Laurent59255e42011-07-27 19:49:51 -07007024void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
Steve Block3856b092011-10-20 11:56:00 +01007026 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027
7028 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007029 mEnabled = enabled;
7030
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 if (signal && mEffectClient != 0) {
7032 mEffectClient->controlStatusChanged(hasControl);
7033 }
7034}
7035
Eric Laurent25f43952010-07-28 05:40:18 -07007036void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7037 uint32_t cmdSize,
7038 void *pCmdData,
7039 uint32_t replySize,
7040 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041{
7042 if (mEffectClient != 0) {
7043 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7044 }
7045}
7046
7047
7048
7049void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7050{
7051 if (mEffectClient != 0) {
7052 mEffectClient->enableStatusChanged(enabled);
7053 }
7054}
7055
7056status_t AudioFlinger::EffectHandle::onTransact(
7057 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7058{
7059 return BnEffect::onTransact(code, data, reply, flags);
7060}
7061
7062
7063void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7064{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007065 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066
7067 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7068 (mClient == NULL) ? getpid() : mClient->pid(),
7069 mPriority,
7070 mHasControl,
7071 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007072 mCblk ? mCblk->clientIndex : 0,
7073 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 );
7075
7076 if (locked) {
7077 mCblk->lock.unlock();
7078 }
7079}
7080
7081#undef LOG_TAG
7082#define LOG_TAG "AudioFlinger::EffectChain"
7083
7084AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7085 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007086 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007087 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7088 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089{
Dima Zavinfce7a472011-04-19 22:30:36 -07007090 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007091 sp<ThreadBase> thread = mThread.promote();
7092 if (thread == 0) {
7093 return;
7094 }
7095 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7096 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007097}
7098
7099AudioFlinger::EffectChain::~EffectChain()
7100{
7101 if (mOwnInBuffer) {
7102 delete mInBuffer;
7103 }
7104
7105}
7106
Eric Laurent59255e42011-07-27 19:49:51 -07007107// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007108sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109{
7110 sp<EffectModule> effect;
7111 size_t size = mEffects.size();
7112
7113 for (size_t i = 0; i < size; i++) {
7114 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7115 effect = mEffects[i];
7116 break;
7117 }
7118 }
7119 return effect;
7120}
7121
Eric Laurent59255e42011-07-27 19:49:51 -07007122// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007123sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124{
7125 sp<EffectModule> effect;
7126 size_t size = mEffects.size();
7127
7128 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007129 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7130 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007131 effect = mEffects[i];
7132 break;
7133 }
7134 }
7135 return effect;
7136}
7137
Eric Laurent59255e42011-07-27 19:49:51 -07007138// getEffectFromType_l() must be called with ThreadBase::mLock held
7139sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7140 const effect_uuid_t *type)
7141{
7142 sp<EffectModule> effect;
7143 size_t size = mEffects.size();
7144
7145 for (size_t i = 0; i < size; i++) {
7146 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7147 effect = mEffects[i];
7148 break;
7149 }
7150 }
7151 return effect;
7152}
7153
Mathias Agopian65ab4712010-07-14 17:59:35 -07007154// Must be called with EffectChain::mLock locked
7155void AudioFlinger::EffectChain::process_l()
7156{
Eric Laurentdac69112010-09-28 14:09:57 -07007157 sp<ThreadBase> thread = mThread.promote();
7158 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007159 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007160 return;
7161 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007162 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7163 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007164 // always process effects unless no more tracks are on the session and the effect tail
7165 // has been rendered
7166 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007167 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007168 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007169
Eric Laurent544fe9b2011-11-11 15:42:52 -08007170 if (!tracksOnSession && mTailBufferCount == 0) {
7171 doProcess = false;
7172 }
7173
7174 if (activeTrackCnt() == 0) {
7175 // if no track is active and the effect tail has not been rendered,
7176 // the input buffer must be cleared here as the mixer process will not do it
7177 if (tracksOnSession || mTailBufferCount > 0) {
7178 size_t numSamples = thread->frameCount() * thread->channelCount();
7179 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7180 if (mTailBufferCount > 0) {
7181 mTailBufferCount--;
7182 }
7183 }
7184 }
Eric Laurentdac69112010-09-28 14:09:57 -07007185 }
7186
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007188 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007189 for (size_t i = 0; i < size; i++) {
7190 mEffects[i]->process();
7191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192 }
7193 for (size_t i = 0; i < size; i++) {
7194 mEffects[i]->updateState();
7195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196}
7197
Eric Laurentcab11242010-07-15 12:50:15 -07007198// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007199status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200{
7201 effect_descriptor_t desc = effect->desc();
7202 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7203
7204 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007205 effect->setChain(this);
7206 sp<ThreadBase> thread = mThread.promote();
7207 if (thread == 0) {
7208 return NO_INIT;
7209 }
7210 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007211
7212 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7213 // Auxiliary effects are inserted at the beginning of mEffects vector as
7214 // they are processed first and accumulated in chain input buffer
7215 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007216
Mathias Agopian65ab4712010-07-14 17:59:35 -07007217 // the input buffer for auxiliary effect contains mono samples in
7218 // 32 bit format. This is to avoid saturation in AudoMixer
7219 // accumulation stage. Saturation is done in EffectModule::process() before
7220 // calling the process in effect engine
7221 size_t numSamples = thread->frameCount();
7222 int32_t *buffer = new int32_t[numSamples];
7223 memset(buffer, 0, numSamples * sizeof(int32_t));
7224 effect->setInBuffer((int16_t *)buffer);
7225 // auxiliary effects output samples to chain input buffer for further processing
7226 // by insert effects
7227 effect->setOutBuffer(mInBuffer);
7228 } else {
7229 // Insert effects are inserted at the end of mEffects vector as they are processed
7230 // after track and auxiliary effects.
7231 // Insert effect order as a function of indicated preference:
7232 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7233 // another effect is present
7234 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7235 // last effect claiming first position
7236 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7237 // first effect claiming last position
7238 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7239 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7240 // already present
7241
7242 int size = (int)mEffects.size();
7243 int idx_insert = size;
7244 int idx_insert_first = -1;
7245 int idx_insert_last = -1;
7246
7247 for (int i = 0; i < size; i++) {
7248 effect_descriptor_t d = mEffects[i]->desc();
7249 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7250 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7251 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7252 // check invalid effect chaining combinations
7253 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7254 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007255 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256 return INVALID_OPERATION;
7257 }
7258 // remember position of first insert effect and by default
7259 // select this as insert position for new effect
7260 if (idx_insert == size) {
7261 idx_insert = i;
7262 }
7263 // remember position of last insert effect claiming
7264 // first position
7265 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7266 idx_insert_first = i;
7267 }
7268 // remember position of first insert effect claiming
7269 // last position
7270 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7271 idx_insert_last == -1) {
7272 idx_insert_last = i;
7273 }
7274 }
7275 }
7276
7277 // modify idx_insert from first position if needed
7278 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7279 if (idx_insert_last != -1) {
7280 idx_insert = idx_insert_last;
7281 } else {
7282 idx_insert = size;
7283 }
7284 } else {
7285 if (idx_insert_first != -1) {
7286 idx_insert = idx_insert_first + 1;
7287 }
7288 }
7289
7290 // always read samples from chain input buffer
7291 effect->setInBuffer(mInBuffer);
7292
7293 // if last effect in the chain, output samples to chain
7294 // output buffer, otherwise to chain input buffer
7295 if (idx_insert == size) {
7296 if (idx_insert != 0) {
7297 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7298 mEffects[idx_insert-1]->configure();
7299 }
7300 effect->setOutBuffer(mOutBuffer);
7301 } else {
7302 effect->setOutBuffer(mInBuffer);
7303 }
7304 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305
Steve Block3856b092011-10-20 11:56:00 +01007306 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 }
7308 effect->configure();
7309 return NO_ERROR;
7310}
7311
Eric Laurentcab11242010-07-15 12:50:15 -07007312// removeEffect_l() must be called with PlaybackThread::mLock held
7313size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314{
7315 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316 int size = (int)mEffects.size();
7317 int i;
7318 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7319
7320 for (i = 0; i < size; i++) {
7321 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007322 // calling stop here will remove pre-processing effect from the audio HAL.
7323 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7324 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007325 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7326 mEffects[i]->state() == EffectModule::STOPPING) {
7327 mEffects[i]->stop();
7328 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7330 delete[] effect->inBuffer();
7331 } else {
7332 if (i == size - 1 && i != 0) {
7333 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7334 mEffects[i - 1]->configure();
7335 }
7336 }
7337 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007338 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 break;
7340 }
7341 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342
7343 return mEffects.size();
7344}
7345
Eric Laurentcab11242010-07-15 12:50:15 -07007346// setDevice_l() must be called with PlaybackThread::mLock held
7347void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348{
7349 size_t size = mEffects.size();
7350 for (size_t i = 0; i < size; i++) {
7351 mEffects[i]->setDevice(device);
7352 }
7353}
7354
Eric Laurentcab11242010-07-15 12:50:15 -07007355// setMode_l() must be called with PlaybackThread::mLock held
7356void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357{
7358 size_t size = mEffects.size();
7359 for (size_t i = 0; i < size; i++) {
7360 mEffects[i]->setMode(mode);
7361 }
7362}
7363
Eric Laurentcab11242010-07-15 12:50:15 -07007364// setVolume_l() must be called with PlaybackThread::mLock held
7365bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366{
7367 uint32_t newLeft = *left;
7368 uint32_t newRight = *right;
7369 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007370 int ctrlIdx = -1;
7371 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372
Eric Laurentcab11242010-07-15 12:50:15 -07007373 // first update volume controller
7374 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007375 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007376 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7377 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007378 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007379 break;
7380 }
7381 }
7382
7383 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007384 if (hasControl) {
7385 *left = mNewLeftVolume;
7386 *right = mNewRightVolume;
7387 }
7388 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007389 }
7390
7391 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007392 mLeftVolume = newLeft;
7393 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007394
7395 // second get volume update from volume controller
7396 if (ctrlIdx >= 0) {
7397 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007398 mNewLeftVolume = newLeft;
7399 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 }
7401 // then indicate volume to all other effects in chain.
7402 // Pass altered volume to effects before volume controller
7403 // and requested volume to effects after controller
7404 uint32_t lVol = newLeft;
7405 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007406
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007408 if ((int)i == ctrlIdx) continue;
7409 // this also works for ctrlIdx == -1 when there is no volume controller
7410 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 lVol = *left;
7412 rVol = *right;
7413 }
7414 mEffects[i]->setVolume(&lVol, &rVol, false);
7415 }
7416 *left = newLeft;
7417 *right = newRight;
7418
7419 return hasControl;
7420}
7421
Mathias Agopian65ab4712010-07-14 17:59:35 -07007422status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7423{
7424 const size_t SIZE = 256;
7425 char buffer[SIZE];
7426 String8 result;
7427
7428 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7429 result.append(buffer);
7430
7431 bool locked = tryLock(mLock);
7432 // failed to lock - AudioFlinger is probably deadlocked
7433 if (!locked) {
7434 result.append("\tCould not lock mutex:\n");
7435 }
7436
Eric Laurentcab11242010-07-15 12:50:15 -07007437 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7438 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439 mEffects.size(),
7440 (uint32_t)mInBuffer,
7441 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007442 mActiveTrackCnt);
7443 result.append(buffer);
7444 write(fd, result.string(), result.size());
7445
7446 for (size_t i = 0; i < mEffects.size(); ++i) {
7447 sp<EffectModule> effect = mEffects[i];
7448 if (effect != 0) {
7449 effect->dump(fd, args);
7450 }
7451 }
7452
7453 if (locked) {
7454 mLock.unlock();
7455 }
7456
7457 return NO_ERROR;
7458}
7459
Eric Laurent59255e42011-07-27 19:49:51 -07007460// must be called with ThreadBase::mLock held
7461void AudioFlinger::EffectChain::setEffectSuspended_l(
7462 const effect_uuid_t *type, bool suspend)
7463{
7464 sp<SuspendedEffectDesc> desc;
7465 // use effect type UUID timelow as key as there is no real risk of identical
7466 // timeLow fields among effect type UUIDs.
7467 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7468 if (suspend) {
7469 if (index >= 0) {
7470 desc = mSuspendedEffects.valueAt(index);
7471 } else {
7472 desc = new SuspendedEffectDesc();
7473 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7474 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007475 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007476 }
7477 if (desc->mRefCount++ == 0) {
7478 sp<EffectModule> effect = getEffectIfEnabled(type);
7479 if (effect != 0) {
7480 desc->mEffect = effect;
7481 effect->setSuspended(true);
7482 effect->setEnabled(false);
7483 }
7484 }
7485 } else {
7486 if (index < 0) {
7487 return;
7488 }
7489 desc = mSuspendedEffects.valueAt(index);
7490 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007491 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007492 desc->mRefCount = 1;
7493 }
7494 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007495 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007496 if (desc->mEffect != 0) {
7497 sp<EffectModule> effect = desc->mEffect.promote();
7498 if (effect != 0) {
7499 effect->setSuspended(false);
7500 sp<EffectHandle> handle = effect->controlHandle();
7501 if (handle != 0) {
7502 effect->setEnabled(handle->enabled());
7503 }
7504 }
7505 desc->mEffect.clear();
7506 }
7507 mSuspendedEffects.removeItemsAt(index);
7508 }
7509 }
7510}
7511
7512// must be called with ThreadBase::mLock held
7513void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7514{
7515 sp<SuspendedEffectDesc> desc;
7516
7517 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7518 if (suspend) {
7519 if (index >= 0) {
7520 desc = mSuspendedEffects.valueAt(index);
7521 } else {
7522 desc = new SuspendedEffectDesc();
7523 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007524 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007525 }
7526 if (desc->mRefCount++ == 0) {
7527 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7528 for (size_t i = 0; i < effects.size(); i++) {
7529 setEffectSuspended_l(&effects[i]->desc().type, true);
7530 }
7531 }
7532 } else {
7533 if (index < 0) {
7534 return;
7535 }
7536 desc = mSuspendedEffects.valueAt(index);
7537 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007538 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007539 desc->mRefCount = 1;
7540 }
7541 if (--desc->mRefCount == 0) {
7542 Vector<const effect_uuid_t *> types;
7543 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7544 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7545 continue;
7546 }
7547 types.add(&mSuspendedEffects.valueAt(i)->mType);
7548 }
7549 for (size_t i = 0; i < types.size(); i++) {
7550 setEffectSuspended_l(types[i], false);
7551 }
Steve Block3856b092011-10-20 11:56:00 +01007552 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007553 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7554 }
7555 }
7556}
7557
Eric Laurent6bffdb82011-09-23 08:40:41 -07007558
7559// The volume effect is used for automated tests only
7560#ifndef OPENSL_ES_H_
7561static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7562 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7563const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7564#endif //OPENSL_ES_H_
7565
Eric Laurentdb7c0792011-08-10 10:37:50 -07007566bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7567{
7568 // auxiliary effects and visualizer are never suspended on output mix
7569 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7570 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007571 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7572 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007573 return false;
7574 }
7575 return true;
7576}
7577
Eric Laurent59255e42011-07-27 19:49:51 -07007578Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7579{
7580 Vector< sp<EffectModule> > effects;
7581 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007582 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007583 continue;
7584 }
7585 effects.add(mEffects[i]);
7586 }
7587 return effects;
7588}
7589
7590sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7591 const effect_uuid_t *type)
7592{
7593 sp<EffectModule> effect;
7594 effect = getEffectFromType_l(type);
7595 if (effect != 0 && !effect->isEnabled()) {
7596 effect.clear();
7597 }
7598 return effect;
7599}
7600
7601void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7602 bool enabled)
7603{
7604 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7605 if (enabled) {
7606 if (index < 0) {
7607 // if the effect is not suspend check if all effects are suspended
7608 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7609 if (index < 0) {
7610 return;
7611 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007612 if (!isEffectEligibleForSuspend(effect->desc())) {
7613 return;
7614 }
Eric Laurent59255e42011-07-27 19:49:51 -07007615 setEffectSuspended_l(&effect->desc().type, enabled);
7616 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007617 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007618 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007619 return;
7620 }
Eric Laurent59255e42011-07-27 19:49:51 -07007621 }
Steve Block3856b092011-10-20 11:56:00 +01007622 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007623 effect->desc().type.timeLow);
7624 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7625 // if effect is requested to suspended but was not yet enabled, supend it now.
7626 if (desc->mEffect == 0) {
7627 desc->mEffect = effect;
7628 effect->setEnabled(false);
7629 effect->setSuspended(true);
7630 }
7631 } else {
7632 if (index < 0) {
7633 return;
7634 }
Steve Block3856b092011-10-20 11:56:00 +01007635 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007636 effect->desc().type.timeLow);
7637 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7638 desc->mEffect.clear();
7639 effect->setSuspended(false);
7640 }
7641}
7642
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643#undef LOG_TAG
7644#define LOG_TAG "AudioFlinger"
7645
7646// ----------------------------------------------------------------------------
7647
7648status_t AudioFlinger::onTransact(
7649 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7650{
7651 return BnAudioFlinger::onTransact(code, data, reply, flags);
7652}
7653
Mathias Agopian65ab4712010-07-14 17:59:35 -07007654}; // namespace android