blob: 7f43100673e79165e7ae66fed30c97e8d834444a [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,
383 int streamType,
384 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{
649 return mMasterVolume;
650}
651
652bool AudioFlinger::masterMute() const
653{
654 return mMasterMute;
655}
656
657status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Dima Zavinfce7a472011-04-19 22:30:36 -0700664 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000665 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 return BAD_VALUE;
667 }
668
669 AutoMutex lock(mLock);
670 PlaybackThread *thread = NULL;
671 if (output) {
672 thread = checkPlaybackThread_l(output);
673 if (thread == NULL) {
674 return BAD_VALUE;
675 }
676 }
677
678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
683 }
684 } else {
685 thread->setStreamVolume(stream, value);
686 }
687
688 return NO_ERROR;
689}
690
691status_t AudioFlinger::setStreamMute(int stream, bool muted)
692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Dima Zavinfce7a472011-04-19 22:30:36 -0700698 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000700 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 return BAD_VALUE;
702 }
703
Eric Laurent93575202011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
708
709 return NO_ERROR;
710}
711
712float AudioFlinger::streamVolume(int stream, int output) const
713{
Dima Zavinfce7a472011-04-19 22:30:36 -0700714 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715 return 0.0f;
716 }
717
718 AutoMutex lock(mLock);
719 float volume;
720 if (output) {
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
723 return 0.0f;
724 }
725 volume = thread->streamVolume(stream);
726 } else {
727 volume = mStreamTypes[stream].volume;
728 }
729
730 return volume;
731}
732
733bool AudioFlinger::streamMute(int stream) const
734{
Dima Zavinfce7a472011-04-19 22:30:36 -0700735 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 return true;
737 }
738
739 return mStreamTypes[stream].mute;
740}
741
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
743{
744 status_t result;
745
Steve Block3856b092011-10-20 11:56:00 +0100746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
751 }
752
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753 // ioHandle == 0 means the parameters are global to the audio hardware interface
754 if (ioHandle == 0) {
755 AutoMutex lock(mHardwareLock);
756 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700757 status_t final_result = NO_ERROR;
758 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759 audio_hw_device_t *dev = mAudioHwDevs[i];
760 result = dev->set_parameters(dev, keyValuePairs.string());
761 final_result = result ?: final_result;
762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700764 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765 AudioParameter param = AudioParameter(keyValuePairs);
766 String8 value;
767 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700771 for (size_t i = 0; i < mRecordThreads.size(); i++) {
772 sp<RecordThread> thread = mRecordThreads.valueAt(i);
773 RecordThread::RecordTrack *track = thread->track();
774 if (track != NULL) {
775 audio_devices_t device = (audio_devices_t)(
776 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700778 thread->setEffectSuspended(FX_IID_AEC,
779 suspend,
780 track->sessionId());
781 thread->setEffectSuspended(FX_IID_NS,
782 suspend,
783 track->sessionId());
784 }
785 }
Eric Laurentbee53372011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700789 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 }
791
792 // hold a strong ref on thread in case closeOutput() or closeInput() is called
793 // and the thread is exited once the lock is released
794 sp<ThreadBase> thread;
795 {
796 Mutex::Autolock _l(mLock);
797 thread = checkPlaybackThread_l(ioHandle);
798 if (thread == NULL) {
799 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700800 } else if (thread.get() == primaryPlaybackThread_l()) {
801 // indicate output device change to all input threads for pre processing
802 AudioParameter param = AudioParameter(keyValuePairs);
803 int value;
804 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807 }
808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810 }
811 if (thread != NULL) {
812 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 return result;
814 }
815 return BAD_VALUE;
816}
817
818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
819{
Steve Block3856b092011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin799a70e2011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700832 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 }
834
835 Mutex::Autolock _l(mLock);
836
837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
846}
847
848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
849{
Eric Laurenta1884f92011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856}
857
858unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurenta1884f92011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
909
910 Mutex::Autolock _l(mLock);
911
912 int pid = IPCThreadState::self()->getCallingPid();
913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block3856b092011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918
919 mNotificationClients.add(pid, notificationClient);
920
921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
923
924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
929
930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
932 }
933 }
934}
935
936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700946
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965}
966
967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
972 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
973 }
974}
975
976// removeClient_l() must be called with AudioFlinger::mLock held
977void AudioFlinger::removeClient_l(pid_t pid)
978{
Steve Block3856b092011-10-20 11:56:00 +0100979 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mClients.removeItem(pid);
981}
982
983
984// ----------------------------------------------------------------------------
985
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700986AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 : Thread(false),
988 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700989 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
990 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700992 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993}
994
995AudioFlinger::ThreadBase::~ThreadBase()
996{
997 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700998 // do not lock the mutex in destructor
999 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001000 if (mPowerManager != 0) {
1001 sp<IBinder> binder = mPowerManager->asBinder();
1002 binder->unlinkToDeath(mDeathRecipient);
1003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004}
1005
1006void AudioFlinger::ThreadBase::exit()
1007{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001008 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 // destroyed in the middle of requestExitAndWait()
1010 sp <ThreadBase> strongMe = this;
1011
Steve Block3856b092011-10-20 11:56:00 +01001012 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001014 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001015 mExiting = true;
1016 requestExit();
1017 mWaitWorkCV.signal();
1018 }
1019 requestExitAndWait();
1020}
1021
1022uint32_t AudioFlinger::ThreadBase::sampleRate() const
1023{
1024 return mSampleRate;
1025}
1026
1027int AudioFlinger::ThreadBase::channelCount() const
1028{
1029 return (int)mChannelCount;
1030}
1031
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001032uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033{
1034 return mFormat;
1035}
1036
1037size_t AudioFlinger::ThreadBase::frameCount() const
1038{
1039 return mFrameCount;
1040}
1041
1042status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1043{
1044 status_t status;
1045
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 Mutex::Autolock _l(mLock);
1048
1049 mNewParameters.add(keyValuePairs);
1050 mWaitWorkCV.signal();
1051 // wait condition with timeout in case the thread loop has exited
1052 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001053 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 status = mParamStatus;
1055 mWaitWorkCV.signal();
1056 } else {
1057 status = TIMED_OUT;
1058 }
1059 return status;
1060}
1061
1062void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1063{
1064 Mutex::Autolock _l(mLock);
1065 sendConfigEvent_l(event, param);
1066}
1067
1068// sendConfigEvent_l() must be called with ThreadBase::mLock held
1069void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1070{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001071 ConfigEvent configEvent;
1072 configEvent.mEvent = event;
1073 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mWaitWorkCV.signal();
1077}
1078
1079void AudioFlinger::ThreadBase::processConfigEvents()
1080{
1081 mLock.lock();
1082 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001084 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 mConfigEvents.removeAt(0);
1086 // release mLock before locking AudioFlinger mLock: lock order is always
1087 // AudioFlinger then ThreadBase to avoid cross deadlock
1088 mLock.unlock();
1089 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001090 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 mLock.lock();
1093 }
1094 mLock.unlock();
1095}
1096
1097status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1098{
1099 const size_t SIZE = 256;
1100 char buffer[SIZE];
1101 String8 result;
1102
1103 bool locked = tryLock(mLock);
1104 if (!locked) {
1105 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1106 write(fd, buffer, strlen(buffer));
1107 }
1108
1109 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1116 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001117 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1118 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1122 result.append(buffer);
1123
1124 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1125 result.append(buffer);
1126 result.append(" Index Command");
1127 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1128 snprintf(buffer, SIZE, "\n %02d ", i);
1129 result.append(buffer);
1130 result.append(mNewParameters[i]);
1131 }
1132
1133 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1134 result.append(buffer);
1135 snprintf(buffer, SIZE, " Index event param\n");
1136 result.append(buffer);
1137 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001138 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 result.append(buffer);
1140 }
1141 result.append("\n");
1142
1143 write(fd, result.string(), result.size());
1144
1145 if (locked) {
1146 mLock.unlock();
1147 }
1148 return NO_ERROR;
1149}
1150
Eric Laurent1d2bff02011-07-24 17:49:51 -07001151status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1152{
1153 const size_t SIZE = 256;
1154 char buffer[SIZE];
1155 String8 result;
1156
1157 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1158 write(fd, buffer, strlen(buffer));
1159
1160 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1161 sp<EffectChain> chain = mEffectChains[i];
1162 if (chain != 0) {
1163 chain->dump(fd, args);
1164 }
1165 }
1166 return NO_ERROR;
1167}
1168
Eric Laurentfeb0db62011-07-22 09:04:31 -07001169void AudioFlinger::ThreadBase::acquireWakeLock()
1170{
1171 Mutex::Autolock _l(mLock);
1172 acquireWakeLock_l();
1173}
1174
1175void AudioFlinger::ThreadBase::acquireWakeLock_l()
1176{
1177 if (mPowerManager == 0) {
1178 // use checkService() to avoid blocking if power service is not up yet
1179 sp<IBinder> binder =
1180 defaultServiceManager()->checkService(String16("power"));
1181 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001182 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001183 } else {
1184 mPowerManager = interface_cast<IPowerManager>(binder);
1185 binder->linkToDeath(mDeathRecipient);
1186 }
1187 }
1188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
1190 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1191 binder,
1192 String16(mName));
1193 if (status == NO_ERROR) {
1194 mWakeLockToken = binder;
1195 }
Steve Block3856b092011-10-20 11:56:00 +01001196 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001197 }
1198}
1199
1200void AudioFlinger::ThreadBase::releaseWakeLock()
1201{
1202 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001203 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001204}
1205
1206void AudioFlinger::ThreadBase::releaseWakeLock_l()
1207{
1208 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001209 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001210 if (mPowerManager != 0) {
1211 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1212 }
1213 mWakeLockToken.clear();
1214 }
1215}
1216
1217void AudioFlinger::ThreadBase::clearPowerManager()
1218{
1219 Mutex::Autolock _l(mLock);
1220 releaseWakeLock_l();
1221 mPowerManager.clear();
1222}
1223
1224void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1225{
1226 sp<ThreadBase> thread = mThread.promote();
1227 if (thread != 0) {
1228 thread->clearPowerManager();
1229 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001230 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001231}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001232
Eric Laurent59255e42011-07-27 19:49:51 -07001233void AudioFlinger::ThreadBase::setEffectSuspended(
1234 const effect_uuid_t *type, bool suspend, int sessionId)
1235{
1236 Mutex::Autolock _l(mLock);
1237 setEffectSuspended_l(type, suspend, sessionId);
1238}
1239
1240void AudioFlinger::ThreadBase::setEffectSuspended_l(
1241 const effect_uuid_t *type, bool suspend, int sessionId)
1242{
1243 sp<EffectChain> chain;
1244 chain = getEffectChain_l(sessionId);
1245 if (chain != 0) {
1246 if (type != NULL) {
1247 chain->setEffectSuspended_l(type, suspend);
1248 } else {
1249 chain->setEffectSuspendedAll_l(suspend);
1250 }
1251 }
1252
1253 updateSuspendedSessions_l(type, suspend, sessionId);
1254}
1255
1256void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1257{
1258 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1259 if (index < 0) {
1260 return;
1261 }
1262
1263 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1264 mSuspendedSessions.editValueAt(index);
1265
1266 for (size_t i = 0; i < sessionEffects.size(); i++) {
1267 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1268 for (int j = 0; j < desc->mRefCount; j++) {
1269 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1270 chain->setEffectSuspendedAll_l(true);
1271 } else {
Steve Block3856b092011-10-20 11:56:00 +01001272 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001273 desc->mType.timeLow);
1274 chain->setEffectSuspended_l(&desc->mType, true);
1275 }
1276 }
1277 }
1278}
1279
Eric Laurent59255e42011-07-27 19:49:51 -07001280void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1281 bool suspend,
1282 int sessionId)
1283{
1284 int index = mSuspendedSessions.indexOfKey(sessionId);
1285
1286 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1287
1288 if (suspend) {
1289 if (index >= 0) {
1290 sessionEffects = mSuspendedSessions.editValueAt(index);
1291 } else {
1292 mSuspendedSessions.add(sessionId, sessionEffects);
1293 }
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 sessionEffects = mSuspendedSessions.editValueAt(index);
1299 }
1300
1301
1302 int key = EffectChain::kKeyForSuspendAll;
1303 if (type != NULL) {
1304 key = type->timeLow;
1305 }
1306 index = sessionEffects.indexOfKey(key);
1307
1308 sp <SuspendedSessionDesc> desc;
1309 if (suspend) {
1310 if (index >= 0) {
1311 desc = sessionEffects.valueAt(index);
1312 } else {
1313 desc = new SuspendedSessionDesc();
1314 if (type != NULL) {
1315 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1316 }
1317 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001319 }
1320 desc->mRefCount++;
1321 } else {
1322 if (index < 0) {
1323 return;
1324 }
1325 desc = sessionEffects.valueAt(index);
1326 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001328 sessionEffects.removeItemsAt(index);
1329 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001330 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001331 sessionId);
1332 mSuspendedSessions.removeItem(sessionId);
1333 }
1334 }
1335 }
1336 if (!sessionEffects.isEmpty()) {
1337 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1338 }
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1342 bool enabled,
1343 int sessionId)
1344{
1345 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001346 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1347}
Eric Laurent59255e42011-07-27 19:49:51 -07001348
Eric Laurenta85a74a2011-10-19 11:44:54 -07001349void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1350 bool enabled,
1351 int sessionId)
1352{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001353 if (mType != RECORD) {
1354 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1355 // another session. This gives the priority to well behaved effect control panels
1356 // and applications not using global effects.
1357 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1358 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1359 }
1360 }
Eric Laurent59255e42011-07-27 19:49:51 -07001361
1362 sp<EffectChain> chain = getEffectChain_l(sessionId);
1363 if (chain != 0) {
1364 chain->checkSuspendOnEffectEnabled(effect, enabled);
1365 }
1366}
1367
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368// ----------------------------------------------------------------------------
1369
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001370AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1371 AudioStreamOut* output,
1372 int id,
1373 uint32_t device)
1374 : ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001375 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 readOutputParameters();
1381
1382 mMasterVolume = mAudioFlinger->masterVolume();
1383 mMasterMute = mAudioFlinger->masterMute();
1384
Dima Zavinfce7a472011-04-19 22:30:36 -07001385 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001388 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389 }
1390}
1391
1392AudioFlinger::PlaybackThread::~PlaybackThread()
1393{
1394 delete [] mMixBuffer;
1395}
1396
1397status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1398{
1399 dumpInternals(fd, args);
1400 dumpTracks(fd, args);
1401 dumpEffectChains(fd, args);
1402 return NO_ERROR;
1403}
1404
1405status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1406{
1407 const size_t SIZE = 256;
1408 char buffer[SIZE];
1409 String8 result;
1410
1411 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1412 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001413 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 -07001414 for (size_t i = 0; i < mTracks.size(); ++i) {
1415 sp<Track> track = mTracks[i];
1416 if (track != 0) {
1417 track->dump(buffer, SIZE);
1418 result.append(buffer);
1419 }
1420 }
1421
1422 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1423 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001424 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 -07001425 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1426 wp<Track> wTrack = mActiveTracks[i];
1427 if (wTrack != 0) {
1428 sp<Track> track = wTrack.promote();
1429 if (track != 0) {
1430 track->dump(buffer, SIZE);
1431 result.append(buffer);
1432 }
1433 }
1434 }
1435 write(fd, result.string(), result.size());
1436 return NO_ERROR;
1437}
1438
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1440{
1441 const size_t SIZE = 256;
1442 char buffer[SIZE];
1443 String8 result;
1444
1445 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1456 result.append(buffer);
1457 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1458 result.append(buffer);
1459 write(fd, result.string(), result.size());
1460
1461 dumpBase(fd, args);
1462
1463 return NO_ERROR;
1464}
1465
1466// Thread virtuals
1467status_t AudioFlinger::PlaybackThread::readyToRun()
1468{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001469 status_t status = initCheck();
1470 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001471 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001472 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001473 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001475 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478void AudioFlinger::PlaybackThread::onFirstRef()
1479{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001480 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481}
1482
1483// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1484sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1485 const sp<AudioFlinger::Client>& client,
1486 int streamType,
1487 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001488 uint32_t format,
1489 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490 int frameCount,
1491 const sp<IMemory>& sharedBuffer,
1492 int sessionId,
1493 status_t *status)
1494{
1495 sp<Track> track;
1496 status_t lStatus;
1497
1498 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001499 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1500 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001501 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001502 "for output %p with format %d",
1503 sampleRate, format, channelMask, mOutput, mFormat);
1504 lStatus = BAD_VALUE;
1505 goto Exit;
1506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 }
1508 } else {
1509 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1510 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001511 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001512 lStatus = BAD_VALUE;
1513 goto Exit;
1514 }
1515 }
1516
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001517 lStatus = initCheck();
1518 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001519 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 goto Exit;
1521 }
1522
1523 { // scope for mLock
1524 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001525
1526 // all tracks in same audio session must share the same routing strategy otherwise
1527 // conflicts will happen when tracks are moved from one output to another by audio policy
1528 // manager
1529 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001530 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001531 for (size_t i = 0; i < mTracks.size(); ++i) {
1532 sp<Track> t = mTracks[i];
1533 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001534 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1535 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001536 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001537 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001538 lStatus = BAD_VALUE;
1539 goto Exit;
1540 }
1541 }
1542 }
1543
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001545 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546 if (track->getCblk() == NULL || track->name() < 0) {
1547 lStatus = NO_MEMORY;
1548 goto Exit;
1549 }
1550 mTracks.add(track);
1551
1552 sp<EffectChain> chain = getEffectChain_l(sessionId);
1553 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001554 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001556 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001557 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001559
1560 // invalidate track immediately if the stream type was moved to another thread since
1561 // createTrack() was called by the client process.
1562 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001563 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001564 this, streamType);
1565 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 }
1568 lStatus = NO_ERROR;
1569
1570Exit:
1571 if(status) {
1572 *status = lStatus;
1573 }
1574 return track;
1575}
1576
1577uint32_t AudioFlinger::PlaybackThread::latency() const
1578{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001579 Mutex::Autolock _l(mLock);
1580 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001581 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001582 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 return 0;
1584 }
1585}
1586
1587status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1588{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 mMasterVolume = value;
1590 return NO_ERROR;
1591}
1592
1593status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1594{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 mMasterMute = muted;
1596 return NO_ERROR;
1597}
1598
1599float AudioFlinger::PlaybackThread::masterVolume() const
1600{
1601 return mMasterVolume;
1602}
1603
1604bool AudioFlinger::PlaybackThread::masterMute() const
1605{
1606 return mMasterMute;
1607}
1608
1609status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1610{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611 mStreamTypes[stream].volume = value;
1612 return NO_ERROR;
1613}
1614
1615status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1616{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617 mStreamTypes[stream].mute = muted;
1618 return NO_ERROR;
1619}
1620
1621float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1622{
1623 return mStreamTypes[stream].volume;
1624}
1625
1626bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1627{
1628 return mStreamTypes[stream].mute;
1629}
1630
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631// addTrack_l() must be called with ThreadBase::mLock held
1632status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1633{
1634 status_t status = ALREADY_EXISTS;
1635
1636 // set retry count for buffer fill
1637 track->mRetryCount = kMaxTrackStartupRetries;
1638 if (mActiveTracks.indexOf(track) < 0) {
1639 // the track is newly added, make sure it fills up all its
1640 // buffers before playing. This is to ensure the client will
1641 // effectively get the latency it requested.
1642 track->mFillingUpStatus = Track::FS_FILLING;
1643 track->mResetDone = false;
1644 mActiveTracks.add(track);
1645 if (track->mainBuffer() != mMixBuffer) {
1646 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1647 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001648 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001649 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 }
1651 }
1652
1653 status = NO_ERROR;
1654 }
1655
Steve Block3856b092011-10-20 11:56:00 +01001656 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 mWaitWorkCV.broadcast();
1658
1659 return status;
1660}
1661
1662// destroyTrack_l() must be called with ThreadBase::mLock held
1663void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1664{
1665 track->mState = TrackBase::TERMINATED;
1666 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001667 removeTrack_l(track);
1668 }
1669}
1670
1671void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1672{
1673 mTracks.remove(track);
1674 deleteTrackName_l(track->name());
1675 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1676 if (chain != 0) {
1677 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 }
1679}
1680
1681String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1682{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001683 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001684 char *s;
1685
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001686 Mutex::Autolock _l(mLock);
1687 if (initCheck() != NO_ERROR) {
1688 return out_s8;
1689 }
1690
Dima Zavin799a70e2011-04-18 16:57:27 -07001691 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001692 out_s8 = String8(s);
1693 free(s);
1694 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001697// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1699 AudioSystem::OutputDescriptor desc;
1700 void *param2 = 0;
1701
Steve Block3856b092011-10-20 11:56:00 +01001702 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703
1704 switch (event) {
1705 case AudioSystem::OUTPUT_OPENED:
1706 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001707 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 desc.samplingRate = mSampleRate;
1709 desc.format = mFormat;
1710 desc.frameCount = mFrameCount;
1711 desc.latency = latency();
1712 param2 = &desc;
1713 break;
1714
1715 case AudioSystem::STREAM_CONFIG_CHANGED:
1716 param2 = &param;
1717 case AudioSystem::OUTPUT_CLOSED:
1718 default:
1719 break;
1720 }
1721 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1722}
1723
1724void AudioFlinger::PlaybackThread::readOutputParameters()
1725{
Dima Zavin799a70e2011-04-18 16:57:27 -07001726 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001727 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1728 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001729 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1730 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1731 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732
1733 // FIXME - Current mixer implementation only supports stereo output: Always
1734 // Allocate a stereo buffer even if HW output is mono.
1735 if (mMixBuffer != NULL) delete[] mMixBuffer;
1736 mMixBuffer = new int16_t[mFrameCount * 2];
1737 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1738
Eric Laurentde070132010-07-13 04:45:46 -07001739 // force reconfiguration of effect chains and engines to take new buffer size and audio
1740 // parameters into account
1741 // Note that mLock is not held when readOutputParameters() is called from the constructor
1742 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1743 // matter.
1744 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1745 Vector< sp<EffectChain> > effectChains = mEffectChains;
1746 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001747 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749}
1750
1751status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1752{
1753 if (halFrames == 0 || dspFrames == 0) {
1754 return BAD_VALUE;
1755 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001756 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001757 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 return INVALID_OPERATION;
1759 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001760 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761
Dima Zavin799a70e2011-04-18 16:57:27 -07001762 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763}
1764
Eric Laurent39e94f82010-07-28 01:32:47 -07001765uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766{
1767 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001768 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001770 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 }
1772
1773 for (size_t i = 0; i < mTracks.size(); ++i) {
1774 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001777 result |= TRACK_SESSION;
1778 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 }
1780 }
1781
Eric Laurent39e94f82010-07-28 01:32:47 -07001782 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783}
1784
Eric Laurentde070132010-07-13 04:45:46 -07001785uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1786{
Dima Zavinfce7a472011-04-19 22:30:36 -07001787 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001788 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001789 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1790 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001791 }
1792 for (size_t i = 0; i < mTracks.size(); i++) {
1793 sp<Track> track = mTracks[i];
1794 if (sessionId == track->sessionId() &&
1795 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001796 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001797 }
1798 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001799 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001800}
1801
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 return mOutput;
1807}
1808
1809AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1810{
1811 Mutex::Autolock _l(mLock);
1812 AudioStreamOut *output = mOutput;
1813 mOutput = NULL;
1814 return output;
1815}
1816
1817// this method must always be called either with ThreadBase mLock held or inside the thread loop
1818audio_stream_t* AudioFlinger::PlaybackThread::stream()
1819{
1820 if (mOutput == NULL) {
1821 return NULL;
1822 }
1823 return &mOutput->stream->common;
1824}
1825
Eric Laurent162b40b2011-12-05 09:47:19 -08001826uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1827{
1828 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1829 // decoding and transfer time. So sleeping for half of the latency would likely cause
1830 // underruns
1831 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1832 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1833 } else {
1834 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1835 }
1836}
1837
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838// ----------------------------------------------------------------------------
1839
Dima Zavin799a70e2011-04-18 16:57:27 -07001840AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001842 mAudioMixer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001844 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1846
1847 // FIXME - Current mixer implementation only supports stereo output
1848 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001849 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001850 }
1851}
1852
1853AudioFlinger::MixerThread::~MixerThread()
1854{
1855 delete mAudioMixer;
1856}
1857
1858bool AudioFlinger::MixerThread::threadLoop()
1859{
1860 Vector< sp<Track> > tracksToRemove;
1861 uint32_t mixerStatus = MIXER_IDLE;
1862 nsecs_t standbyTime = systemTime();
1863 size_t mixBufferSize = mFrameCount * mFrameSize;
1864 // FIXME: Relaxed timing because of a certain device that can't meet latency
1865 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001866 // increase threshold again due to low power audio mode. The way this warning threshold is
1867 // calculated and its usefulness should be reconsidered anyway.
1868 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 nsecs_t lastWarning = 0;
1870 bool longStandbyExit = false;
1871 uint32_t activeSleepTime = activeSleepTimeUs();
1872 uint32_t idleSleepTime = idleSleepTimeUs();
1873 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001874 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001876#ifdef DEBUG_CPU_USAGE
1877 ThreadCpuUsage cpu;
1878 const CentralTendencyStatistics& stats = cpu.statistics();
1879#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880
Eric Laurentfeb0db62011-07-22 09:04:31 -07001881 acquireWakeLock();
1882
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 while (!exitPending())
1884 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001885#ifdef DEBUG_CPU_USAGE
1886 cpu.sampleAndEnable();
1887 unsigned n = stats.n();
1888 // cpu.elapsed() is expensive, so don't call it every loop
1889 if ((n & 127) == 1) {
1890 long long elapsed = cpu.elapsed();
1891 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1892 double perLoop = elapsed / (double) n;
1893 double perLoop100 = perLoop * 0.01;
1894 double mean = stats.mean();
1895 double stddev = stats.stddev();
1896 double minimum = stats.minimum();
1897 double maximum = stats.maximum();
1898 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001899 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 -07001900 elapsed * .000000001, n, perLoop * .000001,
1901 mean * .001,
1902 stddev * .001,
1903 minimum * .001,
1904 maximum * .001,
1905 mean / perLoop100,
1906 stddev / perLoop100,
1907 minimum / perLoop100,
1908 maximum / perLoop100);
1909 }
1910 }
1911#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912 processConfigEvents();
1913
1914 mixerStatus = MIXER_IDLE;
1915 { // scope for mLock
1916
1917 Mutex::Autolock _l(mLock);
1918
1919 if (checkForNewParameters_l()) {
1920 mixBufferSize = mFrameCount * mFrameSize;
1921 // FIXME: Relaxed timing because of a certain device that can't meet latency
1922 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001923 // increase threshold again due to low power audio mode. The way this warning
1924 // threshold is calculated and its usefulness should be reconsidered anyway.
1925 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 activeSleepTime = activeSleepTimeUs();
1927 idleSleepTime = idleSleepTimeUs();
1928 }
1929
1930 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1931
1932 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001933 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1934 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001936 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001937 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 mStandby = true;
1939 mBytesWritten = 0;
1940 }
1941
1942 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1943 // we're about to wait, flush the binder command buffer
1944 IPCThreadState::self()->flushCommands();
1945
1946 if (exitPending()) break;
1947
Eric Laurentfeb0db62011-07-22 09:04:31 -07001948 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001950 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001952 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001953 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954
1955 if (mMasterMute == false) {
1956 char value[PROPERTY_VALUE_MAX];
1957 property_get("ro.audio.silent", value, "0");
1958 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001959 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 setMasterMute(true);
1961 }
1962 }
1963
1964 standbyTime = systemTime() + kStandbyTimeInNsecs;
1965 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001966 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 continue;
1968 }
1969 }
1970
1971 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1972
1973 // prevent any changes in effect chain list and in each effect chain
1974 // during mixing and effect process as the audio buffers could be deleted
1975 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001976 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978
Glenn Kastenf6b16782011-12-15 09:51:17 -08001979 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 // mix buffers...
1981 mAudioMixer->process();
1982 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001983 // increase sleep time progressively when application underrun condition clears
1984 if (sleepTimeShift > 0) {
1985 sleepTimeShift--;
1986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 standbyTime = systemTime() + kStandbyTimeInNsecs;
1988 //TODO: delay standby when effects have a tail
1989 } else {
1990 // If no tracks are ready, sleep once for the duration of an output
1991 // buffer size, then write 0s to the output
1992 if (sleepTime == 0) {
1993 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001994 sleepTime = activeSleepTime >> sleepTimeShift;
1995 if (sleepTime < kMinThreadSleepTimeUs) {
1996 sleepTime = kMinThreadSleepTimeUs;
1997 }
1998 // reduce sleep time in case of consecutive application underruns to avoid
1999 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2000 // duration we would end up writing less data than needed by the audio HAL if
2001 // the condition persists.
2002 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2003 sleepTimeShift++;
2004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 } else {
2006 sleepTime = idleSleepTime;
2007 }
2008 } else if (mBytesWritten != 0 ||
2009 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2010 memset (mMixBuffer, 0, mixBufferSize);
2011 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002012 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
2014 // TODO add standby time extension fct of effect tail
2015 }
2016
2017 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002018 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 }
2020 // sleepTime == 0 means we must write to audio hardware
2021 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002022 for (size_t i = 0; i < effectChains.size(); i ++) {
2023 effectChains[i]->process_l();
2024 }
2025 // enable changes in effect chain
2026 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 mLastWriteTime = systemTime();
2028 mInWrite = true;
2029 mBytesWritten += mixBufferSize;
2030
Dima Zavin799a70e2011-04-18 16:57:27 -07002031 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2033 mNumWrites++;
2034 mInWrite = false;
2035 nsecs_t now = systemTime();
2036 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002037 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002039 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002040 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041 ns2ms(delta), mNumDelayedWrites, this);
2042 lastWarning = now;
2043 }
2044 if (mStandby) {
2045 longStandbyExit = true;
2046 }
2047 }
2048 mStandby = false;
2049 } else {
2050 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002051 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 usleep(sleepTime);
2053 }
2054
2055 // finally let go of all our tracks, without the lock held
2056 // since we can't guarantee the destructors won't acquire that
2057 // same lock.
2058 tracksToRemove.clear();
2059
2060 // Effect chains will be actually deleted here if they were removed from
2061 // mEffectChains list during mixing or effects processing
2062 effectChains.clear();
2063 }
2064
2065 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002066 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 }
2068
Eric Laurentfeb0db62011-07-22 09:04:31 -07002069 releaseWakeLock();
2070
Steve Block3856b092011-10-20 11:56:00 +01002071 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 return false;
2073}
2074
2075// prepareTracks_l() must be called with ThreadBase::mLock held
2076uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2077{
2078
2079 uint32_t mixerStatus = MIXER_IDLE;
2080 // find out which tracks need to be processed
2081 size_t count = activeTracks.size();
2082 size_t mixedTracks = 0;
2083 size_t tracksWithEffect = 0;
2084
2085 float masterVolume = mMasterVolume;
2086 bool masterMute = mMasterMute;
2087
Eric Laurent571d49c2010-08-11 05:20:11 -07002088 if (masterMute) {
2089 masterVolume = 0;
2090 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002092 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002094 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002095 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 masterVolume = (float)((v + (1 << 23)) >> 24);
2097 chain.clear();
2098 }
2099
2100 for (size_t i=0 ; i<count ; i++) {
2101 sp<Track> t = activeTracks[i].promote();
2102 if (t == 0) continue;
2103
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002104 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 Track* const track = t.get();
2106 audio_track_cblk_t* cblk = track->cblk();
2107
2108 // The first time a track is added we wait
2109 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002110 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002111 // make sure that we have enough frames to mix one full buffer.
2112 // enforce this condition only once to enable draining the buffer in case the client
2113 // app does not call stop() and relies on underrun to stop:
2114 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2115 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002116 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002117 if (!track->isStopped() && !track->isPausing() &&
2118 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002119 if (t->sampleRate() == (int)mSampleRate) {
2120 minFrames = mFrameCount;
2121 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002122 // +1 for rounding and +1 for additional sample needed for interpolation
2123 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2124 // add frames already consumed but not yet released by the resampler
2125 // because cblk->framesReady() will include these frames
2126 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2127 // the minimum track buffer size is normally twice the number of frames necessary
2128 // to fill one buffer and the resampler should not leave more than one buffer worth
2129 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002130 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002131 }
2132 }
2133 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 !track->isPaused() && !track->isTerminated())
2135 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002136 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137
2138 mixedTracks++;
2139
2140 // track->mainBuffer() != mMixBuffer means there is an effect chain
2141 // connected to the track
2142 chain.clear();
2143 if (track->mainBuffer() != mMixBuffer) {
2144 chain = getEffectChain_l(track->sessionId());
2145 // Delegate volume control to effect in track effect chain if needed
2146 if (chain != 0) {
2147 tracksWithEffect++;
2148 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002149 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002150 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002151 }
2152 }
2153
2154
2155 int param = AudioMixer::VOLUME;
2156 if (track->mFillingUpStatus == Track::FS_FILLED) {
2157 // no ramp for the first volume setting
2158 track->mFillingUpStatus = Track::FS_ACTIVE;
2159 if (track->mState == TrackBase::RESUMING) {
2160 track->mState = TrackBase::ACTIVE;
2161 param = AudioMixer::RAMP_VOLUME;
2162 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002163 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 } else if (cblk->server != 0) {
2165 // If the track is stopped before the first frame was mixed,
2166 // do not apply ramp
2167 param = AudioMixer::RAMP_VOLUME;
2168 }
2169
2170 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002171 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002172 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002174 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175 if (track->isPausing()) {
2176 track->setPaused();
2177 }
2178 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002179
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 // read original volumes with volume control
2181 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002183 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2184 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185
Glenn Kasten05632a52012-01-03 14:22:33 -08002186 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2187 // send level comes from shared memory and so may be corrupt
2188 if (sendLevel >= 0x1000) {
2189 ALOGV("Track send level out of range: %04X", sendLevel);
2190 sendLevel = 0x1000;
2191 }
2192 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002194 // Delegate volume control to effect in track effect chain if needed
2195 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2196 // Do not ramp volume if volume is controlled by effect
2197 param = AudioMixer::VOLUME;
2198 track->mHasVolumeController = true;
2199 } else {
2200 // force no volume ramp when volume controller was just disabled or removed
2201 // from effect chain to avoid volume spike
2202 if (track->mHasVolumeController) {
2203 param = AudioMixer::VOLUME;
2204 }
2205 track->mHasVolumeController = false;
2206 }
2207
2208 // Convert volumes from 8.24 to 4.12 format
2209 int16_t left, right, aux;
2210 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2211 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2212 left = int16_t(v_clamped);
2213 v_clamped = (vr + (1 << 11)) >> 12;
2214 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2215 right = int16_t(v_clamped);
2216
2217 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2218 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002221 mAudioMixer->setBufferProvider(name, track);
2222 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002224 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2225 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2226 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002228 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 AudioMixer::TRACK,
2230 AudioMixer::FORMAT, (void *)track->format());
2231 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002232 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002234 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002236 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 AudioMixer::RESAMPLE,
2238 AudioMixer::SAMPLE_RATE,
2239 (void *)(cblk->sampleRate));
2240 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002241 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 AudioMixer::TRACK,
2243 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2244 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002245 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 AudioMixer::TRACK,
2247 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2248
2249 // reset retry count
2250 track->mRetryCount = kMaxTrackRetries;
2251 mixerStatus = MIXER_TRACKS_READY;
2252 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002253 //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 -07002254 if (track->isStopped()) {
2255 track->reset();
2256 }
2257 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2258 // We have consumed all the buffers of this track.
2259 // Remove it from the list of active tracks.
2260 tracksToRemove->add(track);
2261 } else {
2262 // No buffers for this track. Give it a few chances to
2263 // fill a buffer, then remove it from active list.
2264 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002265 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002267 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002268 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269 } else if (mixerStatus != MIXER_TRACKS_READY) {
2270 mixerStatus = MIXER_TRACKS_ENABLED;
2271 }
2272 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002273 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 }
2275 }
2276
2277 // remove all the tracks that need to be...
2278 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002279 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 for (size_t i=0 ; i<count ; i++) {
2281 const sp<Track>& track = tracksToRemove->itemAt(i);
2282 mActiveTracks.remove(track);
2283 if (track->mainBuffer() != mMixBuffer) {
2284 chain = getEffectChain_l(track->sessionId());
2285 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002286 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002287 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 }
2289 }
2290 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002291 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 }
2293 }
2294 }
2295
2296 // mix buffer must be cleared if all tracks are connected to an
2297 // effect chain as in this case the mixer will not write to
2298 // mix buffer and track effects will accumulate into it
2299 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2300 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2301 }
2302
2303 return mixerStatus;
2304}
2305
2306void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2307{
Steve Block3856b092011-10-20 11:56:00 +01002308 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002309 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002311
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 size_t size = mTracks.size();
2313 for (size_t i = 0; i < size; i++) {
2314 sp<Track> t = mTracks[i];
2315 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002316 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319 }
2320}
2321
Eric Laurent9f6530f2011-08-30 10:18:54 -07002322void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2323{
Steve Block3856b092011-10-20 11:56:00 +01002324 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002325 this, streamType, valid);
2326 Mutex::Autolock _l(mLock);
2327
2328 mStreamTypes[streamType].valid = valid;
2329}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330
2331// getTrackName_l() must be called with ThreadBase::mLock held
2332int AudioFlinger::MixerThread::getTrackName_l()
2333{
2334 return mAudioMixer->getTrackName();
2335}
2336
2337// deleteTrackName_l() must be called with ThreadBase::mLock held
2338void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2339{
Steve Block3856b092011-10-20 11:56:00 +01002340 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 mAudioMixer->deleteTrackName(name);
2342}
2343
2344// checkForNewParameters_l() must be called with ThreadBase::mLock held
2345bool AudioFlinger::MixerThread::checkForNewParameters_l()
2346{
2347 bool reconfig = false;
2348
2349 while (!mNewParameters.isEmpty()) {
2350 status_t status = NO_ERROR;
2351 String8 keyValuePair = mNewParameters[0];
2352 AudioParameter param = AudioParameter(keyValuePair);
2353 int value;
2354
2355 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2356 reconfig = true;
2357 }
2358 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002359 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 status = BAD_VALUE;
2361 } else {
2362 reconfig = true;
2363 }
2364 }
2365 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002366 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 status = BAD_VALUE;
2368 } else {
2369 reconfig = true;
2370 }
2371 }
2372 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2373 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002374 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375 // if frame count is changed after track creation
2376 if (!mTracks.isEmpty()) {
2377 status = INVALID_OPERATION;
2378 } else {
2379 reconfig = true;
2380 }
2381 }
2382 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002383 // when changing the audio output device, call addBatteryData to notify
2384 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002385 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002386 uint32_t params = 0;
2387 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002388 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002389 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2390 }
2391
2392 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002393 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002394 // check if any other device (except speaker) is on
2395 if (value & deviceWithoutSpeaker ) {
2396 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2397 }
2398
2399 if (params != 0) {
2400 addBatteryData(params);
2401 }
2402 }
2403
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 // forward device change to effects that have requested to be
2405 // aware of attached audio device.
2406 mDevice = (uint32_t)value;
2407 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002408 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 }
2410 }
2411
2412 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002413 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002414 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002416 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002417 mStandby = true;
2418 mBytesWritten = 0;
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 }
2422 if (status == NO_ERROR && reconfig) {
2423 delete mAudioMixer;
2424 readOutputParameters();
2425 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2426 for (size_t i = 0; i < mTracks.size() ; i++) {
2427 int name = getTrackName_l();
2428 if (name < 0) break;
2429 mTracks[i]->mName = name;
2430 // limit track sample rate to 2 x new output sample rate
2431 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2432 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2433 }
2434 }
2435 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2436 }
2437 }
2438
2439 mNewParameters.removeAt(0);
2440
2441 mParamStatus = status;
2442 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002443 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2444 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002445 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002446 }
2447 return reconfig;
2448}
2449
2450status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2451{
2452 const size_t SIZE = 256;
2453 char buffer[SIZE];
2454 String8 result;
2455
2456 PlaybackThread::dumpInternals(fd, args);
2457
2458 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2459 result.append(buffer);
2460 write(fd, result.string(), result.size());
2461 return NO_ERROR;
2462}
2463
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2465{
Eric Laurent60e18242010-07-29 06:50:24 -07002466 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467}
2468
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002469uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2470{
2471 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2472}
2473
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002475AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476 : PlaybackThread(audioFlinger, output, id, device)
2477{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002478 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479}
2480
2481AudioFlinger::DirectOutputThread::~DirectOutputThread()
2482{
2483}
2484
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485static inline
2486int32_t mul(int16_t in, int16_t v)
2487{
2488#if defined(__arm__) && !defined(__thumb__)
2489 int32_t out;
2490 asm( "smulbb %[out], %[in], %[v] \n"
2491 : [out]"=r"(out)
2492 : [in]"%r"(in), [v]"r"(v)
2493 : );
2494 return out;
2495#else
2496 return in * int32_t(v);
2497#endif
2498}
2499
2500void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2501{
2502 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002503 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 return;
2505 }
2506
2507 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002508 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509 size_t count = mFrameCount * mChannelCount;
2510 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2511 int16_t *dst = mMixBuffer + count-1;
2512 while(count--) {
2513 *dst-- = (int16_t)(*src--^0x80) << 8;
2514 }
2515 }
2516
2517 size_t frameCount = mFrameCount;
2518 int16_t *out = mMixBuffer;
2519 if (ramp) {
2520 if (mChannelCount == 1) {
2521 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2522 int32_t vlInc = d / (int32_t)frameCount;
2523 int32_t vl = ((int32_t)mLeftVolShort << 16);
2524 do {
2525 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2526 out++;
2527 vl += vlInc;
2528 } while (--frameCount);
2529
2530 } else {
2531 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2532 int32_t vlInc = d / (int32_t)frameCount;
2533 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2534 int32_t vrInc = d / (int32_t)frameCount;
2535 int32_t vl = ((int32_t)mLeftVolShort << 16);
2536 int32_t vr = ((int32_t)mRightVolShort << 16);
2537 do {
2538 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2539 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2540 out += 2;
2541 vl += vlInc;
2542 vr += vrInc;
2543 } while (--frameCount);
2544 }
2545 } else {
2546 if (mChannelCount == 1) {
2547 do {
2548 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2549 out++;
2550 } while (--frameCount);
2551 } else {
2552 do {
2553 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2554 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2555 out += 2;
2556 } while (--frameCount);
2557 }
2558 }
2559
2560 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002561 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002562 size_t count = mFrameCount * mChannelCount;
2563 int16_t *src = mMixBuffer;
2564 uint8_t *dst = (uint8_t *)mMixBuffer;
2565 while(count--) {
2566 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2567 }
2568 }
2569
2570 mLeftVolShort = leftVol;
2571 mRightVolShort = rightVol;
2572}
2573
2574bool AudioFlinger::DirectOutputThread::threadLoop()
2575{
2576 uint32_t mixerStatus = MIXER_IDLE;
2577 sp<Track> trackToRemove;
2578 sp<Track> activeTrack;
2579 nsecs_t standbyTime = systemTime();
2580 int8_t *curBuf;
2581 size_t mixBufferSize = mFrameCount*mFrameSize;
2582 uint32_t activeSleepTime = activeSleepTimeUs();
2583 uint32_t idleSleepTime = idleSleepTimeUs();
2584 uint32_t sleepTime = idleSleepTime;
2585 // use shorter standby delay as on normal output to release
2586 // hardware resources as soon as possible
2587 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2588
Eric Laurentfeb0db62011-07-22 09:04:31 -07002589 acquireWakeLock();
2590
Mathias Agopian65ab4712010-07-14 17:59:35 -07002591 while (!exitPending())
2592 {
2593 bool rampVolume;
2594 uint16_t leftVol;
2595 uint16_t rightVol;
2596 Vector< sp<EffectChain> > effectChains;
2597
2598 processConfigEvents();
2599
2600 mixerStatus = MIXER_IDLE;
2601
2602 { // scope for the mLock
2603
2604 Mutex::Autolock _l(mLock);
2605
2606 if (checkForNewParameters_l()) {
2607 mixBufferSize = mFrameCount*mFrameSize;
2608 activeSleepTime = activeSleepTimeUs();
2609 idleSleepTime = idleSleepTimeUs();
2610 standbyDelay = microseconds(activeSleepTime*2);
2611 }
2612
2613 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002614 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2615 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 // wait until we have something to do...
2617 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002618 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002619 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002620 mStandby = true;
2621 mBytesWritten = 0;
2622 }
2623
2624 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2625 // we're about to wait, flush the binder command buffer
2626 IPCThreadState::self()->flushCommands();
2627
2628 if (exitPending()) break;
2629
Eric Laurentfeb0db62011-07-22 09:04:31 -07002630 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002631 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002633 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002634 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635
2636 if (mMasterMute == false) {
2637 char value[PROPERTY_VALUE_MAX];
2638 property_get("ro.audio.silent", value, "0");
2639 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002640 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002641 setMasterMute(true);
2642 }
2643 }
2644
2645 standbyTime = systemTime() + standbyDelay;
2646 sleepTime = idleSleepTime;
2647 continue;
2648 }
2649 }
2650
2651 effectChains = mEffectChains;
2652
2653 // find out which tracks need to be processed
2654 if (mActiveTracks.size() != 0) {
2655 sp<Track> t = mActiveTracks[0].promote();
2656 if (t == 0) continue;
2657
2658 Track* const track = t.get();
2659 audio_track_cblk_t* cblk = track->cblk();
2660
2661 // The first time a track is added we wait
2662 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002663 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 !track->isPaused() && !track->isTerminated())
2665 {
Steve Block3856b092011-10-20 11:56:00 +01002666 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667
2668 if (track->mFillingUpStatus == Track::FS_FILLED) {
2669 track->mFillingUpStatus = Track::FS_ACTIVE;
2670 mLeftVolFloat = mRightVolFloat = 0;
2671 mLeftVolShort = mRightVolShort = 0;
2672 if (track->mState == TrackBase::RESUMING) {
2673 track->mState = TrackBase::ACTIVE;
2674 rampVolume = true;
2675 }
2676 } else if (cblk->server != 0) {
2677 // If the track is stopped before the first frame was mixed,
2678 // do not apply ramp
2679 rampVolume = true;
2680 }
2681 // compute volume for this track
2682 float left, right;
2683 if (track->isMuted() || mMasterMute || track->isPausing() ||
2684 mStreamTypes[track->type()].mute) {
2685 left = right = 0;
2686 if (track->isPausing()) {
2687 track->setPaused();
2688 }
2689 } else {
2690 float typeVolume = mStreamTypes[track->type()].volume;
2691 float v = mMasterVolume * typeVolume;
2692 float v_clamped = v * cblk->volume[0];
2693 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2694 left = v_clamped/MAX_GAIN;
2695 v_clamped = v * cblk->volume[1];
2696 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2697 right = v_clamped/MAX_GAIN;
2698 }
2699
2700 if (left != mLeftVolFloat || right != mRightVolFloat) {
2701 mLeftVolFloat = left;
2702 mRightVolFloat = right;
2703
2704 // If audio HAL implements volume control,
2705 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002706 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 left = 1.0f;
2708 right = 1.0f;
2709 }
2710
2711 // Convert volumes from float to 8.24
2712 uint32_t vl = (uint32_t)(left * (1 << 24));
2713 uint32_t vr = (uint32_t)(right * (1 << 24));
2714
2715 // Delegate volume control to effect in track effect chain if needed
2716 // only one effect chain can be present on DirectOutputThread, so if
2717 // there is one, the track is connected to it
2718 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002719 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002720 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 rampVolume = false;
2722 }
2723 }
2724
2725 // Convert volumes from 8.24 to 4.12 format
2726 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2727 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2728 leftVol = (uint16_t)v_clamped;
2729 v_clamped = (vr + (1 << 11)) >> 12;
2730 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2731 rightVol = (uint16_t)v_clamped;
2732 } else {
2733 leftVol = mLeftVolShort;
2734 rightVol = mRightVolShort;
2735 rampVolume = false;
2736 }
2737
2738 // reset retry count
2739 track->mRetryCount = kMaxTrackRetriesDirect;
2740 activeTrack = t;
2741 mixerStatus = MIXER_TRACKS_READY;
2742 } else {
Steve Block3856b092011-10-20 11:56:00 +01002743 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 if (track->isStopped()) {
2745 track->reset();
2746 }
2747 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2748 // We have consumed all the buffers of this track.
2749 // Remove it from the list of active tracks.
2750 trackToRemove = track;
2751 } else {
2752 // No buffers for this track. Give it a few chances to
2753 // fill a buffer, then remove it from active list.
2754 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002755 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 trackToRemove = track;
2757 } else {
2758 mixerStatus = MIXER_TRACKS_ENABLED;
2759 }
2760 }
2761 }
2762 }
2763
2764 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002765 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 mActiveTracks.remove(trackToRemove);
2767 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002768 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002769 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002770 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 }
2772 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002773 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774 }
2775 }
2776
Eric Laurentde070132010-07-13 04:45:46 -07002777 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 }
2779
Glenn Kastenf6b16782011-12-15 09:51:17 -08002780 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781 AudioBufferProvider::Buffer buffer;
2782 size_t frameCount = mFrameCount;
2783 curBuf = (int8_t *)mMixBuffer;
2784 // output audio to hardware
2785 while (frameCount) {
2786 buffer.frameCount = frameCount;
2787 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002788 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 memset(curBuf, 0, frameCount * mFrameSize);
2790 break;
2791 }
2792 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2793 frameCount -= buffer.frameCount;
2794 curBuf += buffer.frameCount * mFrameSize;
2795 activeTrack->releaseBuffer(&buffer);
2796 }
2797 sleepTime = 0;
2798 standbyTime = systemTime() + standbyDelay;
2799 } else {
2800 if (sleepTime == 0) {
2801 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2802 sleepTime = activeSleepTime;
2803 } else {
2804 sleepTime = idleSleepTime;
2805 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002806 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2808 sleepTime = 0;
2809 }
2810 }
2811
2812 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002813 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 }
2815 // sleepTime == 0 means we must write to audio hardware
2816 if (sleepTime == 0) {
2817 if (mixerStatus == MIXER_TRACKS_READY) {
2818 applyVolume(leftVol, rightVol, rampVolume);
2819 }
2820 for (size_t i = 0; i < effectChains.size(); i ++) {
2821 effectChains[i]->process_l();
2822 }
Eric Laurentde070132010-07-13 04:45:46 -07002823 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824
2825 mLastWriteTime = systemTime();
2826 mInWrite = true;
2827 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002828 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2830 mNumWrites++;
2831 mInWrite = false;
2832 mStandby = false;
2833 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002834 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835 usleep(sleepTime);
2836 }
2837
2838 // finally let go of removed track, without the lock held
2839 // since we can't guarantee the destructors won't acquire that
2840 // same lock.
2841 trackToRemove.clear();
2842 activeTrack.clear();
2843
2844 // Effect chains will be actually deleted here if they were removed from
2845 // mEffectChains list during mixing or effects processing
2846 effectChains.clear();
2847 }
2848
2849 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002850 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 }
2852
Eric Laurentfeb0db62011-07-22 09:04:31 -07002853 releaseWakeLock();
2854
Steve Block3856b092011-10-20 11:56:00 +01002855 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 return false;
2857}
2858
2859// getTrackName_l() must be called with ThreadBase::mLock held
2860int AudioFlinger::DirectOutputThread::getTrackName_l()
2861{
2862 return 0;
2863}
2864
2865// deleteTrackName_l() must be called with ThreadBase::mLock held
2866void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2867{
2868}
2869
2870// checkForNewParameters_l() must be called with ThreadBase::mLock held
2871bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2872{
2873 bool reconfig = false;
2874
2875 while (!mNewParameters.isEmpty()) {
2876 status_t status = NO_ERROR;
2877 String8 keyValuePair = mNewParameters[0];
2878 AudioParameter param = AudioParameter(keyValuePair);
2879 int value;
2880
2881 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2882 // do not accept frame count changes if tracks are open as the track buffer
2883 // size depends on frame count and correct behavior would not be garantied
2884 // if frame count is changed after track creation
2885 if (!mTracks.isEmpty()) {
2886 status = INVALID_OPERATION;
2887 } else {
2888 reconfig = true;
2889 }
2890 }
2891 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002892 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002893 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002895 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 mStandby = true;
2897 mBytesWritten = 0;
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 }
2901 if (status == NO_ERROR && reconfig) {
2902 readOutputParameters();
2903 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2904 }
2905 }
2906
2907 mNewParameters.removeAt(0);
2908
2909 mParamStatus = status;
2910 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002911 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2912 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002913 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 }
2915 return reconfig;
2916}
2917
2918uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2919{
2920 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002921 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002922 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 } else {
2924 time = 10000;
2925 }
2926 return time;
2927}
2928
2929uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2930{
2931 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002932 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002933 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 } else {
2935 time = 10000;
2936 }
2937 return time;
2938}
2939
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002940uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2941{
2942 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002943 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002944 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2945 } else {
2946 time = 10000;
2947 }
2948 return time;
2949}
2950
2951
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952// ----------------------------------------------------------------------------
2953
2954AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2955 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2956{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002957 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 addOutputTrack(mainThread);
2959}
2960
2961AudioFlinger::DuplicatingThread::~DuplicatingThread()
2962{
2963 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2964 mOutputTracks[i]->destroy();
2965 }
2966 mOutputTracks.clear();
2967}
2968
2969bool AudioFlinger::DuplicatingThread::threadLoop()
2970{
2971 Vector< sp<Track> > tracksToRemove;
2972 uint32_t mixerStatus = MIXER_IDLE;
2973 nsecs_t standbyTime = systemTime();
2974 size_t mixBufferSize = mFrameCount*mFrameSize;
2975 SortedVector< sp<OutputTrack> > outputTracks;
2976 uint32_t writeFrames = 0;
2977 uint32_t activeSleepTime = activeSleepTimeUs();
2978 uint32_t idleSleepTime = idleSleepTimeUs();
2979 uint32_t sleepTime = idleSleepTime;
2980 Vector< sp<EffectChain> > effectChains;
2981
Eric Laurentfeb0db62011-07-22 09:04:31 -07002982 acquireWakeLock();
2983
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 while (!exitPending())
2985 {
2986 processConfigEvents();
2987
2988 mixerStatus = MIXER_IDLE;
2989 { // scope for the mLock
2990
2991 Mutex::Autolock _l(mLock);
2992
2993 if (checkForNewParameters_l()) {
2994 mixBufferSize = mFrameCount*mFrameSize;
2995 updateWaitTime();
2996 activeSleepTime = activeSleepTimeUs();
2997 idleSleepTime = idleSleepTimeUs();
2998 }
2999
3000 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3001
3002 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3003 outputTracks.add(mOutputTracks[i]);
3004 }
3005
3006 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003007 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3008 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 if (!mStandby) {
3010 for (size_t i = 0; i < outputTracks.size(); i++) {
3011 outputTracks[i]->stop();
3012 }
3013 mStandby = true;
3014 mBytesWritten = 0;
3015 }
3016
3017 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3018 // we're about to wait, flush the binder command buffer
3019 IPCThreadState::self()->flushCommands();
3020 outputTracks.clear();
3021
3022 if (exitPending()) break;
3023
Eric Laurentfeb0db62011-07-22 09:04:31 -07003024 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003025 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003027 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003028 acquireWakeLock_l();
3029
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 if (mMasterMute == false) {
3031 char value[PROPERTY_VALUE_MAX];
3032 property_get("ro.audio.silent", value, "0");
3033 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003034 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003035 setMasterMute(true);
3036 }
3037 }
3038
3039 standbyTime = systemTime() + kStandbyTimeInNsecs;
3040 sleepTime = idleSleepTime;
3041 continue;
3042 }
3043 }
3044
3045 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3046
3047 // prevent any changes in effect chain list and in each effect chain
3048 // during mixing and effect process as the audio buffers could be deleted
3049 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003050 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003051 }
3052
Glenn Kastenf6b16782011-12-15 09:51:17 -08003053 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003054 // mix buffers...
3055 if (outputsReady(outputTracks)) {
3056 mAudioMixer->process();
3057 } else {
3058 memset(mMixBuffer, 0, mixBufferSize);
3059 }
3060 sleepTime = 0;
3061 writeFrames = mFrameCount;
3062 } else {
3063 if (sleepTime == 0) {
3064 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3065 sleepTime = activeSleepTime;
3066 } else {
3067 sleepTime = idleSleepTime;
3068 }
3069 } else if (mBytesWritten != 0) {
3070 // flush remaining overflow buffers in output tracks
3071 for (size_t i = 0; i < outputTracks.size(); i++) {
3072 if (outputTracks[i]->isActive()) {
3073 sleepTime = 0;
3074 writeFrames = 0;
3075 memset(mMixBuffer, 0, mixBufferSize);
3076 break;
3077 }
3078 }
3079 }
3080 }
3081
3082 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003083 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 }
3085 // sleepTime == 0 means we must write to audio hardware
3086 if (sleepTime == 0) {
3087 for (size_t i = 0; i < effectChains.size(); i ++) {
3088 effectChains[i]->process_l();
3089 }
3090 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003091 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003092
3093 standbyTime = systemTime() + kStandbyTimeInNsecs;
3094 for (size_t i = 0; i < outputTracks.size(); i++) {
3095 outputTracks[i]->write(mMixBuffer, writeFrames);
3096 }
3097 mStandby = false;
3098 mBytesWritten += mixBufferSize;
3099 } else {
3100 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003101 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 usleep(sleepTime);
3103 }
3104
3105 // finally let go of all our tracks, without the lock held
3106 // since we can't guarantee the destructors won't acquire that
3107 // same lock.
3108 tracksToRemove.clear();
3109 outputTracks.clear();
3110
3111 // Effect chains will be actually deleted here if they were removed from
3112 // mEffectChains list during mixing or effects processing
3113 effectChains.clear();
3114 }
3115
Eric Laurentfeb0db62011-07-22 09:04:31 -07003116 releaseWakeLock();
3117
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 return false;
3119}
3120
3121void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3122{
3123 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3124 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3125 this,
3126 mSampleRate,
3127 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003128 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 frameCount);
3130 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003131 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003132 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003133 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 updateWaitTime();
3135 }
3136}
3137
3138void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3139{
3140 Mutex::Autolock _l(mLock);
3141 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3142 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3143 mOutputTracks[i]->destroy();
3144 mOutputTracks.removeAt(i);
3145 updateWaitTime();
3146 return;
3147 }
3148 }
Steve Block3856b092011-10-20 11:56:00 +01003149 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150}
3151
3152void AudioFlinger::DuplicatingThread::updateWaitTime()
3153{
3154 mWaitTimeMs = UINT_MAX;
3155 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3156 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3157 if (strong != NULL) {
3158 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3159 if (waitTimeMs < mWaitTimeMs) {
3160 mWaitTimeMs = waitTimeMs;
3161 }
3162 }
3163 }
3164}
3165
3166
3167bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3168{
3169 for (size_t i = 0; i < outputTracks.size(); i++) {
3170 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3171 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003172 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 return false;
3174 }
3175 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3176 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003177 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003178 return false;
3179 }
3180 }
3181 return true;
3182}
3183
3184uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3185{
3186 return (mWaitTimeMs * 1000) / 2;
3187}
3188
3189// ----------------------------------------------------------------------------
3190
3191// TrackBase constructor must be called with AudioFlinger::mLock held
3192AudioFlinger::ThreadBase::TrackBase::TrackBase(
3193 const wp<ThreadBase>& thread,
3194 const sp<Client>& client,
3195 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003196 uint32_t format,
3197 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 int frameCount,
3199 uint32_t flags,
3200 const sp<IMemory>& sharedBuffer,
3201 int sessionId)
3202 : RefBase(),
3203 mThread(thread),
3204 mClient(client),
3205 mCblk(0),
3206 mFrameCount(0),
3207 mState(IDLE),
3208 mClientTid(-1),
3209 mFormat(format),
3210 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3211 mSessionId(sessionId)
3212{
Steve Block3856b092011-10-20 11:56:00 +01003213 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214
Steve Blockb8a80522011-12-20 16:23:08 +00003215 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003217 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3219 if (sharedBuffer == 0) {
3220 size += bufferSize;
3221 }
3222
3223 if (client != NULL) {
3224 mCblkMemory = client->heap()->allocate(size);
3225 if (mCblkMemory != 0) {
3226 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3227 if (mCblk) { // construct the shared structure in-place.
3228 new(mCblk) audio_track_cblk_t();
3229 // clear all buffers
3230 mCblk->frameCount = frameCount;
3231 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003232 mChannelCount = channelCount;
3233 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 if (sharedBuffer == 0) {
3235 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3236 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3237 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003238 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239 mCblk->flags = CBLK_UNDERRUN_ON;
3240 } else {
3241 mBuffer = sharedBuffer->pointer();
3242 }
3243 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3244 }
3245 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003246 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003247 client->heap()->dump("AudioTrack");
3248 return;
3249 }
3250 } else {
3251 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003252 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 new(mCblk) audio_track_cblk_t();
3254 // clear all buffers
3255 mCblk->frameCount = frameCount;
3256 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003257 mChannelCount = channelCount;
3258 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3260 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3261 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003262 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 mCblk->flags = CBLK_UNDERRUN_ON;
3264 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 }
3266}
3267
3268AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3269{
3270 if (mCblk) {
3271 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3272 if (mClient == NULL) {
3273 delete mCblk;
3274 }
3275 }
3276 mCblkMemory.clear(); // and free the shared memory
3277 if (mClient != NULL) {
3278 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3279 mClient.clear();
3280 }
3281}
3282
3283void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3284{
Glenn Kastene0feee32011-12-13 11:53:26 -08003285 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 mFrameCount = buffer->frameCount;
3287 step();
3288 buffer->frameCount = 0;
3289}
3290
3291bool AudioFlinger::ThreadBase::TrackBase::step() {
3292 bool result;
3293 audio_track_cblk_t* cblk = this->cblk();
3294
3295 result = cblk->stepServer(mFrameCount);
3296 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003297 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 mFlags |= STEPSERVER_FAILED;
3299 }
3300 return result;
3301}
3302
3303void AudioFlinger::ThreadBase::TrackBase::reset() {
3304 audio_track_cblk_t* cblk = this->cblk();
3305
3306 cblk->user = 0;
3307 cblk->server = 0;
3308 cblk->userBase = 0;
3309 cblk->serverBase = 0;
3310 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003311 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312}
3313
3314sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3315{
3316 return mCblkMemory;
3317}
3318
3319int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3320 return (int)mCblk->sampleRate;
3321}
3322
3323int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003324 return (const int)mChannelCount;
3325}
3326
3327uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3328 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329}
3330
3331void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3332 audio_track_cblk_t* cblk = this->cblk();
3333 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3334 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3335
3336 // Check validity of returned pointer in case the track control block would have been corrupted.
3337 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3338 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003339 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 -07003340 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003342 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 return 0;
3344 }
3345
3346 return bufferStart;
3347}
3348
3349// ----------------------------------------------------------------------------
3350
3351// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3352AudioFlinger::PlaybackThread::Track::Track(
3353 const wp<ThreadBase>& thread,
3354 const sp<Client>& client,
3355 int streamType,
3356 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003357 uint32_t format,
3358 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 int frameCount,
3360 const sp<IMemory>& sharedBuffer,
3361 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003362 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003363 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3364 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365{
3366 if (mCblk != NULL) {
3367 sp<ThreadBase> baseThread = thread.promote();
3368 if (baseThread != 0) {
3369 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3370 mName = playbackThread->getTrackName_l();
3371 mMainBuffer = playbackThread->mixBuffer();
3372 }
Steve Block3856b092011-10-20 11:56:00 +01003373 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003375 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 }
3377 mVolume[0] = 1.0f;
3378 mVolume[1] = 1.0f;
3379 mStreamType = streamType;
3380 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3381 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003382 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 }
3384}
3385
3386AudioFlinger::PlaybackThread::Track::~Track()
3387{
Steve Block3856b092011-10-20 11:56:00 +01003388 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 sp<ThreadBase> thread = mThread.promote();
3390 if (thread != 0) {
3391 Mutex::Autolock _l(thread->mLock);
3392 mState = TERMINATED;
3393 }
3394}
3395
3396void AudioFlinger::PlaybackThread::Track::destroy()
3397{
3398 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3399 // by removing it from mTracks vector, so there is a risk that this Tracks's
3400 // desctructor is called. As the destructor needs to lock mLock,
3401 // we must acquire a strong reference on this Track before locking mLock
3402 // here so that the destructor is called only when exiting this function.
3403 // On the other hand, as long as Track::destroy() is only called by
3404 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3405 // this Track with its member mTrack.
3406 sp<Track> keep(this);
3407 { // scope for mLock
3408 sp<ThreadBase> thread = mThread.promote();
3409 if (thread != 0) {
3410 if (!isOutputTrack()) {
3411 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003412 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003413 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003414 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003415
3416 // to track the speaker usage
3417 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418 }
3419 AudioSystem::releaseOutput(thread->id());
3420 }
3421 Mutex::Autolock _l(thread->mLock);
3422 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3423 playbackThread->destroyTrack_l(this);
3424 }
3425 }
3426}
3427
3428void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3429{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003430 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 -07003431 mName - AudioMixer::TRACK0,
3432 (mClient == NULL) ? getpid() : mClient->pid(),
3433 mStreamType,
3434 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003435 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 mSessionId,
3437 mFrameCount,
3438 mState,
3439 mMute,
3440 mFillingUpStatus,
3441 mCblk->sampleRate,
3442 mCblk->volume[0],
3443 mCblk->volume[1],
3444 mCblk->server,
3445 mCblk->user,
3446 (int)mMainBuffer,
3447 (int)mAuxBuffer);
3448}
3449
3450status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3451{
3452 audio_track_cblk_t* cblk = this->cblk();
3453 uint32_t framesReady;
3454 uint32_t framesReq = buffer->frameCount;
3455
3456 // Check if last stepServer failed, try to step now
3457 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3458 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003459 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3461 }
3462
3463 framesReady = cblk->framesReady();
3464
Glenn Kastenf6b16782011-12-15 09:51:17 -08003465 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 uint32_t s = cblk->server;
3467 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3468
3469 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3470 if (framesReq > framesReady) {
3471 framesReq = framesReady;
3472 }
3473 if (s + framesReq > bufferEnd) {
3474 framesReq = bufferEnd - s;
3475 }
3476
3477 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003478 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479
3480 buffer->frameCount = framesReq;
3481 return NO_ERROR;
3482 }
3483
3484getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003485 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003487 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003488 return NOT_ENOUGH_DATA;
3489}
3490
3491bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003492 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493
3494 if (mCblk->framesReady() >= mCblk->frameCount ||
3495 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3496 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003497 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498 return true;
3499 }
3500 return false;
3501}
3502
3503status_t AudioFlinger::PlaybackThread::Track::start()
3504{
3505 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003506 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003507 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508 sp<ThreadBase> thread = mThread.promote();
3509 if (thread != 0) {
3510 Mutex::Autolock _l(thread->mLock);
3511 int state = mState;
3512 // here the track could be either new, or restarted
3513 // in both cases "unstop" the track
3514 if (mState == PAUSED) {
3515 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003516 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 } else {
3518 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003519 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 }
3521
3522 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3523 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003524 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003525 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003526 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003528
3529 // to track the speaker usage
3530 if (status == NO_ERROR) {
3531 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 }
3534 if (status == NO_ERROR) {
3535 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3536 playbackThread->addTrack_l(this);
3537 } else {
3538 mState = state;
3539 }
3540 } else {
3541 status = BAD_VALUE;
3542 }
3543 return status;
3544}
3545
3546void AudioFlinger::PlaybackThread::Track::stop()
3547{
Steve Block3856b092011-10-20 11:56:00 +01003548 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003549 sp<ThreadBase> thread = mThread.promote();
3550 if (thread != 0) {
3551 Mutex::Autolock _l(thread->mLock);
3552 int state = mState;
3553 if (mState > STOPPED) {
3554 mState = STOPPED;
3555 // If the track is not active (PAUSED and buffers full), flush buffers
3556 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3557 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3558 reset();
3559 }
Steve Block3856b092011-10-20 11:56:00 +01003560 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 }
3562 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3563 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003564 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003565 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003566 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003568
3569 // to track the speaker usage
3570 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 }
3572 }
3573}
3574
3575void AudioFlinger::PlaybackThread::Track::pause()
3576{
Steve Block3856b092011-10-20 11:56:00 +01003577 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 sp<ThreadBase> thread = mThread.promote();
3579 if (thread != 0) {
3580 Mutex::Autolock _l(thread->mLock);
3581 if (mState == ACTIVE || mState == RESUMING) {
3582 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003583 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 if (!isOutputTrack()) {
3585 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003586 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003587 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003588 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003590
3591 // to track the speaker usage
3592 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 }
3594 }
3595 }
3596}
3597
3598void AudioFlinger::PlaybackThread::Track::flush()
3599{
Steve Block3856b092011-10-20 11:56:00 +01003600 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 sp<ThreadBase> thread = mThread.promote();
3602 if (thread != 0) {
3603 Mutex::Autolock _l(thread->mLock);
3604 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3605 return;
3606 }
3607 // No point remaining in PAUSED state after a flush => go to
3608 // STOPPED state
3609 mState = STOPPED;
3610
Eric Laurent38ccae22011-03-28 18:37:07 -07003611 // do not reset the track if it is still in the process of being stopped or paused.
3612 // this will be done by prepareTracks_l() when the track is stopped.
3613 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3614 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3615 reset();
3616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 }
3618}
3619
3620void AudioFlinger::PlaybackThread::Track::reset()
3621{
3622 // Do not reset twice to avoid discarding data written just after a flush and before
3623 // the audioflinger thread detects the track is stopped.
3624 if (!mResetDone) {
3625 TrackBase::reset();
3626 // Force underrun condition to avoid false underrun callback until first data is
3627 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003628 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3629 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 mFillingUpStatus = FS_FILLING;
3631 mResetDone = true;
3632 }
3633}
3634
3635void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3636{
3637 mMute = muted;
3638}
3639
3640void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3641{
3642 mVolume[0] = left;
3643 mVolume[1] = right;
3644}
3645
3646status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3647{
3648 status_t status = DEAD_OBJECT;
3649 sp<ThreadBase> thread = mThread.promote();
3650 if (thread != 0) {
3651 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3652 status = playbackThread->attachAuxEffect(this, EffectId);
3653 }
3654 return status;
3655}
3656
3657void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3658{
3659 mAuxEffectId = EffectId;
3660 mAuxBuffer = buffer;
3661}
3662
3663// ----------------------------------------------------------------------------
3664
3665// RecordTrack constructor must be called with AudioFlinger::mLock held
3666AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3667 const wp<ThreadBase>& thread,
3668 const sp<Client>& client,
3669 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003670 uint32_t format,
3671 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 int frameCount,
3673 uint32_t flags,
3674 int sessionId)
3675 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003676 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677 mOverflow(false)
3678{
3679 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003680 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003681 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003682 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003683 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003684 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 } else {
3686 mCblk->frameSize = sizeof(int8_t);
3687 }
3688 }
3689}
3690
3691AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3692{
3693 sp<ThreadBase> thread = mThread.promote();
3694 if (thread != 0) {
3695 AudioSystem::releaseInput(thread->id());
3696 }
3697}
3698
3699status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3700{
3701 audio_track_cblk_t* cblk = this->cblk();
3702 uint32_t framesAvail;
3703 uint32_t framesReq = buffer->frameCount;
3704
3705 // Check if last stepServer failed, try to step now
3706 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3707 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003708 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3710 }
3711
3712 framesAvail = cblk->framesAvailable_l();
3713
Glenn Kastenf6b16782011-12-15 09:51:17 -08003714 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003715 uint32_t s = cblk->server;
3716 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3717
3718 if (framesReq > framesAvail) {
3719 framesReq = framesAvail;
3720 }
3721 if (s + framesReq > bufferEnd) {
3722 framesReq = bufferEnd - s;
3723 }
3724
3725 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003726 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727
3728 buffer->frameCount = framesReq;
3729 return NO_ERROR;
3730 }
3731
3732getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003733 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 buffer->frameCount = 0;
3735 return NOT_ENOUGH_DATA;
3736}
3737
3738status_t AudioFlinger::RecordThread::RecordTrack::start()
3739{
3740 sp<ThreadBase> thread = mThread.promote();
3741 if (thread != 0) {
3742 RecordThread *recordThread = (RecordThread *)thread.get();
3743 return recordThread->start(this);
3744 } else {
3745 return BAD_VALUE;
3746 }
3747}
3748
3749void AudioFlinger::RecordThread::RecordTrack::stop()
3750{
3751 sp<ThreadBase> thread = mThread.promote();
3752 if (thread != 0) {
3753 RecordThread *recordThread = (RecordThread *)thread.get();
3754 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003755 TrackBase::reset();
3756 // Force overerrun condition to avoid false overrun callback until first data is
3757 // read from buffer
3758 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759 }
3760}
3761
3762void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3763{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003764 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 (mClient == NULL) ? getpid() : mClient->pid(),
3766 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003767 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 mSessionId,
3769 mFrameCount,
3770 mState,
3771 mCblk->sampleRate,
3772 mCblk->server,
3773 mCblk->user);
3774}
3775
3776
3777// ----------------------------------------------------------------------------
3778
3779AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3780 const wp<ThreadBase>& thread,
3781 DuplicatingThread *sourceThread,
3782 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003783 uint32_t format,
3784 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003786 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787 mActive(false), mSourceThread(sourceThread)
3788{
3789
3790 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3791 if (mCblk != NULL) {
3792 mCblk->flags |= CBLK_DIRECTION_OUT;
3793 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3794 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3795 mOutBuffer.frameCount = 0;
3796 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003797 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003798 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3799 mCblk, mBuffer, mCblk->buffers,
3800 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003802 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003803 }
3804}
3805
3806AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3807{
3808 clearBufferQueue();
3809}
3810
3811status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3812{
3813 status_t status = Track::start();
3814 if (status != NO_ERROR) {
3815 return status;
3816 }
3817
3818 mActive = true;
3819 mRetryCount = 127;
3820 return status;
3821}
3822
3823void AudioFlinger::PlaybackThread::OutputTrack::stop()
3824{
3825 Track::stop();
3826 clearBufferQueue();
3827 mOutBuffer.frameCount = 0;
3828 mActive = false;
3829}
3830
3831bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3832{
3833 Buffer *pInBuffer;
3834 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003835 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836 bool outputBufferFull = false;
3837 inBuffer.frameCount = frames;
3838 inBuffer.i16 = data;
3839
3840 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3841
3842 if (!mActive && frames != 0) {
3843 start();
3844 sp<ThreadBase> thread = mThread.promote();
3845 if (thread != 0) {
3846 MixerThread *mixerThread = (MixerThread *)thread.get();
3847 if (mCblk->frameCount > frames){
3848 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3849 uint32_t startFrames = (mCblk->frameCount - frames);
3850 pInBuffer = new Buffer;
3851 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3852 pInBuffer->frameCount = startFrames;
3853 pInBuffer->i16 = pInBuffer->mBuffer;
3854 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3855 mBufferQueue.add(pInBuffer);
3856 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003857 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858 }
3859 }
3860 }
3861 }
3862
3863 while (waitTimeLeftMs) {
3864 // First write pending buffers, then new data
3865 if (mBufferQueue.size()) {
3866 pInBuffer = mBufferQueue.itemAt(0);
3867 } else {
3868 pInBuffer = &inBuffer;
3869 }
3870
3871 if (pInBuffer->frameCount == 0) {
3872 break;
3873 }
3874
3875 if (mOutBuffer.frameCount == 0) {
3876 mOutBuffer.frameCount = pInBuffer->frameCount;
3877 nsecs_t startTime = systemTime();
3878 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003879 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880 outputBufferFull = true;
3881 break;
3882 }
3883 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3884 if (waitTimeLeftMs >= waitTimeMs) {
3885 waitTimeLeftMs -= waitTimeMs;
3886 } else {
3887 waitTimeLeftMs = 0;
3888 }
3889 }
3890
3891 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3892 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3893 mCblk->stepUser(outFrames);
3894 pInBuffer->frameCount -= outFrames;
3895 pInBuffer->i16 += outFrames * channelCount;
3896 mOutBuffer.frameCount -= outFrames;
3897 mOutBuffer.i16 += outFrames * channelCount;
3898
3899 if (pInBuffer->frameCount == 0) {
3900 if (mBufferQueue.size()) {
3901 mBufferQueue.removeAt(0);
3902 delete [] pInBuffer->mBuffer;
3903 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003904 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 } else {
3906 break;
3907 }
3908 }
3909 }
3910
3911 // If we could not write all frames, allocate a buffer and queue it for next time.
3912 if (inBuffer.frameCount) {
3913 sp<ThreadBase> thread = mThread.promote();
3914 if (thread != 0 && !thread->standby()) {
3915 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3916 pInBuffer = new Buffer;
3917 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3918 pInBuffer->frameCount = inBuffer.frameCount;
3919 pInBuffer->i16 = pInBuffer->mBuffer;
3920 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3921 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003922 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003923 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003924 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925 }
3926 }
3927 }
3928
3929 // Calling write() with a 0 length buffer, means that no more data will be written:
3930 // If no more buffers are pending, fill output track buffer to make sure it is started
3931 // by output mixer.
3932 if (frames == 0 && mBufferQueue.size() == 0) {
3933 if (mCblk->user < mCblk->frameCount) {
3934 frames = mCblk->frameCount - mCblk->user;
3935 pInBuffer = new Buffer;
3936 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3937 pInBuffer->frameCount = frames;
3938 pInBuffer->i16 = pInBuffer->mBuffer;
3939 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3940 mBufferQueue.add(pInBuffer);
3941 } else if (mActive) {
3942 stop();
3943 }
3944 }
3945
3946 return outputBufferFull;
3947}
3948
3949status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3950{
3951 int active;
3952 status_t result;
3953 audio_track_cblk_t* cblk = mCblk;
3954 uint32_t framesReq = buffer->frameCount;
3955
Steve Block3856b092011-10-20 11:56:00 +01003956// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957 buffer->frameCount = 0;
3958
3959 uint32_t framesAvail = cblk->framesAvailable();
3960
3961
3962 if (framesAvail == 0) {
3963 Mutex::Autolock _l(cblk->lock);
3964 goto start_loop_here;
3965 while (framesAvail == 0) {
3966 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003967 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003968 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 return AudioTrack::NO_MORE_BUFFERS;
3970 }
3971 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3972 if (result != NO_ERROR) {
3973 return AudioTrack::NO_MORE_BUFFERS;
3974 }
3975 // read the server count again
3976 start_loop_here:
3977 framesAvail = cblk->framesAvailable_l();
3978 }
3979 }
3980
3981// if (framesAvail < framesReq) {
3982// return AudioTrack::NO_MORE_BUFFERS;
3983// }
3984
3985 if (framesReq > framesAvail) {
3986 framesReq = framesAvail;
3987 }
3988
3989 uint32_t u = cblk->user;
3990 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3991
3992 if (u + framesReq > bufferEnd) {
3993 framesReq = bufferEnd - u;
3994 }
3995
3996 buffer->frameCount = framesReq;
3997 buffer->raw = (void *)cblk->buffer(u);
3998 return NO_ERROR;
3999}
4000
4001
4002void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4003{
4004 size_t size = mBufferQueue.size();
4005 Buffer *pBuffer;
4006
4007 for (size_t i = 0; i < size; i++) {
4008 pBuffer = mBufferQueue.itemAt(i);
4009 delete [] pBuffer->mBuffer;
4010 delete pBuffer;
4011 }
4012 mBufferQueue.clear();
4013}
4014
4015// ----------------------------------------------------------------------------
4016
4017AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4018 : RefBase(),
4019 mAudioFlinger(audioFlinger),
4020 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4021 mPid(pid)
4022{
4023 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4024}
4025
4026// Client destructor must be called with AudioFlinger::mLock held
4027AudioFlinger::Client::~Client()
4028{
4029 mAudioFlinger->removeClient_l(mPid);
4030}
4031
4032const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4033{
4034 return mMemoryDealer;
4035}
4036
4037// ----------------------------------------------------------------------------
4038
4039AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4040 const sp<IAudioFlingerClient>& client,
4041 pid_t pid)
4042 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4043{
4044}
4045
4046AudioFlinger::NotificationClient::~NotificationClient()
4047{
4048 mClient.clear();
4049}
4050
4051void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4052{
4053 sp<NotificationClient> keep(this);
4054 {
4055 mAudioFlinger->removeNotificationClient(mPid);
4056 }
4057}
4058
4059// ----------------------------------------------------------------------------
4060
4061AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4062 : BnAudioTrack(),
4063 mTrack(track)
4064{
4065}
4066
4067AudioFlinger::TrackHandle::~TrackHandle() {
4068 // just stop the track on deletion, associated resources
4069 // will be freed from the main thread once all pending buffers have
4070 // been played. Unless it's not in the active track list, in which
4071 // case we free everything now...
4072 mTrack->destroy();
4073}
4074
4075status_t AudioFlinger::TrackHandle::start() {
4076 return mTrack->start();
4077}
4078
4079void AudioFlinger::TrackHandle::stop() {
4080 mTrack->stop();
4081}
4082
4083void AudioFlinger::TrackHandle::flush() {
4084 mTrack->flush();
4085}
4086
4087void AudioFlinger::TrackHandle::mute(bool e) {
4088 mTrack->mute(e);
4089}
4090
4091void AudioFlinger::TrackHandle::pause() {
4092 mTrack->pause();
4093}
4094
4095void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4096 mTrack->setVolume(left, right);
4097}
4098
4099sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4100 return mTrack->getCblk();
4101}
4102
4103status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4104{
4105 return mTrack->attachAuxEffect(EffectId);
4106}
4107
4108status_t AudioFlinger::TrackHandle::onTransact(
4109 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4110{
4111 return BnAudioTrack::onTransact(code, data, reply, flags);
4112}
4113
4114// ----------------------------------------------------------------------------
4115
4116sp<IAudioRecord> AudioFlinger::openRecord(
4117 pid_t pid,
4118 int input,
4119 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004120 uint32_t format,
4121 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 int frameCount,
4123 uint32_t flags,
4124 int *sessionId,
4125 status_t *status)
4126{
4127 sp<RecordThread::RecordTrack> recordTrack;
4128 sp<RecordHandle> recordHandle;
4129 sp<Client> client;
4130 wp<Client> wclient;
4131 status_t lStatus;
4132 RecordThread *thread;
4133 size_t inFrameCount;
4134 int lSessionId;
4135
4136 // check calling permissions
4137 if (!recordingAllowed()) {
4138 lStatus = PERMISSION_DENIED;
4139 goto Exit;
4140 }
4141
4142 // add client to list
4143 { // scope for mLock
4144 Mutex::Autolock _l(mLock);
4145 thread = checkRecordThread_l(input);
4146 if (thread == NULL) {
4147 lStatus = BAD_VALUE;
4148 goto Exit;
4149 }
4150
4151 wclient = mClients.valueFor(pid);
4152 if (wclient != NULL) {
4153 client = wclient.promote();
4154 } else {
4155 client = new Client(this, pid);
4156 mClients.add(pid, client);
4157 }
4158
4159 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004160 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 lSessionId = *sessionId;
4162 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004163 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 if (sessionId != NULL) {
4165 *sessionId = lSessionId;
4166 }
4167 }
4168 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004169 recordTrack = thread->createRecordTrack_l(client,
4170 sampleRate,
4171 format,
4172 channelMask,
4173 frameCount,
4174 flags,
4175 lSessionId,
4176 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004178 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4180 // destructor is called by the TrackBase destructor with mLock held
4181 client.clear();
4182 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 goto Exit;
4184 }
4185
4186 // return to handle to client
4187 recordHandle = new RecordHandle(recordTrack);
4188 lStatus = NO_ERROR;
4189
4190Exit:
4191 if (status) {
4192 *status = lStatus;
4193 }
4194 return recordHandle;
4195}
4196
4197// ----------------------------------------------------------------------------
4198
4199AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4200 : BnAudioRecord(),
4201 mRecordTrack(recordTrack)
4202{
4203}
4204
4205AudioFlinger::RecordHandle::~RecordHandle() {
4206 stop();
4207}
4208
4209status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004210 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 return mRecordTrack->start();
4212}
4213
4214void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004215 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 mRecordTrack->stop();
4217}
4218
4219sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4220 return mRecordTrack->getCblk();
4221}
4222
4223status_t AudioFlinger::RecordHandle::onTransact(
4224 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4225{
4226 return BnAudioRecord::onTransact(code, data, reply, flags);
4227}
4228
4229// ----------------------------------------------------------------------------
4230
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004231AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4232 AudioStreamIn *input,
4233 uint32_t sampleRate,
4234 uint32_t channels,
4235 int id,
4236 uint32_t device) :
4237 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004238 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004240 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004241
4242 snprintf(mName, kNameLength, "AudioIn_%d", id);
4243
Dima Zavinfce7a472011-04-19 22:30:36 -07004244 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245 mReqSampleRate = sampleRate;
4246 readInputParameters();
4247}
4248
4249
4250AudioFlinger::RecordThread::~RecordThread()
4251{
4252 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004253 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 delete mResampler;
4255 delete[] mRsmpOutBuffer;
4256 }
4257}
4258
4259void AudioFlinger::RecordThread::onFirstRef()
4260{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004261 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262}
4263
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004264status_t AudioFlinger::RecordThread::readyToRun()
4265{
4266 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004267 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004268 return status;
4269}
4270
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271bool AudioFlinger::RecordThread::threadLoop()
4272{
4273 AudioBufferProvider::Buffer buffer;
4274 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004275 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276
Eric Laurent44d98482010-09-30 16:12:31 -07004277 nsecs_t lastWarning = 0;
4278
Eric Laurentfeb0db62011-07-22 09:04:31 -07004279 acquireWakeLock();
4280
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 // start recording
4282 while (!exitPending()) {
4283
4284 processConfigEvents();
4285
4286 { // scope for mLock
4287 Mutex::Autolock _l(mLock);
4288 checkForNewParameters_l();
4289 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4290 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004291 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 mStandby = true;
4293 }
4294
4295 if (exitPending()) break;
4296
Eric Laurentfeb0db62011-07-22 09:04:31 -07004297 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004298 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 // go to sleep
4300 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004301 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004302 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 continue;
4304 }
4305 if (mActiveTrack != 0) {
4306 if (mActiveTrack->mState == TrackBase::PAUSING) {
4307 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004308 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 mStandby = true;
4310 }
4311 mActiveTrack.clear();
4312 mStartStopCond.broadcast();
4313 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4314 if (mReqChannelCount != mActiveTrack->channelCount()) {
4315 mActiveTrack.clear();
4316 mStartStopCond.broadcast();
4317 } else if (mBytesRead != 0) {
4318 // record start succeeds only if first read from audio input
4319 // succeeds
4320 if (mBytesRead > 0) {
4321 mActiveTrack->mState = TrackBase::ACTIVE;
4322 } else {
4323 mActiveTrack.clear();
4324 }
4325 mStartStopCond.broadcast();
4326 }
4327 mStandby = false;
4328 }
4329 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004330 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 }
4332
4333 if (mActiveTrack != 0) {
4334 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4335 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004336 unlockEffectChains(effectChains);
4337 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 continue;
4339 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004340 for (size_t i = 0; i < effectChains.size(); i ++) {
4341 effectChains[i]->process_l();
4342 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004343
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004345 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004347 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 // no resampling
4349 while (framesOut) {
4350 size_t framesIn = mFrameCount - mRsmpInIndex;
4351 if (framesIn) {
4352 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4353 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4354 if (framesIn > framesOut)
4355 framesIn = framesOut;
4356 mRsmpInIndex += framesIn;
4357 framesOut -= framesIn;
4358 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004359 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 memcpy(dst, src, framesIn * mFrameSize);
4361 } else {
4362 int16_t *src16 = (int16_t *)src;
4363 int16_t *dst16 = (int16_t *)dst;
4364 if (mChannelCount == 1) {
4365 while (framesIn--) {
4366 *dst16++ = *src16;
4367 *dst16++ = *src16++;
4368 }
4369 } else {
4370 while (framesIn--) {
4371 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4372 src16 += 2;
4373 }
4374 }
4375 }
4376 }
4377 if (framesOut && mFrameCount == mRsmpInIndex) {
4378 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004379 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004380 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 framesOut = 0;
4382 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004383 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 mRsmpInIndex = 0;
4385 }
4386 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004387 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4389 // Force input into standby so that it tries to
4390 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004391 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004392 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 }
4394 mRsmpInIndex = mFrameCount;
4395 framesOut = 0;
4396 buffer.frameCount = 0;
4397 }
4398 }
4399 }
4400 } else {
4401 // resampling
4402
4403 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4404 // alter output frame count as if we were expecting stereo samples
4405 if (mChannelCount == 1 && mReqChannelCount == 1) {
4406 framesOut >>= 1;
4407 }
4408 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4409 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4410 // are 32 bit aligned which should be always true.
4411 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004412 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 // the resampler always outputs stereo samples: do post stereo to mono conversion
4414 int16_t *src = (int16_t *)mRsmpOutBuffer;
4415 int16_t *dst = buffer.i16;
4416 while (framesOut--) {
4417 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4418 src += 2;
4419 }
4420 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004421 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423
4424 }
4425 mActiveTrack->releaseBuffer(&buffer);
4426 mActiveTrack->overflow();
4427 }
4428 // client isn't retrieving buffers fast enough
4429 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004430 if (!mActiveTrack->setOverflow()) {
4431 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004432 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004433 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004434 lastWarning = now;
4435 }
4436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 // Release the processor for a while before asking for a new buffer.
4438 // This will give the application more chance to read from the buffer and
4439 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004440 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 }
4442 }
Eric Laurentec437d82011-07-26 20:54:46 -07004443 // enable changes in effect chain
4444 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004445 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446 }
4447
4448 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004449 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450 }
4451 mActiveTrack.clear();
4452
4453 mStartStopCond.broadcast();
4454
Eric Laurentfeb0db62011-07-22 09:04:31 -07004455 releaseWakeLock();
4456
Steve Block3856b092011-10-20 11:56:00 +01004457 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 return false;
4459}
4460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004461
4462sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4463 const sp<AudioFlinger::Client>& client,
4464 uint32_t sampleRate,
4465 int format,
4466 int channelMask,
4467 int frameCount,
4468 uint32_t flags,
4469 int sessionId,
4470 status_t *status)
4471{
4472 sp<RecordTrack> track;
4473 status_t lStatus;
4474
4475 lStatus = initCheck();
4476 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004477 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004478 goto Exit;
4479 }
4480
4481 { // scope for mLock
4482 Mutex::Autolock _l(mLock);
4483
4484 track = new RecordTrack(this, client, sampleRate,
4485 format, channelMask, frameCount, flags, sessionId);
4486
4487 if (track->getCblk() == NULL) {
4488 lStatus = NO_MEMORY;
4489 goto Exit;
4490 }
4491
4492 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004493 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4494 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004495 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004496 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4497 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004498 }
4499 lStatus = NO_ERROR;
4500
4501Exit:
4502 if (status) {
4503 *status = lStatus;
4504 }
4505 return track;
4506}
4507
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4509{
Steve Block3856b092011-10-20 11:56:00 +01004510 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 sp <ThreadBase> strongMe = this;
4512 status_t status = NO_ERROR;
4513 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004514 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 if (mActiveTrack != 0) {
4516 if (recordTrack != mActiveTrack.get()) {
4517 status = -EBUSY;
4518 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4519 mActiveTrack->mState = TrackBase::ACTIVE;
4520 }
4521 return status;
4522 }
4523
4524 recordTrack->mState = TrackBase::IDLE;
4525 mActiveTrack = recordTrack;
4526 mLock.unlock();
4527 status_t status = AudioSystem::startInput(mId);
4528 mLock.lock();
4529 if (status != NO_ERROR) {
4530 mActiveTrack.clear();
4531 return status;
4532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mRsmpInIndex = mFrameCount;
4534 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004535 if (mResampler != NULL) {
4536 mResampler->reset();
4537 }
4538 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004540 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 mWaitWorkCV.signal();
4542 // do not wait for mStartStopCond if exiting
4543 if (mExiting) {
4544 mActiveTrack.clear();
4545 status = INVALID_OPERATION;
4546 goto startError;
4547 }
4548 mStartStopCond.wait(mLock);
4549 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 status = BAD_VALUE;
4552 goto startError;
4553 }
Steve Block3856b092011-10-20 11:56:00 +01004554 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 return status;
4556 }
4557startError:
4558 AudioSystem::stopInput(mId);
4559 return status;
4560}
4561
4562void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004563 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 sp <ThreadBase> strongMe = this;
4565 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004566 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4568 mActiveTrack->mState = TrackBase::PAUSING;
4569 // do not wait for mStartStopCond if exiting
4570 if (mExiting) {
4571 return;
4572 }
4573 mStartStopCond.wait(mLock);
4574 // if we have been restarted, recordTrack == mActiveTrack.get() here
4575 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4576 mLock.unlock();
4577 AudioSystem::stopInput(mId);
4578 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004579 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 }
4581 }
4582 }
4583}
4584
4585status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4586{
4587 const size_t SIZE = 256;
4588 char buffer[SIZE];
4589 String8 result;
4590 pid_t pid = 0;
4591
4592 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4593 result.append(buffer);
4594
4595 if (mActiveTrack != 0) {
4596 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004597 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004598 mActiveTrack->dump(buffer, SIZE);
4599 result.append(buffer);
4600
4601 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4602 result.append(buffer);
4603 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4604 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004605 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 result.append(buffer);
4607 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4608 result.append(buffer);
4609 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4610 result.append(buffer);
4611
4612
4613 } else {
4614 result.append("No record client\n");
4615 }
4616 write(fd, result.string(), result.size());
4617
4618 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004619 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620
4621 return NO_ERROR;
4622}
4623
4624status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4625{
4626 size_t framesReq = buffer->frameCount;
4627 size_t framesReady = mFrameCount - mRsmpInIndex;
4628 int channelCount;
4629
4630 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004631 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004632 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004633 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4635 // Force input into standby so that it tries to
4636 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004637 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004638 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004640 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004641 buffer->frameCount = 0;
4642 return NOT_ENOUGH_DATA;
4643 }
4644 mRsmpInIndex = 0;
4645 framesReady = mFrameCount;
4646 }
4647
4648 if (framesReq > framesReady) {
4649 framesReq = framesReady;
4650 }
4651
4652 if (mChannelCount == 1 && mReqChannelCount == 2) {
4653 channelCount = 1;
4654 } else {
4655 channelCount = 2;
4656 }
4657 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4658 buffer->frameCount = framesReq;
4659 return NO_ERROR;
4660}
4661
4662void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4663{
4664 mRsmpInIndex += buffer->frameCount;
4665 buffer->frameCount = 0;
4666}
4667
4668bool AudioFlinger::RecordThread::checkForNewParameters_l()
4669{
4670 bool reconfig = false;
4671
4672 while (!mNewParameters.isEmpty()) {
4673 status_t status = NO_ERROR;
4674 String8 keyValuePair = mNewParameters[0];
4675 AudioParameter param = AudioParameter(keyValuePair);
4676 int value;
4677 int reqFormat = mFormat;
4678 int reqSamplingRate = mReqSampleRate;
4679 int reqChannelCount = mReqChannelCount;
4680
4681 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4682 reqSamplingRate = value;
4683 reconfig = true;
4684 }
4685 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4686 reqFormat = value;
4687 reconfig = true;
4688 }
4689 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004690 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 reconfig = true;
4692 }
4693 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4694 // do not accept frame count changes if tracks are open as the track buffer
4695 // size depends on frame count and correct behavior would not be garantied
4696 // if frame count is changed after track creation
4697 if (mActiveTrack != 0) {
4698 status = INVALID_OPERATION;
4699 } else {
4700 reconfig = true;
4701 }
4702 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004703 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4704 // forward device change to effects that have requested to be
4705 // aware of attached audio device.
4706 for (size_t i = 0; i < mEffectChains.size(); i++) {
4707 mEffectChains[i]->setDevice_l(value);
4708 }
4709 // store input device and output device but do not forward output device to audio HAL.
4710 // Note that status is ignored by the caller for output device
4711 // (see AudioFlinger::setParameters()
4712 if (value & AUDIO_DEVICE_OUT_ALL) {
4713 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4714 status = BAD_VALUE;
4715 } else {
4716 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004717 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4718 if (mTrack != NULL) {
4719 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004720 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004721 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4722 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4723 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004724 }
4725 mDevice |= (uint32_t)value;
4726 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004728 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004730 mInput->stream->common.standby(&mInput->stream->common);
4731 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732 }
4733 if (reconfig) {
4734 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004735 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004736 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004737 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4738 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004739 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740 status = NO_ERROR;
4741 }
4742 if (status == NO_ERROR) {
4743 readInputParameters();
4744 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4745 }
4746 }
4747 }
4748
4749 mNewParameters.removeAt(0);
4750
4751 mParamStatus = status;
4752 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004753 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4754 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004755 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004756 }
4757 return reconfig;
4758}
4759
4760String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4761{
Dima Zavinfce7a472011-04-19 22:30:36 -07004762 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004763 String8 out_s8 = String8();
4764
4765 Mutex::Autolock _l(mLock);
4766 if (initCheck() != NO_ERROR) {
4767 return out_s8;
4768 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004769
Dima Zavin799a70e2011-04-18 16:57:27 -07004770 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004771 out_s8 = String8(s);
4772 free(s);
4773 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774}
4775
4776void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4777 AudioSystem::OutputDescriptor desc;
4778 void *param2 = 0;
4779
4780 switch (event) {
4781 case AudioSystem::INPUT_OPENED:
4782 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004783 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004784 desc.samplingRate = mSampleRate;
4785 desc.format = mFormat;
4786 desc.frameCount = mFrameCount;
4787 desc.latency = 0;
4788 param2 = &desc;
4789 break;
4790
4791 case AudioSystem::INPUT_CLOSED:
4792 default:
4793 break;
4794 }
4795 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4796}
4797
4798void AudioFlinger::RecordThread::readInputParameters()
4799{
4800 if (mRsmpInBuffer) delete mRsmpInBuffer;
4801 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4802 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004803 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004804
Dima Zavin799a70e2011-04-18 16:57:27 -07004805 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004806 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4807 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004808 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4809 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4810 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811 mFrameCount = mInputBytes / mFrameSize;
4812 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4813
4814 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4815 {
4816 int channelCount;
4817 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4818 // stereo to mono post process as the resampler always outputs stereo.
4819 if (mChannelCount == 1 && mReqChannelCount == 2) {
4820 channelCount = 1;
4821 } else {
4822 channelCount = 2;
4823 }
4824 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4825 mResampler->setSampleRate(mSampleRate);
4826 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4827 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4828
4829 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4830 if (mChannelCount == 1 && mReqChannelCount == 1) {
4831 mFrameCount >>= 1;
4832 }
4833
4834 }
4835 mRsmpInIndex = mFrameCount;
4836}
4837
4838unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4839{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004840 Mutex::Autolock _l(mLock);
4841 if (initCheck() != NO_ERROR) {
4842 return 0;
4843 }
4844
Dima Zavin799a70e2011-04-18 16:57:27 -07004845 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004846}
4847
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004848uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4849{
4850 Mutex::Autolock _l(mLock);
4851 uint32_t result = 0;
4852 if (getEffectChain_l(sessionId) != 0) {
4853 result = EFFECT_SESSION;
4854 }
4855
4856 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4857 result |= TRACK_SESSION;
4858 }
4859
4860 return result;
4861}
4862
Eric Laurent59bd0da2011-08-01 09:52:20 -07004863AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4864{
4865 Mutex::Autolock _l(mLock);
4866 return mTrack;
4867}
4868
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004869AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4870{
4871 Mutex::Autolock _l(mLock);
4872 return mInput;
4873}
4874
4875AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4876{
4877 Mutex::Autolock _l(mLock);
4878 AudioStreamIn *input = mInput;
4879 mInput = NULL;
4880 return input;
4881}
4882
4883// this method must always be called either with ThreadBase mLock held or inside the thread loop
4884audio_stream_t* AudioFlinger::RecordThread::stream()
4885{
4886 if (mInput == NULL) {
4887 return NULL;
4888 }
4889 return &mInput->stream->common;
4890}
4891
4892
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893// ----------------------------------------------------------------------------
4894
4895int AudioFlinger::openOutput(uint32_t *pDevices,
4896 uint32_t *pSamplingRate,
4897 uint32_t *pFormat,
4898 uint32_t *pChannels,
4899 uint32_t *pLatencyMs,
4900 uint32_t flags)
4901{
4902 status_t status;
4903 PlaybackThread *thread = NULL;
4904 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4905 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4906 uint32_t format = pFormat ? *pFormat : 0;
4907 uint32_t channels = pChannels ? *pChannels : 0;
4908 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004909 audio_stream_out_t *outStream;
4910 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004911
Steve Block3856b092011-10-20 11:56:00 +01004912 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 pDevices ? *pDevices : 0,
4914 samplingRate,
4915 format,
4916 channels,
4917 flags);
4918
4919 if (pDevices == NULL || *pDevices == 0) {
4920 return 0;
4921 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004922
Mathias Agopian65ab4712010-07-14 17:59:35 -07004923 Mutex::Autolock _l(mLock);
4924
Dima Zavin799a70e2011-04-18 16:57:27 -07004925 outHwDev = findSuitableHwDev_l(*pDevices);
4926 if (outHwDev == NULL)
4927 return 0;
4928
4929 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4930 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004931 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004932 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 samplingRate,
4934 format,
4935 channels,
4936 status);
4937
4938 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004939 if (outStream != NULL) {
4940 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004941 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004942
Dima Zavinfce7a472011-04-19 22:30:36 -07004943 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4944 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4945 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004946 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004947 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004948 } else {
4949 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004950 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 }
4952 mPlaybackThreads.add(id, thread);
4953
4954 if (pSamplingRate) *pSamplingRate = samplingRate;
4955 if (pFormat) *pFormat = format;
4956 if (pChannels) *pChannels = channels;
4957 if (pLatencyMs) *pLatencyMs = thread->latency();
4958
4959 // notify client processes of the new output creation
4960 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4961 return id;
4962 }
4963
4964 return 0;
4965}
4966
4967int AudioFlinger::openDuplicateOutput(int output1, int output2)
4968{
4969 Mutex::Autolock _l(mLock);
4970 MixerThread *thread1 = checkMixerThread_l(output1);
4971 MixerThread *thread2 = checkMixerThread_l(output2);
4972
4973 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004974 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004975 return 0;
4976 }
4977
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004978 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4980 thread->addOutputTrack(thread2);
4981 mPlaybackThreads.add(id, thread);
4982 // notify client processes of the new output creation
4983 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4984 return id;
4985}
4986
4987status_t AudioFlinger::closeOutput(int output)
4988{
4989 // keep strong reference on the playback thread so that
4990 // it is not destroyed while exit() is executed
4991 sp <PlaybackThread> thread;
4992 {
4993 Mutex::Autolock _l(mLock);
4994 thread = checkPlaybackThread_l(output);
4995 if (thread == NULL) {
4996 return BAD_VALUE;
4997 }
4998
Steve Block3856b092011-10-20 11:56:00 +01004999 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005001 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005003 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5005 dupThread->removeOutputTrack((MixerThread *)thread.get());
5006 }
5007 }
5008 }
5009 void *param2 = 0;
5010 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5011 mPlaybackThreads.removeItem(output);
5012 }
5013 thread->exit();
5014
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005015 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005016 AudioStreamOut *out = thread->clearOutput();
5017 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005018 out->hwDev->close_output_stream(out->hwDev, out->stream);
5019 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005020 }
5021 return NO_ERROR;
5022}
5023
5024status_t AudioFlinger::suspendOutput(int output)
5025{
5026 Mutex::Autolock _l(mLock);
5027 PlaybackThread *thread = checkPlaybackThread_l(output);
5028
5029 if (thread == NULL) {
5030 return BAD_VALUE;
5031 }
5032
Steve Block3856b092011-10-20 11:56:00 +01005033 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 thread->suspend();
5035
5036 return NO_ERROR;
5037}
5038
5039status_t AudioFlinger::restoreOutput(int output)
5040{
5041 Mutex::Autolock _l(mLock);
5042 PlaybackThread *thread = checkPlaybackThread_l(output);
5043
5044 if (thread == NULL) {
5045 return BAD_VALUE;
5046 }
5047
Steve Block3856b092011-10-20 11:56:00 +01005048 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049
5050 thread->restore();
5051
5052 return NO_ERROR;
5053}
5054
5055int AudioFlinger::openInput(uint32_t *pDevices,
5056 uint32_t *pSamplingRate,
5057 uint32_t *pFormat,
5058 uint32_t *pChannels,
5059 uint32_t acoustics)
5060{
5061 status_t status;
5062 RecordThread *thread = NULL;
5063 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5064 uint32_t format = pFormat ? *pFormat : 0;
5065 uint32_t channels = pChannels ? *pChannels : 0;
5066 uint32_t reqSamplingRate = samplingRate;
5067 uint32_t reqFormat = format;
5068 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005069 audio_stream_in_t *inStream;
5070 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005071
5072 if (pDevices == NULL || *pDevices == 0) {
5073 return 0;
5074 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005075
Mathias Agopian65ab4712010-07-14 17:59:35 -07005076 Mutex::Autolock _l(mLock);
5077
Dima Zavin799a70e2011-04-18 16:57:27 -07005078 inHwDev = findSuitableHwDev_l(*pDevices);
5079 if (inHwDev == NULL)
5080 return 0;
5081
5082 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5083 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005084 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005085 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005086 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005087 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 samplingRate,
5089 format,
5090 channels,
5091 acoustics,
5092 status);
5093
5094 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5095 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5096 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005097 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005098 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005099 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005100 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005101 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005102 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5103 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005104 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005105 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 }
5107
Dima Zavin799a70e2011-04-18 16:57:27 -07005108 if (inStream != NULL) {
5109 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5110
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005111 int id = nextUniqueId();
5112 // Start record thread
5113 // RecorThread require both input and output device indication to forward to audio
5114 // pre processing modules
5115 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5116 thread = new RecordThread(this,
5117 input,
5118 reqSamplingRate,
5119 reqChannels,
5120 id,
5121 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005122 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005123 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005124 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5125 if (pFormat) *pFormat = format;
5126 if (pChannels) *pChannels = reqChannels;
5127
Dima Zavin799a70e2011-04-18 16:57:27 -07005128 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129
5130 // notify client processes of the new input creation
5131 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5132 return id;
5133 }
5134
5135 return 0;
5136}
5137
5138status_t AudioFlinger::closeInput(int input)
5139{
5140 // keep strong reference on the record thread so that
5141 // it is not destroyed while exit() is executed
5142 sp <RecordThread> thread;
5143 {
5144 Mutex::Autolock _l(mLock);
5145 thread = checkRecordThread_l(input);
5146 if (thread == NULL) {
5147 return BAD_VALUE;
5148 }
5149
Steve Block3856b092011-10-20 11:56:00 +01005150 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 void *param2 = 0;
5152 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5153 mRecordThreads.removeItem(input);
5154 }
5155 thread->exit();
5156
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005157 AudioStreamIn *in = thread->clearInput();
5158 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005159 in->hwDev->close_input_stream(in->hwDev, in->stream);
5160 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161
5162 return NO_ERROR;
5163}
5164
5165status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5166{
5167 Mutex::Autolock _l(mLock);
5168 MixerThread *dstThread = checkMixerThread_l(output);
5169 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005170 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 return BAD_VALUE;
5172 }
5173
Steve Block3856b092011-10-20 11:56:00 +01005174 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5176
Eric Laurent9f6530f2011-08-30 10:18:54 -07005177 dstThread->setStreamValid(stream, true);
5178
Mathias Agopian65ab4712010-07-14 17:59:35 -07005179 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5180 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5181 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005182 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005184 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005185 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 }
Eric Laurentde070132010-07-13 04:45:46 -07005187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188
5189 return NO_ERROR;
5190}
5191
5192
5193int AudioFlinger::newAudioSessionId()
5194{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005195 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196}
5197
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005198void AudioFlinger::acquireAudioSessionId(int audioSession)
5199{
5200 Mutex::Autolock _l(mLock);
5201 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005202 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005203 int num = mAudioSessionRefs.size();
5204 for (int i = 0; i< num; i++) {
5205 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5206 if (ref->sessionid == audioSession && ref->pid == caller) {
5207 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005208 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005209 return;
5210 }
5211 }
5212 AudioSessionRef *ref = new AudioSessionRef();
5213 ref->sessionid = audioSession;
5214 ref->pid = caller;
5215 ref->cnt = 1;
5216 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005217 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005218}
5219
5220void AudioFlinger::releaseAudioSessionId(int audioSession)
5221{
5222 Mutex::Autolock _l(mLock);
5223 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005224 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005225 int num = mAudioSessionRefs.size();
5226 for (int i = 0; i< num; i++) {
5227 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5228 if (ref->sessionid == audioSession && ref->pid == caller) {
5229 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005230 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005231 if (ref->cnt == 0) {
5232 mAudioSessionRefs.removeAt(i);
5233 delete ref;
5234 purgeStaleEffects_l();
5235 }
5236 return;
5237 }
5238 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005239 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005240}
5241
5242void AudioFlinger::purgeStaleEffects_l() {
5243
Steve Block3856b092011-10-20 11:56:00 +01005244 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005245
5246 Vector< sp<EffectChain> > chains;
5247
5248 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5249 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5250 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5251 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005252 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5253 chains.push(ec);
5254 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005255 }
5256 }
5257 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5258 sp<RecordThread> t = mRecordThreads.valueAt(i);
5259 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5260 sp<EffectChain> ec = t->mEffectChains[j];
5261 chains.push(ec);
5262 }
5263 }
5264
5265 for (size_t i = 0; i < chains.size(); i++) {
5266 sp<EffectChain> ec = chains[i];
5267 int sessionid = ec->sessionId();
5268 sp<ThreadBase> t = ec->mThread.promote();
5269 if (t == 0) {
5270 continue;
5271 }
5272 size_t numsessionrefs = mAudioSessionRefs.size();
5273 bool found = false;
5274 for (size_t k = 0; k < numsessionrefs; k++) {
5275 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5276 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005277 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005278 sessionid, ref->pid, ref->cnt);
5279 found = true;
5280 break;
5281 }
5282 }
5283 if (!found) {
5284 // remove all effects from the chain
5285 while (ec->mEffects.size()) {
5286 sp<EffectModule> effect = ec->mEffects[0];
5287 effect->unPin();
5288 Mutex::Autolock _l (t->mLock);
5289 t->removeEffect_l(effect);
5290 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5291 sp<EffectHandle> handle = effect->mHandles[j].promote();
5292 if (handle != 0) {
5293 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005294 if (handle->mHasControl && handle->mEnabled) {
5295 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5296 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005297 }
5298 }
5299 AudioSystem::unregisterEffect(effect->id());
5300 }
5301 }
5302 }
5303 return;
5304}
5305
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5307AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5308{
5309 PlaybackThread *thread = NULL;
5310 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5311 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5312 }
5313 return thread;
5314}
5315
5316// checkMixerThread_l() must be called with AudioFlinger::mLock held
5317AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5318{
5319 PlaybackThread *thread = checkPlaybackThread_l(output);
5320 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005321 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 thread = NULL;
5323 }
5324 }
5325 return (MixerThread *)thread;
5326}
5327
5328// checkRecordThread_l() must be called with AudioFlinger::mLock held
5329AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5330{
5331 RecordThread *thread = NULL;
5332 if (mRecordThreads.indexOfKey(input) >= 0) {
5333 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5334 }
5335 return thread;
5336}
5337
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005338uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005340 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005341}
5342
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005343AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5344{
5345 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5346 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005347 AudioStreamOut *output = thread->getOutput();
5348 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005349 return thread;
5350 }
5351 }
5352 return NULL;
5353}
5354
5355uint32_t AudioFlinger::primaryOutputDevice_l()
5356{
5357 PlaybackThread *thread = primaryPlaybackThread_l();
5358
5359 if (thread == NULL) {
5360 return 0;
5361 }
5362
5363 return thread->device();
5364}
5365
5366
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367// ----------------------------------------------------------------------------
5368// Effect management
5369// ----------------------------------------------------------------------------
5370
5371
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5373{
5374 Mutex::Autolock _l(mLock);
5375 return EffectQueryNumberEffects(numEffects);
5376}
5377
5378status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5379{
5380 Mutex::Autolock _l(mLock);
5381 return EffectQueryEffect(index, descriptor);
5382}
5383
5384status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5385{
5386 Mutex::Autolock _l(mLock);
5387 return EffectGetDescriptor(pUuid, descriptor);
5388}
5389
5390
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5392 effect_descriptor_t *pDesc,
5393 const sp<IEffectClient>& effectClient,
5394 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005395 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 int sessionId,
5397 status_t *status,
5398 int *id,
5399 int *enabled)
5400{
5401 status_t lStatus = NO_ERROR;
5402 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 effect_descriptor_t desc;
5404 sp<Client> client;
5405 wp<Client> wclient;
5406
Steve Block3856b092011-10-20 11:56:00 +01005407 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005408 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005409
5410 if (pDesc == NULL) {
5411 lStatus = BAD_VALUE;
5412 goto Exit;
5413 }
5414
Eric Laurent84e9a102010-09-23 16:10:16 -07005415 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005416 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005417 lStatus = PERMISSION_DENIED;
5418 goto Exit;
5419 }
5420
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005423 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 lStatus = PERMISSION_DENIED;
5425 goto Exit;
5426 }
5427
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005428 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005429 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005430 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005431 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005432 lStatus = BAD_VALUE;
5433 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005434 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005435 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005436 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005437 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005438 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005439 }
5440 }
5441
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 {
5443 Mutex::Autolock _l(mLock);
5444
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445
5446 if (!EffectIsNullUuid(&pDesc->uuid)) {
5447 // if uuid is specified, request effect descriptor
5448 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5449 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005450 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 goto Exit;
5452 }
5453 } else {
5454 // if uuid is not specified, look for an available implementation
5455 // of the required type in effect factory
5456 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005457 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005458 lStatus = BAD_VALUE;
5459 goto Exit;
5460 }
5461 uint32_t numEffects = 0;
5462 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005463 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 bool found = false;
5465
5466 lStatus = EffectQueryNumberEffects(&numEffects);
5467 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005468 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 goto Exit;
5470 }
5471 for (uint32_t i = 0; i < numEffects; i++) {
5472 lStatus = EffectQueryEffect(i, &desc);
5473 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005474 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 continue;
5476 }
5477 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5478 // If matching type found save effect descriptor. If the session is
5479 // 0 and the effect is not auxiliary, continue enumeration in case
5480 // an auxiliary version of this effect type is available
5481 found = true;
5482 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005483 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5485 break;
5486 }
5487 }
5488 }
5489 if (!found) {
5490 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005491 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 goto Exit;
5493 }
5494 // For same effect type, chose auxiliary version over insert version if
5495 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005496 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5498 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5499 }
5500 }
5501
5502 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005503 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5505 lStatus = INVALID_OPERATION;
5506 goto Exit;
5507 }
5508
Eric Laurent59255e42011-07-27 19:49:51 -07005509 // check recording permission for visualizer
5510 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5511 !recordingAllowed()) {
5512 lStatus = PERMISSION_DENIED;
5513 goto Exit;
5514 }
5515
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 // return effect descriptor
5517 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5518
5519 // If output is not specified try to find a matching audio session ID in one of the
5520 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005521 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5522 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005523 // Note: io is never 0 when creating an effect on an input
5524 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005525 // look for the thread where the specified audio session is present
5526 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5527 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005528 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005529 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005530 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005532 if (io == 0) {
5533 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5534 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5535 io = mRecordThreads.keyAt(i);
5536 break;
5537 }
5538 }
5539 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005540 // If no output thread contains the requested session ID, default to
5541 // first output. The effect chain will be moved to the correct output
5542 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005543 if (io == 0 && mPlaybackThreads.size()) {
5544 io = mPlaybackThreads.keyAt(0);
5545 }
Steve Block3856b092011-10-20 11:56:00 +01005546 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005547 }
5548 ThreadBase *thread = checkRecordThread_l(io);
5549 if (thread == NULL) {
5550 thread = checkPlaybackThread_l(io);
5551 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005552 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005553 lStatus = BAD_VALUE;
5554 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005557
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 wclient = mClients.valueFor(pid);
5559
5560 if (wclient != NULL) {
5561 client = wclient.promote();
5562 } else {
5563 client = new Client(this, pid);
5564 mClients.add(pid, client);
5565 }
5566
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005567 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005568 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5569 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570 if (handle != 0 && id != NULL) {
5571 *id = handle->id();
5572 }
5573 }
5574
5575Exit:
5576 if(status) {
5577 *status = lStatus;
5578 }
5579 return handle;
5580}
5581
Eric Laurent59255e42011-07-27 19:49:51 -07005582status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005583{
Steve Block3856b092011-10-20 11:56:00 +01005584 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005585 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005586 Mutex::Autolock _l(mLock);
5587 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005588 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005589 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 }
Eric Laurentde070132010-07-13 04:45:46 -07005591 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5592 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005593 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005594 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 }
Eric Laurentde070132010-07-13 04:45:46 -07005596 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5597 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005598 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005599 return BAD_VALUE;
5600 }
5601
5602 Mutex::Autolock _dl(dstThread->mLock);
5603 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005604 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005605
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 return NO_ERROR;
5607}
5608
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005609// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005610status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005611 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005612 AudioFlinger::PlaybackThread *dstThread,
5613 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005614{
Steve Block3856b092011-10-20 11:56:00 +01005615 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005616 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005617
Eric Laurent59255e42011-07-27 19:49:51 -07005618 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005619 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005620 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005621 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005622 return INVALID_OPERATION;
5623 }
5624
Eric Laurent39e94f82010-07-28 01:32:47 -07005625 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005626 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005627 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005628 // removed.
5629 srcThread->removeEffectChain_l(chain);
5630
5631 // transfer all effects one by one so that new effect chain is created on new thread with
5632 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005633 int dstOutput = dstThread->id();
5634 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005635 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005636 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5637 while (effect != 0) {
5638 srcThread->removeEffect_l(effect);
5639 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005640 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5641 if (effect->state() == EffectModule::ACTIVE ||
5642 effect->state() == EffectModule::STOPPING) {
5643 effect->start();
5644 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005645 // if the move request is not received from audio policy manager, the effect must be
5646 // re-registered with the new strategy and output
5647 if (dstChain == 0) {
5648 dstChain = effect->chain().promote();
5649 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005650 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005651 srcThread->addEffect_l(effect);
5652 return NO_INIT;
5653 }
5654 strategy = dstChain->strategy();
5655 }
5656 if (reRegister) {
5657 AudioSystem::unregisterEffect(effect->id());
5658 AudioSystem::registerEffect(&effect->desc(),
5659 dstOutput,
5660 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005661 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005662 effect->id());
5663 }
Eric Laurentde070132010-07-13 04:45:46 -07005664 effect = chain->getEffectFromId_l(0);
5665 }
5666
5667 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668}
5669
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005670
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005672sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673 const sp<AudioFlinger::Client>& client,
5674 const sp<IEffectClient>& effectClient,
5675 int32_t priority,
5676 int sessionId,
5677 effect_descriptor_t *desc,
5678 int *enabled,
5679 status_t *status
5680 )
5681{
5682 sp<EffectModule> effect;
5683 sp<EffectHandle> handle;
5684 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005686 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005687 bool effectCreated = false;
5688 bool effectRegistered = false;
5689
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005690 lStatus = initCheck();
5691 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005692 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 goto Exit;
5694 }
5695
5696 // Do not allow effects with session ID 0 on direct output or duplicating threads
5697 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005698 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005699 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005700 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 lStatus = BAD_VALUE;
5702 goto Exit;
5703 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005704 // Only Pre processor effects are allowed on input threads and only on input threads
5705 if ((mType == RECORD &&
5706 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5707 (mType != RECORD &&
5708 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005709 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005710 desc->name, desc->flags, mType);
5711 lStatus = BAD_VALUE;
5712 goto Exit;
5713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714
Steve Block3856b092011-10-20 11:56:00 +01005715 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 { // scope for mLock
5718 Mutex::Autolock _l(mLock);
5719
5720 // check for existing effect chain with the requested audio session
5721 chain = getEffectChain_l(sessionId);
5722 if (chain == 0) {
5723 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005724 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725 chain = new EffectChain(this, sessionId);
5726 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005727 chain->setStrategy(getStrategyForSession_l(sessionId));
5728 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005730 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731 }
5732
Steve Block3856b092011-10-20 11:56:00 +01005733 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734
5735 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005736 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005738 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 if (lStatus != NO_ERROR) {
5740 goto Exit;
5741 }
5742 effectRegistered = true;
5743 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005744 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 lStatus = effect->status();
5746 if (lStatus != NO_ERROR) {
5747 goto Exit;
5748 }
Eric Laurentcab11242010-07-15 12:50:15 -07005749 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 if (lStatus != NO_ERROR) {
5751 goto Exit;
5752 }
5753 effectCreated = true;
5754
5755 effect->setDevice(mDevice);
5756 effect->setMode(mAudioFlinger->getMode());
5757 }
5758 // create effect handle and connect it to effect module
5759 handle = new EffectHandle(effect, client, effectClient, priority);
5760 lStatus = effect->addHandle(handle);
5761 if (enabled) {
5762 *enabled = (int)effect->isEnabled();
5763 }
5764 }
5765
5766Exit:
5767 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005768 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005770 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 }
5772 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005773 AudioSystem::unregisterEffect(effect->id());
5774 }
5775 if (chainCreated) {
5776 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 }
5778 handle.clear();
5779 }
5780
5781 if(status) {
5782 *status = lStatus;
5783 }
5784 return handle;
5785}
5786
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005787sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5788{
5789 sp<EffectModule> effect;
5790
5791 sp<EffectChain> chain = getEffectChain_l(sessionId);
5792 if (chain != 0) {
5793 effect = chain->getEffectFromId_l(effectId);
5794 }
5795 return effect;
5796}
5797
Eric Laurentde070132010-07-13 04:45:46 -07005798// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5799// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005800status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005801{
5802 // check for existing effect chain with the requested audio session
5803 int sessionId = effect->sessionId();
5804 sp<EffectChain> chain = getEffectChain_l(sessionId);
5805 bool chainCreated = false;
5806
5807 if (chain == 0) {
5808 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005809 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005810 chain = new EffectChain(this, sessionId);
5811 addEffectChain_l(chain);
5812 chain->setStrategy(getStrategyForSession_l(sessionId));
5813 chainCreated = true;
5814 }
Steve Block3856b092011-10-20 11:56:00 +01005815 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005816
5817 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005818 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005819 this, effect->desc().name, chain.get());
5820 return BAD_VALUE;
5821 }
5822
5823 status_t status = chain->addEffect_l(effect);
5824 if (status != NO_ERROR) {
5825 if (chainCreated) {
5826 removeEffectChain_l(chain);
5827 }
5828 return status;
5829 }
5830
5831 effect->setDevice(mDevice);
5832 effect->setMode(mAudioFlinger->getMode());
5833 return NO_ERROR;
5834}
5835
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005836void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005837
Steve Block3856b092011-10-20 11:56:00 +01005838 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005839 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005840 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5841 detachAuxEffect_l(effect->id());
5842 }
5843
5844 sp<EffectChain> chain = effect->chain().promote();
5845 if (chain != 0) {
5846 // remove effect chain if removing last effect
5847 if (chain->removeEffect_l(effect) == 0) {
5848 removeEffectChain_l(chain);
5849 }
5850 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005851 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005852 }
5853}
5854
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005855void AudioFlinger::ThreadBase::lockEffectChains_l(
5856 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5857{
5858 effectChains = mEffectChains;
5859 for (size_t i = 0; i < mEffectChains.size(); i++) {
5860 mEffectChains[i]->lock();
5861 }
5862}
5863
5864void AudioFlinger::ThreadBase::unlockEffectChains(
5865 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5866{
5867 for (size_t i = 0; i < effectChains.size(); i++) {
5868 effectChains[i]->unlock();
5869 }
5870}
5871
5872sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5873{
5874 Mutex::Autolock _l(mLock);
5875 return getEffectChain_l(sessionId);
5876}
5877
5878sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5879{
5880 sp<EffectChain> chain;
5881
5882 size_t size = mEffectChains.size();
5883 for (size_t i = 0; i < size; i++) {
5884 if (mEffectChains[i]->sessionId() == sessionId) {
5885 chain = mEffectChains[i];
5886 break;
5887 }
5888 }
5889 return chain;
5890}
5891
5892void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5893{
5894 Mutex::Autolock _l(mLock);
5895 size_t size = mEffectChains.size();
5896 for (size_t i = 0; i < size; i++) {
5897 mEffectChains[i]->setMode_l(mode);
5898 }
5899}
5900
5901void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005902 const wp<EffectHandle>& handle,
5903 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005904
Mathias Agopian65ab4712010-07-14 17:59:35 -07005905 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 // delete the effect module if removing last handle on it
5908 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005909 if (!effect->isPinned() || unpiniflast) {
5910 removeEffect_l(effect);
5911 AudioSystem::unregisterEffect(effect->id());
5912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913 }
5914}
5915
5916status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5917{
5918 int session = chain->sessionId();
5919 int16_t *buffer = mMixBuffer;
5920 bool ownsBuffer = false;
5921
Steve Block3856b092011-10-20 11:56:00 +01005922 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 if (session > 0) {
5924 // Only one effect chain can be present in direct output thread and it uses
5925 // the mix buffer as input
5926 if (mType != DIRECT) {
5927 size_t numSamples = mFrameCount * mChannelCount;
5928 buffer = new int16_t[numSamples];
5929 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005930 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931 ownsBuffer = true;
5932 }
5933
5934 // Attach all tracks with same session ID to this chain.
5935 for (size_t i = 0; i < mTracks.size(); ++i) {
5936 sp<Track> track = mTracks[i];
5937 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005938 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005939 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005940 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941 }
5942 }
5943
5944 // indicate all active tracks in the chain
5945 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5946 sp<Track> track = mActiveTracks[i].promote();
5947 if (track == 0) continue;
5948 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005949 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005950 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 }
5952 }
5953 }
5954
5955 chain->setInBuffer(buffer, ownsBuffer);
5956 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005957 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005958 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005959 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5960 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005962 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5963 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005964 // Effect chain for other sessions are inserted at beginning of effect
5965 // chains list to be processed before output mix effects. Relative order between other
5966 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 size_t size = mEffectChains.size();
5968 size_t i = 0;
5969 for (i = 0; i < size; i++) {
5970 if (mEffectChains[i]->sessionId() < session) break;
5971 }
5972 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005973 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974
5975 return NO_ERROR;
5976}
5977
5978size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5979{
5980 int session = chain->sessionId();
5981
Steve Block3856b092011-10-20 11:56:00 +01005982 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983
5984 for (size_t i = 0; i < mEffectChains.size(); i++) {
5985 if (chain == mEffectChains[i]) {
5986 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005987 // detach all active tracks from the chain
5988 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5989 sp<Track> track = mActiveTracks[i].promote();
5990 if (track == 0) continue;
5991 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005992 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005993 chain.get(), session);
5994 chain->decActiveTrackCnt();
5995 }
5996 }
5997
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998 // detach all tracks with same session ID from this chain
5999 for (size_t i = 0; i < mTracks.size(); ++i) {
6000 sp<Track> track = mTracks[i];
6001 if (session == track->sessionId()) {
6002 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006003 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006004 }
6005 }
Eric Laurentde070132010-07-13 04:45:46 -07006006 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 }
6008 }
6009 return mEffectChains.size();
6010}
6011
Eric Laurentde070132010-07-13 04:45:46 -07006012status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6013 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014{
6015 Mutex::Autolock _l(mLock);
6016 return attachAuxEffect_l(track, EffectId);
6017}
6018
Eric Laurentde070132010-07-13 04:45:46 -07006019status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6020 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021{
6022 status_t status = NO_ERROR;
6023
6024 if (EffectId == 0) {
6025 track->setAuxBuffer(0, NULL);
6026 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006027 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6028 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 if (effect != 0) {
6030 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6031 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6032 } else {
6033 status = INVALID_OPERATION;
6034 }
6035 } else {
6036 status = BAD_VALUE;
6037 }
6038 }
6039 return status;
6040}
6041
6042void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6043{
6044 for (size_t i = 0; i < mTracks.size(); ++i) {
6045 sp<Track> track = mTracks[i];
6046 if (track->auxEffectId() == effectId) {
6047 attachAuxEffect_l(track, 0);
6048 }
6049 }
6050}
6051
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6053{
6054 // only one chain per input thread
6055 if (mEffectChains.size() != 0) {
6056 return INVALID_OPERATION;
6057 }
Steve Block3856b092011-10-20 11:56:00 +01006058 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006059
6060 chain->setInBuffer(NULL);
6061 chain->setOutBuffer(NULL);
6062
Eric Laurent59255e42011-07-27 19:49:51 -07006063 checkSuspendOnAddEffectChain_l(chain);
6064
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006065 mEffectChains.add(chain);
6066
6067 return NO_ERROR;
6068}
6069
6070size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6071{
Steve Block3856b092011-10-20 11:56:00 +01006072 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006073 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006074 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6075 chain.get(), mEffectChains.size(), this);
6076 if (mEffectChains.size() == 1) {
6077 mEffectChains.removeAt(0);
6078 }
6079 return 0;
6080}
6081
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082// ----------------------------------------------------------------------------
6083// EffectModule implementation
6084// ----------------------------------------------------------------------------
6085
6086#undef LOG_TAG
6087#define LOG_TAG "AudioFlinger::EffectModule"
6088
6089AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6090 const wp<AudioFlinger::EffectChain>& chain,
6091 effect_descriptor_t *desc,
6092 int id,
6093 int sessionId)
6094 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006095 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096{
Steve Block3856b092011-10-20 11:56:00 +01006097 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 int lStatus;
6099 sp<ThreadBase> thread = mThread.promote();
6100 if (thread == 0) {
6101 return;
6102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103
6104 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6105
6106 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006107 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108
6109 if (mStatus != NO_ERROR) {
6110 return;
6111 }
6112 lStatus = init();
6113 if (lStatus < 0) {
6114 mStatus = lStatus;
6115 goto Error;
6116 }
6117
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006118 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6119 mPinned = true;
6120 }
Steve Block3856b092011-10-20 11:56:00 +01006121 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 return;
6123Error:
6124 EffectRelease(mEffectInterface);
6125 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006126 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127}
6128
6129AudioFlinger::EffectModule::~EffectModule()
6130{
Steve Block3856b092011-10-20 11:56:00 +01006131 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6134 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6135 sp<ThreadBase> thread = mThread.promote();
6136 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006137 audio_stream_t *stream = thread->stream();
6138 if (stream != NULL) {
6139 stream->remove_audio_effect(stream, mEffectInterface);
6140 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006141 }
6142 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 // release effect engine
6144 EffectRelease(mEffectInterface);
6145 }
6146}
6147
6148status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6149{
6150 status_t status;
6151
6152 Mutex::Autolock _l(mLock);
6153 // First handle in mHandles has highest priority and controls the effect module
6154 int priority = handle->priority();
6155 size_t size = mHandles.size();
6156 sp<EffectHandle> h;
6157 size_t i;
6158 for (i = 0; i < size; i++) {
6159 h = mHandles[i].promote();
6160 if (h == 0) continue;
6161 if (h->priority() <= priority) break;
6162 }
6163 // if inserted in first place, move effect control from previous owner to this handle
6164 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006165 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006167 enabled = h->enabled();
6168 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 }
Eric Laurent59255e42011-07-27 19:49:51 -07006170 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006171 status = NO_ERROR;
6172 } else {
6173 status = ALREADY_EXISTS;
6174 }
Steve Block3856b092011-10-20 11:56:00 +01006175 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006176 mHandles.insertAt(handle, i);
6177 return status;
6178}
6179
6180size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6181{
6182 Mutex::Autolock _l(mLock);
6183 size_t size = mHandles.size();
6184 size_t i;
6185 for (i = 0; i < size; i++) {
6186 if (mHandles[i] == handle) break;
6187 }
6188 if (i == size) {
6189 return size;
6190 }
Steve Block3856b092011-10-20 11:56:00 +01006191 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006192
6193 bool enabled = false;
6194 EffectHandle *hdl = handle.unsafe_get();
6195 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006196 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006197 enabled = hdl->enabled();
6198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 mHandles.removeAt(i);
6200 size = mHandles.size();
6201 // if removed from first place, move effect control from this handle to next in line
6202 if (i == 0 && size != 0) {
6203 sp<EffectHandle> h = mHandles[0].promote();
6204 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006205 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 }
6207 }
6208
Eric Laurentec437d82011-07-26 20:54:46 -07006209 // Prevent calls to process() and other functions on effect interface from now on.
6210 // The effect engine will be released by the destructor when the last strong reference on
6211 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006212 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006213 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006214 }
6215
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 return size;
6217}
6218
Eric Laurent59255e42011-07-27 19:49:51 -07006219sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6220{
6221 Mutex::Autolock _l(mLock);
6222 sp<EffectHandle> handle;
6223 if (mHandles.size() != 0) {
6224 handle = mHandles[0].promote();
6225 }
6226 return handle;
6227}
6228
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006229void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230{
Steve Block3856b092011-10-20 11:56:00 +01006231 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 // keep a strong reference on this EffectModule to avoid calling the
6233 // destructor before we exit
6234 sp<EffectModule> keep(this);
6235 {
6236 sp<ThreadBase> thread = mThread.promote();
6237 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006238 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 }
6240 }
6241}
6242
6243void AudioFlinger::EffectModule::updateState() {
6244 Mutex::Autolock _l(mLock);
6245
6246 switch (mState) {
6247 case RESTART:
6248 reset_l();
6249 // FALL THROUGH
6250
6251 case STARTING:
6252 // clear auxiliary effect input buffer for next accumulation
6253 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6254 memset(mConfig.inputCfg.buffer.raw,
6255 0,
6256 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6257 }
6258 start_l();
6259 mState = ACTIVE;
6260 break;
6261 case STOPPING:
6262 stop_l();
6263 mDisableWaitCnt = mMaxDisableWaitCnt;
6264 mState = STOPPED;
6265 break;
6266 case STOPPED:
6267 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6268 // turn off sequence.
6269 if (--mDisableWaitCnt == 0) {
6270 reset_l();
6271 mState = IDLE;
6272 }
6273 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006274 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 break;
6276 }
6277}
6278
6279void AudioFlinger::EffectModule::process()
6280{
6281 Mutex::Autolock _l(mLock);
6282
Eric Laurentec437d82011-07-26 20:54:46 -07006283 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 mConfig.inputCfg.buffer.raw == NULL ||
6285 mConfig.outputCfg.buffer.raw == NULL) {
6286 return;
6287 }
6288
Eric Laurent8f45bd72010-08-31 13:50:07 -07006289 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6291 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006292 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006294 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 }
6296
6297 // do the actual processing in the effect engine
6298 int ret = (*mEffectInterface)->process(mEffectInterface,
6299 &mConfig.inputCfg.buffer,
6300 &mConfig.outputCfg.buffer);
6301
6302 // force transition to IDLE state when engine is ready
6303 if (mState == STOPPED && ret == -ENODATA) {
6304 mDisableWaitCnt = 1;
6305 }
6306
6307 // clear auxiliary effect input buffer for next accumulation
6308 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006309 memset(mConfig.inputCfg.buffer.raw, 0,
6310 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 }
6312 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006313 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6314 // If an insert effect is idle and input buffer is different from output buffer,
6315 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006317 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006318 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6319 int16_t *in = mConfig.inputCfg.buffer.s16;
6320 int16_t *out = mConfig.outputCfg.buffer.s16;
6321 for (size_t i = 0; i < frameCnt; i++) {
6322 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 }
6325 }
6326}
6327
6328void AudioFlinger::EffectModule::reset_l()
6329{
6330 if (mEffectInterface == NULL) {
6331 return;
6332 }
6333 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6334}
6335
6336status_t AudioFlinger::EffectModule::configure()
6337{
6338 uint32_t channels;
6339 if (mEffectInterface == NULL) {
6340 return NO_INIT;
6341 }
6342
6343 sp<ThreadBase> thread = mThread.promote();
6344 if (thread == 0) {
6345 return DEAD_OBJECT;
6346 }
6347
6348 // TODO: handle configuration of effects replacing track process
6349 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006350 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006352 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353 }
6354
6355 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006356 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 } else {
6358 mConfig.inputCfg.channels = channels;
6359 }
6360 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006361 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6362 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006363 mConfig.inputCfg.samplingRate = thread->sampleRate();
6364 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6365 mConfig.inputCfg.bufferProvider.cookie = NULL;
6366 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6367 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6368 mConfig.outputCfg.bufferProvider.cookie = NULL;
6369 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6370 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6371 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6372 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006373 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006374 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006375 // - in other sessions:
6376 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6377 // other effect: overwrites output buffer: input buffer == output buffer
6378 // Auxiliary effect:
6379 // accumulates in output buffer: input buffer != output buffer
6380 // Therefore: accumulate <=> input buffer != output buffer
6381 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6382 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6383 } else {
6384 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6385 }
6386 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6387 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6388 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6389 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6390
Steve Block3856b092011-10-20 11:56:00 +01006391 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006392 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6393
Mathias Agopian65ab4712010-07-14 17:59:35 -07006394 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006395 uint32_t size = sizeof(int);
6396 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006397 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006398 sizeof(effect_config_t),
6399 &mConfig,
6400 &size,
6401 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 if (status == 0) {
6403 status = cmdStatus;
6404 }
6405
6406 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6407 (1000 * mConfig.outputCfg.buffer.frameCount);
6408
6409 return status;
6410}
6411
6412status_t AudioFlinger::EffectModule::init()
6413{
6414 Mutex::Autolock _l(mLock);
6415 if (mEffectInterface == NULL) {
6416 return NO_INIT;
6417 }
6418 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006419 uint32_t size = sizeof(status_t);
6420 status_t status = (*mEffectInterface)->command(mEffectInterface,
6421 EFFECT_CMD_INIT,
6422 0,
6423 NULL,
6424 &size,
6425 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 if (status == 0) {
6427 status = cmdStatus;
6428 }
6429 return status;
6430}
6431
Eric Laurentec35a142011-10-05 17:42:25 -07006432status_t AudioFlinger::EffectModule::start()
6433{
6434 Mutex::Autolock _l(mLock);
6435 return start_l();
6436}
6437
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438status_t AudioFlinger::EffectModule::start_l()
6439{
6440 if (mEffectInterface == NULL) {
6441 return NO_INIT;
6442 }
6443 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006444 uint32_t size = sizeof(status_t);
6445 status_t status = (*mEffectInterface)->command(mEffectInterface,
6446 EFFECT_CMD_ENABLE,
6447 0,
6448 NULL,
6449 &size,
6450 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006451 if (status == 0) {
6452 status = cmdStatus;
6453 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006454 if (status == 0 &&
6455 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6456 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6457 sp<ThreadBase> thread = mThread.promote();
6458 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006459 audio_stream_t *stream = thread->stream();
6460 if (stream != NULL) {
6461 stream->add_audio_effect(stream, mEffectInterface);
6462 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006463 }
6464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465 return status;
6466}
6467
Eric Laurentec437d82011-07-26 20:54:46 -07006468status_t AudioFlinger::EffectModule::stop()
6469{
6470 Mutex::Autolock _l(mLock);
6471 return stop_l();
6472}
6473
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474status_t AudioFlinger::EffectModule::stop_l()
6475{
6476 if (mEffectInterface == NULL) {
6477 return NO_INIT;
6478 }
6479 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006480 uint32_t size = sizeof(status_t);
6481 status_t status = (*mEffectInterface)->command(mEffectInterface,
6482 EFFECT_CMD_DISABLE,
6483 0,
6484 NULL,
6485 &size,
6486 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487 if (status == 0) {
6488 status = cmdStatus;
6489 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006490 if (status == 0 &&
6491 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6492 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6493 sp<ThreadBase> thread = mThread.promote();
6494 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006495 audio_stream_t *stream = thread->stream();
6496 if (stream != NULL) {
6497 stream->remove_audio_effect(stream, mEffectInterface);
6498 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006499 }
6500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 return status;
6502}
6503
Eric Laurent25f43952010-07-28 05:40:18 -07006504status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6505 uint32_t cmdSize,
6506 void *pCmdData,
6507 uint32_t *replySize,
6508 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509{
6510 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006511// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512
Eric Laurentec437d82011-07-26 20:54:46 -07006513 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514 return NO_INIT;
6515 }
Eric Laurent25f43952010-07-28 05:40:18 -07006516 status_t status = (*mEffectInterface)->command(mEffectInterface,
6517 cmdCode,
6518 cmdSize,
6519 pCmdData,
6520 replySize,
6521 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006523 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 for (size_t i = 1; i < mHandles.size(); i++) {
6525 sp<EffectHandle> h = mHandles[i].promote();
6526 if (h != 0) {
6527 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6528 }
6529 }
6530 }
6531 return status;
6532}
6533
6534status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6535{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006536
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006538 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539
6540 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006541 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6542 if (enabled && status != NO_ERROR) {
6543 return status;
6544 }
6545
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 switch (mState) {
6547 // going from disabled to enabled
6548 case IDLE:
6549 mState = STARTING;
6550 break;
6551 case STOPPED:
6552 mState = RESTART;
6553 break;
6554 case STOPPING:
6555 mState = ACTIVE;
6556 break;
6557
6558 // going from enabled to disabled
6559 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006560 mState = STOPPED;
6561 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 case STARTING:
6563 mState = IDLE;
6564 break;
6565 case ACTIVE:
6566 mState = STOPPING;
6567 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006568 case DESTROYED:
6569 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570 }
6571 for (size_t i = 1; i < mHandles.size(); i++) {
6572 sp<EffectHandle> h = mHandles[i].promote();
6573 if (h != 0) {
6574 h->setEnabled(enabled);
6575 }
6576 }
6577 }
6578 return NO_ERROR;
6579}
6580
6581bool AudioFlinger::EffectModule::isEnabled()
6582{
6583 switch (mState) {
6584 case RESTART:
6585 case STARTING:
6586 case ACTIVE:
6587 return true;
6588 case IDLE:
6589 case STOPPING:
6590 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006591 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592 default:
6593 return false;
6594 }
6595}
6596
Eric Laurent8f45bd72010-08-31 13:50:07 -07006597bool AudioFlinger::EffectModule::isProcessEnabled()
6598{
6599 switch (mState) {
6600 case RESTART:
6601 case ACTIVE:
6602 case STOPPING:
6603 case STOPPED:
6604 return true;
6605 case IDLE:
6606 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006607 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006608 default:
6609 return false;
6610 }
6611}
6612
Mathias Agopian65ab4712010-07-14 17:59:35 -07006613status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6614{
6615 Mutex::Autolock _l(mLock);
6616 status_t status = NO_ERROR;
6617
6618 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6619 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006620 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006621 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6622 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006623 status_t cmdStatus;
6624 uint32_t volume[2];
6625 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006626 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006627 volume[0] = *left;
6628 volume[1] = *right;
6629 if (controller) {
6630 pVolume = volume;
6631 }
Eric Laurent25f43952010-07-28 05:40:18 -07006632 status = (*mEffectInterface)->command(mEffectInterface,
6633 EFFECT_CMD_SET_VOLUME,
6634 size,
6635 volume,
6636 &size,
6637 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6639 *left = volume[0];
6640 *right = volume[1];
6641 }
6642 }
6643 return status;
6644}
6645
6646status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6647{
6648 Mutex::Autolock _l(mLock);
6649 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006650 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6651 // audio pre processing modules on RecordThread can receive both output and
6652 // input device indication in the same call
6653 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6654 if (dev) {
6655 status_t cmdStatus;
6656 uint32_t size = sizeof(status_t);
6657
6658 status = (*mEffectInterface)->command(mEffectInterface,
6659 EFFECT_CMD_SET_DEVICE,
6660 sizeof(uint32_t),
6661 &dev,
6662 &size,
6663 &cmdStatus);
6664 if (status == NO_ERROR) {
6665 status = cmdStatus;
6666 }
6667 }
6668 dev = device & AUDIO_DEVICE_IN_ALL;
6669 if (dev) {
6670 status_t cmdStatus;
6671 uint32_t size = sizeof(status_t);
6672
6673 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6674 EFFECT_CMD_SET_INPUT_DEVICE,
6675 sizeof(uint32_t),
6676 &dev,
6677 &size,
6678 &cmdStatus);
6679 if (status2 == NO_ERROR) {
6680 status2 = cmdStatus;
6681 }
6682 if (status == NO_ERROR) {
6683 status = status2;
6684 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006685 }
6686 }
6687 return status;
6688}
6689
6690status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6691{
6692 Mutex::Autolock _l(mLock);
6693 status_t status = NO_ERROR;
6694 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006695 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006696 uint32_t size = sizeof(status_t);
6697 status = (*mEffectInterface)->command(mEffectInterface,
6698 EFFECT_CMD_SET_AUDIO_MODE,
6699 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006700 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006701 &size,
6702 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006703 if (status == NO_ERROR) {
6704 status = cmdStatus;
6705 }
6706 }
6707 return status;
6708}
6709
Eric Laurent59255e42011-07-27 19:49:51 -07006710void AudioFlinger::EffectModule::setSuspended(bool suspended)
6711{
6712 Mutex::Autolock _l(mLock);
6713 mSuspended = suspended;
6714}
Glenn Kastena3a85482012-01-04 11:01:11 -08006715
6716bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006717{
6718 Mutex::Autolock _l(mLock);
6719 return mSuspended;
6720}
6721
Mathias Agopian65ab4712010-07-14 17:59:35 -07006722status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6723{
6724 const size_t SIZE = 256;
6725 char buffer[SIZE];
6726 String8 result;
6727
6728 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6729 result.append(buffer);
6730
6731 bool locked = tryLock(mLock);
6732 // failed to lock - AudioFlinger is probably deadlocked
6733 if (!locked) {
6734 result.append("\t\tCould not lock Fx mutex:\n");
6735 }
6736
6737 result.append("\t\tSession Status State Engine:\n");
6738 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6739 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6740 result.append(buffer);
6741
6742 result.append("\t\tDescriptor:\n");
6743 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6744 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6745 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6746 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6747 result.append(buffer);
6748 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6749 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6750 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6751 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6752 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006753 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006754 mDescriptor.apiVersion,
6755 mDescriptor.flags);
6756 result.append(buffer);
6757 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6758 mDescriptor.name);
6759 result.append(buffer);
6760 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6761 mDescriptor.implementor);
6762 result.append(buffer);
6763
6764 result.append("\t\t- Input configuration:\n");
6765 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6766 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6767 (uint32_t)mConfig.inputCfg.buffer.raw,
6768 mConfig.inputCfg.buffer.frameCount,
6769 mConfig.inputCfg.samplingRate,
6770 mConfig.inputCfg.channels,
6771 mConfig.inputCfg.format);
6772 result.append(buffer);
6773
6774 result.append("\t\t- Output configuration:\n");
6775 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6776 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6777 (uint32_t)mConfig.outputCfg.buffer.raw,
6778 mConfig.outputCfg.buffer.frameCount,
6779 mConfig.outputCfg.samplingRate,
6780 mConfig.outputCfg.channels,
6781 mConfig.outputCfg.format);
6782 result.append(buffer);
6783
6784 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6785 result.append(buffer);
6786 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6787 for (size_t i = 0; i < mHandles.size(); ++i) {
6788 sp<EffectHandle> handle = mHandles[i].promote();
6789 if (handle != 0) {
6790 handle->dump(buffer, SIZE);
6791 result.append(buffer);
6792 }
6793 }
6794
6795 result.append("\n");
6796
6797 write(fd, result.string(), result.length());
6798
6799 if (locked) {
6800 mLock.unlock();
6801 }
6802
6803 return NO_ERROR;
6804}
6805
6806// ----------------------------------------------------------------------------
6807// EffectHandle implementation
6808// ----------------------------------------------------------------------------
6809
6810#undef LOG_TAG
6811#define LOG_TAG "AudioFlinger::EffectHandle"
6812
6813AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6814 const sp<AudioFlinger::Client>& client,
6815 const sp<IEffectClient>& effectClient,
6816 int32_t priority)
6817 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006818 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006819 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820{
Steve Block3856b092011-10-20 11:56:00 +01006821 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006822
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006823 if (client == 0) {
6824 return;
6825 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6827 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6828 if (mCblkMemory != 0) {
6829 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6830
6831 if (mCblk) {
6832 new(mCblk) effect_param_cblk_t();
6833 mBuffer = (uint8_t *)mCblk + bufOffset;
6834 }
6835 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006836 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 return;
6838 }
6839}
6840
6841AudioFlinger::EffectHandle::~EffectHandle()
6842{
Steve Block3856b092011-10-20 11:56:00 +01006843 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006844 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006845 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846}
6847
6848status_t AudioFlinger::EffectHandle::enable()
6849{
Steve Block3856b092011-10-20 11:56:00 +01006850 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851 if (!mHasControl) return INVALID_OPERATION;
6852 if (mEffect == 0) return DEAD_OBJECT;
6853
Eric Laurentdb7c0792011-08-10 10:37:50 -07006854 if (mEnabled) {
6855 return NO_ERROR;
6856 }
6857
Eric Laurent59255e42011-07-27 19:49:51 -07006858 mEnabled = true;
6859
6860 sp<ThreadBase> thread = mEffect->thread().promote();
6861 if (thread != 0) {
6862 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6863 }
6864
6865 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6866 if (mEffect->suspended()) {
6867 return NO_ERROR;
6868 }
6869
Eric Laurentdb7c0792011-08-10 10:37:50 -07006870 status_t status = mEffect->setEnabled(true);
6871 if (status != NO_ERROR) {
6872 if (thread != 0) {
6873 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6874 }
6875 mEnabled = false;
6876 }
6877 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878}
6879
6880status_t AudioFlinger::EffectHandle::disable()
6881{
Steve Block3856b092011-10-20 11:56:00 +01006882 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006884 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885
Eric Laurentdb7c0792011-08-10 10:37:50 -07006886 if (!mEnabled) {
6887 return NO_ERROR;
6888 }
Eric Laurent59255e42011-07-27 19:49:51 -07006889 mEnabled = false;
6890
6891 if (mEffect->suspended()) {
6892 return NO_ERROR;
6893 }
6894
6895 status_t status = mEffect->setEnabled(false);
6896
6897 sp<ThreadBase> thread = mEffect->thread().promote();
6898 if (thread != 0) {
6899 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6900 }
6901
6902 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903}
6904
6905void AudioFlinger::EffectHandle::disconnect()
6906{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006907 disconnect(true);
6908}
6909
6910void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6911{
Steve Block3856b092011-10-20 11:56:00 +01006912 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 if (mEffect == 0) {
6914 return;
6915 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006916 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006917
Eric Laurenta85a74a2011-10-19 11:44:54 -07006918 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006919 sp<ThreadBase> thread = mEffect->thread().promote();
6920 if (thread != 0) {
6921 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6922 }
Eric Laurent59255e42011-07-27 19:49:51 -07006923 }
6924
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 // release sp on module => module destructor can be called now
6926 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006928 if (mCblk) {
6929 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6930 }
6931 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6933 mClient.clear();
6934 }
6935}
6936
Eric Laurent25f43952010-07-28 05:40:18 -07006937status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6938 uint32_t cmdSize,
6939 void *pCmdData,
6940 uint32_t *replySize,
6941 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942{
Steve Block3856b092011-10-20 11:56:00 +01006943// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006944// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945
6946 // only get parameter command is permitted for applications not controlling the effect
6947 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6948 return INVALID_OPERATION;
6949 }
6950 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006951 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952
6953 // handle commands that are not forwarded transparently to effect engine
6954 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6955 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6956 // no risk to block the whole media server process or mixer threads is we are stuck here
6957 Mutex::Autolock _l(mCblk->lock);
6958 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6959 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6960 mCblk->serverIndex = 0;
6961 mCblk->clientIndex = 0;
6962 return BAD_VALUE;
6963 }
6964 status_t status = NO_ERROR;
6965 while (mCblk->serverIndex < mCblk->clientIndex) {
6966 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006967 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 int *p = (int *)(mBuffer + mCblk->serverIndex);
6969 int size = *p++;
6970 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006971 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 break;
6973 }
6974 effect_param_t *param = (effect_param_t *)p;
6975 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006976 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 mCblk->serverIndex += size;
6978 continue;
6979 }
Eric Laurent25f43952010-07-28 05:40:18 -07006980 uint32_t psize = sizeof(effect_param_t) +
6981 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6982 param->vsize;
6983 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6984 psize,
6985 p,
6986 &rsize,
6987 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006988 // stop at first error encountered
6989 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006991 *(int *)pReplyData = reply;
6992 break;
6993 } else if (reply != NO_ERROR) {
6994 *(int *)pReplyData = reply;
6995 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 }
6997 mCblk->serverIndex += size;
6998 }
6999 mCblk->serverIndex = 0;
7000 mCblk->clientIndex = 0;
7001 return status;
7002 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007003 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004 return enable();
7005 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007006 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 return disable();
7008 }
7009
7010 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7011}
7012
7013sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7014 return mCblkMemory;
7015}
7016
Eric Laurent59255e42011-07-27 19:49:51 -07007017void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018{
Steve Block3856b092011-10-20 11:56:00 +01007019 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020
7021 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007022 mEnabled = enabled;
7023
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 if (signal && mEffectClient != 0) {
7025 mEffectClient->controlStatusChanged(hasControl);
7026 }
7027}
7028
Eric Laurent25f43952010-07-28 05:40:18 -07007029void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7030 uint32_t cmdSize,
7031 void *pCmdData,
7032 uint32_t replySize,
7033 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034{
7035 if (mEffectClient != 0) {
7036 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7037 }
7038}
7039
7040
7041
7042void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7043{
7044 if (mEffectClient != 0) {
7045 mEffectClient->enableStatusChanged(enabled);
7046 }
7047}
7048
7049status_t AudioFlinger::EffectHandle::onTransact(
7050 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7051{
7052 return BnEffect::onTransact(code, data, reply, flags);
7053}
7054
7055
7056void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7057{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007058 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059
7060 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7061 (mClient == NULL) ? getpid() : mClient->pid(),
7062 mPriority,
7063 mHasControl,
7064 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007065 mCblk ? mCblk->clientIndex : 0,
7066 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 );
7068
7069 if (locked) {
7070 mCblk->lock.unlock();
7071 }
7072}
7073
7074#undef LOG_TAG
7075#define LOG_TAG "AudioFlinger::EffectChain"
7076
7077AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7078 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007079 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007080 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7081 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007082{
Dima Zavinfce7a472011-04-19 22:30:36 -07007083 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007084 sp<ThreadBase> thread = mThread.promote();
7085 if (thread == 0) {
7086 return;
7087 }
7088 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7089 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090}
7091
7092AudioFlinger::EffectChain::~EffectChain()
7093{
7094 if (mOwnInBuffer) {
7095 delete mInBuffer;
7096 }
7097
7098}
7099
Eric Laurent59255e42011-07-27 19:49:51 -07007100// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007101sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007102{
7103 sp<EffectModule> effect;
7104 size_t size = mEffects.size();
7105
7106 for (size_t i = 0; i < size; i++) {
7107 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7108 effect = mEffects[i];
7109 break;
7110 }
7111 }
7112 return effect;
7113}
7114
Eric Laurent59255e42011-07-27 19:49:51 -07007115// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007116sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007117{
7118 sp<EffectModule> effect;
7119 size_t size = mEffects.size();
7120
7121 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007122 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7123 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 effect = mEffects[i];
7125 break;
7126 }
7127 }
7128 return effect;
7129}
7130
Eric Laurent59255e42011-07-27 19:49:51 -07007131// getEffectFromType_l() must be called with ThreadBase::mLock held
7132sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7133 const effect_uuid_t *type)
7134{
7135 sp<EffectModule> effect;
7136 size_t size = mEffects.size();
7137
7138 for (size_t i = 0; i < size; i++) {
7139 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7140 effect = mEffects[i];
7141 break;
7142 }
7143 }
7144 return effect;
7145}
7146
Mathias Agopian65ab4712010-07-14 17:59:35 -07007147// Must be called with EffectChain::mLock locked
7148void AudioFlinger::EffectChain::process_l()
7149{
Eric Laurentdac69112010-09-28 14:09:57 -07007150 sp<ThreadBase> thread = mThread.promote();
7151 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007152 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007153 return;
7154 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007155 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7156 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007157 // always process effects unless no more tracks are on the session and the effect tail
7158 // has been rendered
7159 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007160 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007161 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007162
Eric Laurent544fe9b2011-11-11 15:42:52 -08007163 if (!tracksOnSession && mTailBufferCount == 0) {
7164 doProcess = false;
7165 }
7166
7167 if (activeTrackCnt() == 0) {
7168 // if no track is active and the effect tail has not been rendered,
7169 // the input buffer must be cleared here as the mixer process will not do it
7170 if (tracksOnSession || mTailBufferCount > 0) {
7171 size_t numSamples = thread->frameCount() * thread->channelCount();
7172 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7173 if (mTailBufferCount > 0) {
7174 mTailBufferCount--;
7175 }
7176 }
7177 }
Eric Laurentdac69112010-09-28 14:09:57 -07007178 }
7179
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007181 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007182 for (size_t i = 0; i < size; i++) {
7183 mEffects[i]->process();
7184 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185 }
7186 for (size_t i = 0; i < size; i++) {
7187 mEffects[i]->updateState();
7188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007189}
7190
Eric Laurentcab11242010-07-15 12:50:15 -07007191// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007192status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193{
7194 effect_descriptor_t desc = effect->desc();
7195 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7196
7197 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007198 effect->setChain(this);
7199 sp<ThreadBase> thread = mThread.promote();
7200 if (thread == 0) {
7201 return NO_INIT;
7202 }
7203 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204
7205 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7206 // Auxiliary effects are inserted at the beginning of mEffects vector as
7207 // they are processed first and accumulated in chain input buffer
7208 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007209
Mathias Agopian65ab4712010-07-14 17:59:35 -07007210 // the input buffer for auxiliary effect contains mono samples in
7211 // 32 bit format. This is to avoid saturation in AudoMixer
7212 // accumulation stage. Saturation is done in EffectModule::process() before
7213 // calling the process in effect engine
7214 size_t numSamples = thread->frameCount();
7215 int32_t *buffer = new int32_t[numSamples];
7216 memset(buffer, 0, numSamples * sizeof(int32_t));
7217 effect->setInBuffer((int16_t *)buffer);
7218 // auxiliary effects output samples to chain input buffer for further processing
7219 // by insert effects
7220 effect->setOutBuffer(mInBuffer);
7221 } else {
7222 // Insert effects are inserted at the end of mEffects vector as they are processed
7223 // after track and auxiliary effects.
7224 // Insert effect order as a function of indicated preference:
7225 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7226 // another effect is present
7227 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7228 // last effect claiming first position
7229 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7230 // first effect claiming last position
7231 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7232 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7233 // already present
7234
7235 int size = (int)mEffects.size();
7236 int idx_insert = size;
7237 int idx_insert_first = -1;
7238 int idx_insert_last = -1;
7239
7240 for (int i = 0; i < size; i++) {
7241 effect_descriptor_t d = mEffects[i]->desc();
7242 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7243 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7244 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7245 // check invalid effect chaining combinations
7246 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7247 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007248 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249 return INVALID_OPERATION;
7250 }
7251 // remember position of first insert effect and by default
7252 // select this as insert position for new effect
7253 if (idx_insert == size) {
7254 idx_insert = i;
7255 }
7256 // remember position of last insert effect claiming
7257 // first position
7258 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7259 idx_insert_first = i;
7260 }
7261 // remember position of first insert effect claiming
7262 // last position
7263 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7264 idx_insert_last == -1) {
7265 idx_insert_last = i;
7266 }
7267 }
7268 }
7269
7270 // modify idx_insert from first position if needed
7271 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7272 if (idx_insert_last != -1) {
7273 idx_insert = idx_insert_last;
7274 } else {
7275 idx_insert = size;
7276 }
7277 } else {
7278 if (idx_insert_first != -1) {
7279 idx_insert = idx_insert_first + 1;
7280 }
7281 }
7282
7283 // always read samples from chain input buffer
7284 effect->setInBuffer(mInBuffer);
7285
7286 // if last effect in the chain, output samples to chain
7287 // output buffer, otherwise to chain input buffer
7288 if (idx_insert == size) {
7289 if (idx_insert != 0) {
7290 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7291 mEffects[idx_insert-1]->configure();
7292 }
7293 effect->setOutBuffer(mOutBuffer);
7294 } else {
7295 effect->setOutBuffer(mInBuffer);
7296 }
7297 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007298
Steve Block3856b092011-10-20 11:56:00 +01007299 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300 }
7301 effect->configure();
7302 return NO_ERROR;
7303}
7304
Eric Laurentcab11242010-07-15 12:50:15 -07007305// removeEffect_l() must be called with PlaybackThread::mLock held
7306size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307{
7308 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309 int size = (int)mEffects.size();
7310 int i;
7311 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7312
7313 for (i = 0; i < size; i++) {
7314 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007315 // calling stop here will remove pre-processing effect from the audio HAL.
7316 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7317 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007318 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7319 mEffects[i]->state() == EffectModule::STOPPING) {
7320 mEffects[i]->stop();
7321 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7323 delete[] effect->inBuffer();
7324 } else {
7325 if (i == size - 1 && i != 0) {
7326 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7327 mEffects[i - 1]->configure();
7328 }
7329 }
7330 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007331 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332 break;
7333 }
7334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335
7336 return mEffects.size();
7337}
7338
Eric Laurentcab11242010-07-15 12:50:15 -07007339// setDevice_l() must be called with PlaybackThread::mLock held
7340void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341{
7342 size_t size = mEffects.size();
7343 for (size_t i = 0; i < size; i++) {
7344 mEffects[i]->setDevice(device);
7345 }
7346}
7347
Eric Laurentcab11242010-07-15 12:50:15 -07007348// setMode_l() must be called with PlaybackThread::mLock held
7349void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007350{
7351 size_t size = mEffects.size();
7352 for (size_t i = 0; i < size; i++) {
7353 mEffects[i]->setMode(mode);
7354 }
7355}
7356
Eric Laurentcab11242010-07-15 12:50:15 -07007357// setVolume_l() must be called with PlaybackThread::mLock held
7358bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359{
7360 uint32_t newLeft = *left;
7361 uint32_t newRight = *right;
7362 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007363 int ctrlIdx = -1;
7364 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365
Eric Laurentcab11242010-07-15 12:50:15 -07007366 // first update volume controller
7367 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007368 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007369 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7370 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007371 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007372 break;
7373 }
7374 }
7375
7376 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007377 if (hasControl) {
7378 *left = mNewLeftVolume;
7379 *right = mNewRightVolume;
7380 }
7381 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007382 }
7383
7384 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007385 mLeftVolume = newLeft;
7386 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007387
7388 // second get volume update from volume controller
7389 if (ctrlIdx >= 0) {
7390 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007391 mNewLeftVolume = newLeft;
7392 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007393 }
7394 // then indicate volume to all other effects in chain.
7395 // Pass altered volume to effects before volume controller
7396 // and requested volume to effects after controller
7397 uint32_t lVol = newLeft;
7398 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007399
Mathias Agopian65ab4712010-07-14 17:59:35 -07007400 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007401 if ((int)i == ctrlIdx) continue;
7402 // this also works for ctrlIdx == -1 when there is no volume controller
7403 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404 lVol = *left;
7405 rVol = *right;
7406 }
7407 mEffects[i]->setVolume(&lVol, &rVol, false);
7408 }
7409 *left = newLeft;
7410 *right = newRight;
7411
7412 return hasControl;
7413}
7414
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7416{
7417 const size_t SIZE = 256;
7418 char buffer[SIZE];
7419 String8 result;
7420
7421 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7422 result.append(buffer);
7423
7424 bool locked = tryLock(mLock);
7425 // failed to lock - AudioFlinger is probably deadlocked
7426 if (!locked) {
7427 result.append("\tCould not lock mutex:\n");
7428 }
7429
Eric Laurentcab11242010-07-15 12:50:15 -07007430 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7431 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432 mEffects.size(),
7433 (uint32_t)mInBuffer,
7434 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435 mActiveTrackCnt);
7436 result.append(buffer);
7437 write(fd, result.string(), result.size());
7438
7439 for (size_t i = 0; i < mEffects.size(); ++i) {
7440 sp<EffectModule> effect = mEffects[i];
7441 if (effect != 0) {
7442 effect->dump(fd, args);
7443 }
7444 }
7445
7446 if (locked) {
7447 mLock.unlock();
7448 }
7449
7450 return NO_ERROR;
7451}
7452
Eric Laurent59255e42011-07-27 19:49:51 -07007453// must be called with ThreadBase::mLock held
7454void AudioFlinger::EffectChain::setEffectSuspended_l(
7455 const effect_uuid_t *type, bool suspend)
7456{
7457 sp<SuspendedEffectDesc> desc;
7458 // use effect type UUID timelow as key as there is no real risk of identical
7459 // timeLow fields among effect type UUIDs.
7460 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7461 if (suspend) {
7462 if (index >= 0) {
7463 desc = mSuspendedEffects.valueAt(index);
7464 } else {
7465 desc = new SuspendedEffectDesc();
7466 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7467 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007468 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007469 }
7470 if (desc->mRefCount++ == 0) {
7471 sp<EffectModule> effect = getEffectIfEnabled(type);
7472 if (effect != 0) {
7473 desc->mEffect = effect;
7474 effect->setSuspended(true);
7475 effect->setEnabled(false);
7476 }
7477 }
7478 } else {
7479 if (index < 0) {
7480 return;
7481 }
7482 desc = mSuspendedEffects.valueAt(index);
7483 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007484 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007485 desc->mRefCount = 1;
7486 }
7487 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007488 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007489 if (desc->mEffect != 0) {
7490 sp<EffectModule> effect = desc->mEffect.promote();
7491 if (effect != 0) {
7492 effect->setSuspended(false);
7493 sp<EffectHandle> handle = effect->controlHandle();
7494 if (handle != 0) {
7495 effect->setEnabled(handle->enabled());
7496 }
7497 }
7498 desc->mEffect.clear();
7499 }
7500 mSuspendedEffects.removeItemsAt(index);
7501 }
7502 }
7503}
7504
7505// must be called with ThreadBase::mLock held
7506void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7507{
7508 sp<SuspendedEffectDesc> desc;
7509
7510 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7511 if (suspend) {
7512 if (index >= 0) {
7513 desc = mSuspendedEffects.valueAt(index);
7514 } else {
7515 desc = new SuspendedEffectDesc();
7516 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007517 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007518 }
7519 if (desc->mRefCount++ == 0) {
7520 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7521 for (size_t i = 0; i < effects.size(); i++) {
7522 setEffectSuspended_l(&effects[i]->desc().type, true);
7523 }
7524 }
7525 } else {
7526 if (index < 0) {
7527 return;
7528 }
7529 desc = mSuspendedEffects.valueAt(index);
7530 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007531 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007532 desc->mRefCount = 1;
7533 }
7534 if (--desc->mRefCount == 0) {
7535 Vector<const effect_uuid_t *> types;
7536 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7537 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7538 continue;
7539 }
7540 types.add(&mSuspendedEffects.valueAt(i)->mType);
7541 }
7542 for (size_t i = 0; i < types.size(); i++) {
7543 setEffectSuspended_l(types[i], false);
7544 }
Steve Block3856b092011-10-20 11:56:00 +01007545 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007546 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7547 }
7548 }
7549}
7550
Eric Laurent6bffdb82011-09-23 08:40:41 -07007551
7552// The volume effect is used for automated tests only
7553#ifndef OPENSL_ES_H_
7554static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7555 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7556const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7557#endif //OPENSL_ES_H_
7558
Eric Laurentdb7c0792011-08-10 10:37:50 -07007559bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7560{
7561 // auxiliary effects and visualizer are never suspended on output mix
7562 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7563 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007564 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7565 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007566 return false;
7567 }
7568 return true;
7569}
7570
Eric Laurent59255e42011-07-27 19:49:51 -07007571Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7572{
7573 Vector< sp<EffectModule> > effects;
7574 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007575 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007576 continue;
7577 }
7578 effects.add(mEffects[i]);
7579 }
7580 return effects;
7581}
7582
7583sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7584 const effect_uuid_t *type)
7585{
7586 sp<EffectModule> effect;
7587 effect = getEffectFromType_l(type);
7588 if (effect != 0 && !effect->isEnabled()) {
7589 effect.clear();
7590 }
7591 return effect;
7592}
7593
7594void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7595 bool enabled)
7596{
7597 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7598 if (enabled) {
7599 if (index < 0) {
7600 // if the effect is not suspend check if all effects are suspended
7601 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7602 if (index < 0) {
7603 return;
7604 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007605 if (!isEffectEligibleForSuspend(effect->desc())) {
7606 return;
7607 }
Eric Laurent59255e42011-07-27 19:49:51 -07007608 setEffectSuspended_l(&effect->desc().type, enabled);
7609 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007610 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007611 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007612 return;
7613 }
Eric Laurent59255e42011-07-27 19:49:51 -07007614 }
Steve Block3856b092011-10-20 11:56:00 +01007615 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007616 effect->desc().type.timeLow);
7617 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7618 // if effect is requested to suspended but was not yet enabled, supend it now.
7619 if (desc->mEffect == 0) {
7620 desc->mEffect = effect;
7621 effect->setEnabled(false);
7622 effect->setSuspended(true);
7623 }
7624 } else {
7625 if (index < 0) {
7626 return;
7627 }
Steve Block3856b092011-10-20 11:56:00 +01007628 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007629 effect->desc().type.timeLow);
7630 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7631 desc->mEffect.clear();
7632 effect->setSuspended(false);
7633 }
7634}
7635
Mathias Agopian65ab4712010-07-14 17:59:35 -07007636#undef LOG_TAG
7637#define LOG_TAG "AudioFlinger"
7638
7639// ----------------------------------------------------------------------------
7640
7641status_t AudioFlinger::onTransact(
7642 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7643{
7644 return BnAudioFlinger::onTransact(code, data, reply, flags);
7645}
7646
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647}; // namespace android