blob: a43afacff0e3f006c8d65d093e2983227e022aaf [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kastene0feee32011-12-13 11:53:26 -0800163 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700164 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700171
Eric Laurent93575202011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin799a70e2011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175 mHardwareStatus = AUDIO_HW_IDLE;
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
178 const hw_module_t *mod;
179 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700180
Dima Zavin799a70e2011-04-18 16:57:27 -0700181 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
182 if (rc)
183 continue;
184
Steve Blockdf64d152012-01-04 20:05:49 +0000185 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 mod->name, mod->id);
187 mAudioHwDevs.push(dev);
188
189 if (!mPrimaryHardwareDev) {
190 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000191 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 }
194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195
196 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000199 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 return;
201 }
202
203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204 audio_hw_device_t *dev = mAudioHwDevs[i];
205
206 mHardwareStatus = AUDIO_HW_INIT;
207 rc = dev->init_check(dev);
208 if (rc == 0) {
209 AutoMutex lock(mHardwareLock);
210
211 mMode = AUDIO_MODE_NORMAL;
212 mHardwareStatus = AUDIO_HW_SET_MODE;
213 dev->set_mode(dev, mMode);
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 dev->set_master_volume(dev, 1.0f);
216 mHardwareStatus = AUDIO_HW_IDLE;
217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219}
220
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700221status_t AudioFlinger::initCheck() const
222{
223 Mutex::Autolock _l(mLock);
224 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
225 return NO_INIT;
226 return NO_ERROR;
227}
228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229AudioFlinger::~AudioFlinger()
230{
Dima Zavin799a70e2011-04-18 16:57:27 -0700231 int num_devs = mAudioHwDevs.size();
232
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700241
242 for (int i = 0; i < num_devs; i++) {
243 audio_hw_device_t *dev = mAudioHwDevs[i];
244 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
Dima Zavin799a70e2011-04-18 16:57:27 -0700249audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
250{
251 /* first matching HW device is returned */
252 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
253 audio_hw_device_t *dev = mAudioHwDevs[i];
254 if ((dev->get_supported_devices(dev) & devices) == devices)
255 return dev;
256 }
257 return NULL;
258}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259
260status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
261{
262 const size_t SIZE = 256;
263 char buffer[SIZE];
264 String8 result;
265
266 result.append("Clients:\n");
267 for (size_t i = 0; i < mClients.size(); ++i) {
268 wp<Client> wClient = mClients.valueAt(i);
269 if (wClient != 0) {
270 sp<Client> client = wClient.promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
274 }
275 }
276 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700277
278 result.append("Global session refs:\n");
279 result.append(" session pid cnt\n");
280 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
281 AudioSessionRef *r = mAudioSessionRefs[i];
282 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
283 result.append(buffer);
284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285 write(fd, result.string(), result.size());
286 return NO_ERROR;
287}
288
289
290status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800295 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700296
297 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
298 result.append(buffer);
299 write(fd, result.string(), result.size());
300 return NO_ERROR;
301}
302
303status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308 snprintf(buffer, SIZE, "Permission Denial: "
309 "can't dump AudioFlinger from pid=%d, uid=%d\n",
310 IPCThreadState::self()->getCallingPid(),
311 IPCThreadState::self()->getCallingUid());
312 result.append(buffer);
313 write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
317static bool tryLock(Mutex& mutex)
318{
319 bool locked = false;
320 for (int i = 0; i < kDumpLockRetries; ++i) {
321 if (mutex.tryLock() == NO_ERROR) {
322 locked = true;
323 break;
324 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800325 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 }
327 return locked;
328}
329
330status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
331{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800332 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700333 dumpPermissionDenial(fd, args);
334 } else {
335 // get state of hardware lock
336 bool hardwareLocked = tryLock(mHardwareLock);
337 if (!hardwareLocked) {
338 String8 result(kHardwareLockedString);
339 write(fd, result.string(), result.size());
340 } else {
341 mHardwareLock.unlock();
342 }
343
344 bool locked = tryLock(mLock);
345
346 // failed to lock - AudioFlinger is probably deadlocked
347 if (!locked) {
348 String8 result(kDeadlockedString);
349 write(fd, result.string(), result.size());
350 }
351
352 dumpClients(fd, args);
353 dumpInternals(fd, args);
354
355 // dump playback threads
356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
357 mPlaybackThreads.valueAt(i)->dump(fd, args);
358 }
359
360 // dump record threads
361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
362 mRecordThreads.valueAt(i)->dump(fd, args);
363 }
364
Dima Zavin799a70e2011-04-18 16:57:27 -0700365 // dump all hardware devs
366 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
367 audio_hw_device_t *dev = mAudioHwDevs[i];
368 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369 }
370 if (locked) mLock.unlock();
371 }
372 return NO_ERROR;
373}
374
375
376// IAudioFlinger interface
377
378
379sp<IAudioTrack> AudioFlinger::createTrack(
380 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800381 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700382 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800383 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700384 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 int frameCount,
386 uint32_t flags,
387 const sp<IMemory>& sharedBuffer,
388 int output,
389 int *sessionId,
390 status_t *status)
391{
392 sp<PlaybackThread::Track> track;
393 sp<TrackHandle> trackHandle;
394 sp<Client> client;
395 wp<Client> wclient;
396 status_t lStatus;
397 int lSessionId;
398
Glenn Kasten263709e2012-01-06 08:40:01 -0800399 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
400 // but if someone uses binder directly they could bypass that and cause us to crash
401 if (uint32_t(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
Glenn Kasten58f30212012-01-12 12:27:51 -0800503audio_format_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);
Glenn Kasten58f30212012-01-12 12:27:51 -0800509 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700510 }
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
Glenn Kastenf78aee72012-01-04 11:00:47 -0800566status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567{
Eric Laurenta1884f92011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572
573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800577 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000578 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 return BAD_VALUE;
580 }
581
582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 }
588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 }
595
596 return ret;
597}
598
599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurenta1884f92011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavinfce7a472011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
638
Eric Laurent93575202011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
643
644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
Glenn Kasten98067102011-12-13 11:47:54 -0800649 Mutex::Autolock _l(mLock);
650 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700651}
652
653bool AudioFlinger::masterMute() const
654{
Glenn Kasten98067102011-12-13 11:47:54 -0800655 Mutex::Autolock _l(mLock);
656 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657}
658
Glenn Kastenfff6d712012-01-12 16:38:12 -0800659status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660{
661 // check calling permissions
662 if (!settingsAllowed()) {
663 return PERMISSION_DENIED;
664 }
665
Glenn Kasten263709e2012-01-06 08:40:01 -0800666 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000667 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 return BAD_VALUE;
669 }
670
671 AutoMutex lock(mLock);
672 PlaybackThread *thread = NULL;
673 if (output) {
674 thread = checkPlaybackThread_l(output);
675 if (thread == NULL) {
676 return BAD_VALUE;
677 }
678 }
679
680 mStreamTypes[stream].volume = value;
681
682 if (thread == NULL) {
683 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
684 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
685 }
686 } else {
687 thread->setStreamVolume(stream, value);
688 }
689
690 return NO_ERROR;
691}
692
Glenn Kastenfff6d712012-01-12 16:38:12 -0800693status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694{
695 // check calling permissions
696 if (!settingsAllowed()) {
697 return PERMISSION_DENIED;
698 }
699
Glenn Kasten263709e2012-01-06 08:40:01 -0800700 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000702 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 return BAD_VALUE;
704 }
705
Eric Laurent93575202011-01-18 18:39:02 -0800706 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707 mStreamTypes[stream].mute = muted;
708 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
709 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
710
711 return NO_ERROR;
712}
713
Glenn Kastenfff6d712012-01-12 16:38:12 -0800714float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715{
Glenn Kasten263709e2012-01-06 08:40:01 -0800716 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717 return 0.0f;
718 }
719
720 AutoMutex lock(mLock);
721 float volume;
722 if (output) {
723 PlaybackThread *thread = checkPlaybackThread_l(output);
724 if (thread == NULL) {
725 return 0.0f;
726 }
727 volume = thread->streamVolume(stream);
728 } else {
729 volume = mStreamTypes[stream].volume;
730 }
731
732 return volume;
733}
734
Glenn Kastenfff6d712012-01-12 16:38:12 -0800735bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736{
Glenn Kasten263709e2012-01-06 08:40:01 -0800737 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738 return true;
739 }
740
741 return mStreamTypes[stream].mute;
742}
743
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
745{
746 status_t result;
747
Steve Block3856b092011-10-20 11:56:00 +0100748 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
750 // check calling permissions
751 if (!settingsAllowed()) {
752 return PERMISSION_DENIED;
753 }
754
Mathias Agopian65ab4712010-07-14 17:59:35 -0700755 // ioHandle == 0 means the parameters are global to the audio hardware interface
756 if (ioHandle == 0) {
757 AutoMutex lock(mHardwareLock);
758 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700759 status_t final_result = NO_ERROR;
760 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
761 audio_hw_device_t *dev = mAudioHwDevs[i];
762 result = dev->set_parameters(dev, keyValuePairs.string());
763 final_result = result ?: final_result;
764 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700765 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700766 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
767 AudioParameter param = AudioParameter(keyValuePairs);
768 String8 value;
769 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
770 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700771 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
772 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700773 for (size_t i = 0; i < mRecordThreads.size(); i++) {
774 sp<RecordThread> thread = mRecordThreads.valueAt(i);
775 RecordThread::RecordTrack *track = thread->track();
776 if (track != NULL) {
777 audio_devices_t device = (audio_devices_t)(
778 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700779 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700780 thread->setEffectSuspended(FX_IID_AEC,
781 suspend,
782 track->sessionId());
783 thread->setEffectSuspended(FX_IID_NS,
784 suspend,
785 track->sessionId());
786 }
787 }
Eric Laurentbee53372011-08-29 12:42:48 -0700788 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700789 }
790 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700791 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700792 }
793
794 // hold a strong ref on thread in case closeOutput() or closeInput() is called
795 // and the thread is exited once the lock is released
796 sp<ThreadBase> thread;
797 {
798 Mutex::Autolock _l(mLock);
799 thread = checkPlaybackThread_l(ioHandle);
800 if (thread == NULL) {
801 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800802 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700803 // indicate output device change to all input threads for pre processing
804 AudioParameter param = AudioParameter(keyValuePairs);
805 int value;
806 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
807 for (size_t i = 0; i < mRecordThreads.size(); i++) {
808 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
809 }
810 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 }
812 }
813 if (thread != NULL) {
814 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 return result;
816 }
817 return BAD_VALUE;
818}
819
820String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
821{
Steve Block3856b092011-10-20 11:56:00 +0100822// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
824
825 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700826 String8 out_s8;
827
Dima Zavin799a70e2011-04-18 16:57:27 -0700828 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
829 audio_hw_device_t *dev = mAudioHwDevs[i];
830 char *s = dev->get_parameters(dev, keys.string());
831 out_s8 += String8(s);
832 free(s);
833 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700834 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835 }
836
837 Mutex::Autolock _l(mLock);
838
839 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
840 if (playbackThread != NULL) {
841 return playbackThread->getParameters(keys);
842 }
843 RecordThread *recordThread = checkRecordThread_l(ioHandle);
844 if (recordThread != NULL) {
845 return recordThread->getParameters(keys);
846 }
847 return String8("");
848}
849
Glenn Kasten58f30212012-01-12 12:27:51 -0800850size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851{
Eric Laurenta1884f92011-08-23 08:25:03 -0700852 status_t ret = initCheck();
853 if (ret != NO_ERROR) {
854 return 0;
855 }
856
Dima Zavin799a70e2011-04-18 16:57:27 -0700857 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700858}
859
860unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
861{
862 if (ioHandle == 0) {
863 return 0;
864 }
865
866 Mutex::Autolock _l(mLock);
867
868 RecordThread *recordThread = checkRecordThread_l(ioHandle);
869 if (recordThread != NULL) {
870 return recordThread->getInputFramesLost();
871 }
872 return 0;
873}
874
875status_t AudioFlinger::setVoiceVolume(float value)
876{
Eric Laurenta1884f92011-08-23 08:25:03 -0700877 status_t ret = initCheck();
878 if (ret != NO_ERROR) {
879 return ret;
880 }
881
Mathias Agopian65ab4712010-07-14 17:59:35 -0700882 // check calling permissions
883 if (!settingsAllowed()) {
884 return PERMISSION_DENIED;
885 }
886
887 AutoMutex lock(mHardwareLock);
888 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700889 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890 mHardwareStatus = AUDIO_HW_IDLE;
891
892 return ret;
893}
894
895status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
896{
897 status_t status;
898
899 Mutex::Autolock _l(mLock);
900
901 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
902 if (playbackThread != NULL) {
903 return playbackThread->getRenderPosition(halFrames, dspFrames);
904 }
905
906 return BAD_VALUE;
907}
908
909void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
910{
911
912 Mutex::Autolock _l(mLock);
913
914 int pid = IPCThreadState::self()->getCallingPid();
915 if (mNotificationClients.indexOfKey(pid) < 0) {
916 sp<NotificationClient> notificationClient = new NotificationClient(this,
917 client,
918 pid);
Steve Block3856b092011-10-20 11:56:00 +0100919 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920
921 mNotificationClients.add(pid, notificationClient);
922
923 sp<IBinder> binder = client->asBinder();
924 binder->linkToDeath(notificationClient);
925
926 // the config change is always sent from playback or record threads to avoid deadlock
927 // with AudioSystem::gLock
928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
929 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
930 }
931
932 for (size_t i = 0; i < mRecordThreads.size(); i++) {
933 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
934 }
935 }
936}
937
938void AudioFlinger::removeNotificationClient(pid_t pid)
939{
940 Mutex::Autolock _l(mLock);
941
942 int index = mNotificationClients.indexOfKey(pid);
943 if (index >= 0) {
944 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100945 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700946 mNotificationClients.removeItem(pid);
947 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950 int num = mAudioSessionRefs.size();
951 bool removed = false;
952 for (int i = 0; i< num; i++) {
953 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100954 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700955 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700957 mAudioSessionRefs.removeAt(i);
958 delete ref;
959 removed = true;
960 i--;
961 num--;
962 }
963 }
964 if (removed) {
965 purgeStaleEffects_l();
966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700967}
968
969// audioConfigChanged_l() must be called with AudioFlinger::mLock held
970void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
971{
972 size_t size = mNotificationClients.size();
973 for (size_t i = 0; i < size; i++) {
974 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
975 }
976}
977
978// removeClient_l() must be called with AudioFlinger::mLock held
979void AudioFlinger::removeClient_l(pid_t pid)
980{
Steve Block3856b092011-10-20 11:56:00 +0100981 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 mClients.removeItem(pid);
983}
984
985
986// ----------------------------------------------------------------------------
987
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
989 type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800991 mType(type),
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Glenn Kasten58f30212012-01-12 12:27:51 -0800993 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID), mStandby(false), mId(id), mExiting(false),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700994 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700996 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997}
998
999AudioFlinger::ThreadBase::~ThreadBase()
1000{
1001 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001002 // do not lock the mutex in destructor
1003 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001004 if (mPowerManager != 0) {
1005 sp<IBinder> binder = mPowerManager->asBinder();
1006 binder->unlinkToDeath(mDeathRecipient);
1007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008}
1009
1010void AudioFlinger::ThreadBase::exit()
1011{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001012 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 // destroyed in the middle of requestExitAndWait()
1014 sp <ThreadBase> strongMe = this;
1015
Steve Block3856b092011-10-20 11:56:00 +01001016 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001018 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 mExiting = true;
1020 requestExit();
1021 mWaitWorkCV.signal();
1022 }
1023 requestExitAndWait();
1024}
1025
1026uint32_t AudioFlinger::ThreadBase::sampleRate() const
1027{
1028 return mSampleRate;
1029}
1030
1031int AudioFlinger::ThreadBase::channelCount() const
1032{
1033 return (int)mChannelCount;
1034}
1035
Glenn Kasten58f30212012-01-12 12:27:51 -08001036audio_format_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037{
1038 return mFormat;
1039}
1040
1041size_t AudioFlinger::ThreadBase::frameCount() const
1042{
1043 return mFrameCount;
1044}
1045
1046status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1047{
1048 status_t status;
1049
Steve Block3856b092011-10-20 11:56:00 +01001050 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 Mutex::Autolock _l(mLock);
1052
1053 mNewParameters.add(keyValuePairs);
1054 mWaitWorkCV.signal();
1055 // wait condition with timeout in case the thread loop has exited
1056 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001057 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 status = mParamStatus;
1059 mWaitWorkCV.signal();
1060 } else {
1061 status = TIMED_OUT;
1062 }
1063 return status;
1064}
1065
1066void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1067{
1068 Mutex::Autolock _l(mLock);
1069 sendConfigEvent_l(event, param);
1070}
1071
1072// sendConfigEvent_l() must be called with ThreadBase::mLock held
1073void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1074{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001075 ConfigEvent configEvent;
1076 configEvent.mEvent = event;
1077 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 mWaitWorkCV.signal();
1081}
1082
1083void AudioFlinger::ThreadBase::processConfigEvents()
1084{
1085 mLock.lock();
1086 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001088 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 mConfigEvents.removeAt(0);
1090 // release mLock before locking AudioFlinger mLock: lock order is always
1091 // AudioFlinger then ThreadBase to avoid cross deadlock
1092 mLock.unlock();
1093 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001094 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mLock.lock();
1097 }
1098 mLock.unlock();
1099}
1100
1101status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1102{
1103 const size_t SIZE = 256;
1104 char buffer[SIZE];
1105 String8 result;
1106
1107 bool locked = tryLock(mLock);
1108 if (!locked) {
1109 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1110 write(fd, buffer, strlen(buffer));
1111 }
1112
1113 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1116 result.append(buffer);
1117 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1118 result.append(buffer);
1119 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1120 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001121 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1122 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1124 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001125 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 result.append(buffer);
1127
1128 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1129 result.append(buffer);
1130 result.append(" Index Command");
1131 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1132 snprintf(buffer, SIZE, "\n %02d ", i);
1133 result.append(buffer);
1134 result.append(mNewParameters[i]);
1135 }
1136
1137 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1138 result.append(buffer);
1139 snprintf(buffer, SIZE, " Index event param\n");
1140 result.append(buffer);
1141 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001142 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143 result.append(buffer);
1144 }
1145 result.append("\n");
1146
1147 write(fd, result.string(), result.size());
1148
1149 if (locked) {
1150 mLock.unlock();
1151 }
1152 return NO_ERROR;
1153}
1154
Eric Laurent1d2bff02011-07-24 17:49:51 -07001155status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1156{
1157 const size_t SIZE = 256;
1158 char buffer[SIZE];
1159 String8 result;
1160
1161 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1162 write(fd, buffer, strlen(buffer));
1163
1164 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1165 sp<EffectChain> chain = mEffectChains[i];
1166 if (chain != 0) {
1167 chain->dump(fd, args);
1168 }
1169 }
1170 return NO_ERROR;
1171}
1172
Eric Laurentfeb0db62011-07-22 09:04:31 -07001173void AudioFlinger::ThreadBase::acquireWakeLock()
1174{
1175 Mutex::Autolock _l(mLock);
1176 acquireWakeLock_l();
1177}
1178
1179void AudioFlinger::ThreadBase::acquireWakeLock_l()
1180{
1181 if (mPowerManager == 0) {
1182 // use checkService() to avoid blocking if power service is not up yet
1183 sp<IBinder> binder =
1184 defaultServiceManager()->checkService(String16("power"));
1185 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001186 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001187 } else {
1188 mPowerManager = interface_cast<IPowerManager>(binder);
1189 binder->linkToDeath(mDeathRecipient);
1190 }
1191 }
1192 if (mPowerManager != 0) {
1193 sp<IBinder> binder = new BBinder();
1194 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1195 binder,
1196 String16(mName));
1197 if (status == NO_ERROR) {
1198 mWakeLockToken = binder;
1199 }
Steve Block3856b092011-10-20 11:56:00 +01001200 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001201 }
1202}
1203
1204void AudioFlinger::ThreadBase::releaseWakeLock()
1205{
1206 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001207 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001208}
1209
1210void AudioFlinger::ThreadBase::releaseWakeLock_l()
1211{
1212 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001213 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001214 if (mPowerManager != 0) {
1215 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1216 }
1217 mWakeLockToken.clear();
1218 }
1219}
1220
1221void AudioFlinger::ThreadBase::clearPowerManager()
1222{
1223 Mutex::Autolock _l(mLock);
1224 releaseWakeLock_l();
1225 mPowerManager.clear();
1226}
1227
1228void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1229{
1230 sp<ThreadBase> thread = mThread.promote();
1231 if (thread != 0) {
1232 thread->clearPowerManager();
1233 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001234 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001235}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001236
Eric Laurent59255e42011-07-27 19:49:51 -07001237void AudioFlinger::ThreadBase::setEffectSuspended(
1238 const effect_uuid_t *type, bool suspend, int sessionId)
1239{
1240 Mutex::Autolock _l(mLock);
1241 setEffectSuspended_l(type, suspend, sessionId);
1242}
1243
1244void AudioFlinger::ThreadBase::setEffectSuspended_l(
1245 const effect_uuid_t *type, bool suspend, int sessionId)
1246{
1247 sp<EffectChain> chain;
1248 chain = getEffectChain_l(sessionId);
1249 if (chain != 0) {
1250 if (type != NULL) {
1251 chain->setEffectSuspended_l(type, suspend);
1252 } else {
1253 chain->setEffectSuspendedAll_l(suspend);
1254 }
1255 }
1256
1257 updateSuspendedSessions_l(type, suspend, sessionId);
1258}
1259
1260void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1261{
1262 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1263 if (index < 0) {
1264 return;
1265 }
1266
1267 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1268 mSuspendedSessions.editValueAt(index);
1269
1270 for (size_t i = 0; i < sessionEffects.size(); i++) {
1271 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1272 for (int j = 0; j < desc->mRefCount; j++) {
1273 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1274 chain->setEffectSuspendedAll_l(true);
1275 } else {
Steve Block3856b092011-10-20 11:56:00 +01001276 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001277 desc->mType.timeLow);
1278 chain->setEffectSuspended_l(&desc->mType, true);
1279 }
1280 }
1281 }
1282}
1283
Eric Laurent59255e42011-07-27 19:49:51 -07001284void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1285 bool suspend,
1286 int sessionId)
1287{
1288 int index = mSuspendedSessions.indexOfKey(sessionId);
1289
1290 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1291
1292 if (suspend) {
1293 if (index >= 0) {
1294 sessionEffects = mSuspendedSessions.editValueAt(index);
1295 } else {
1296 mSuspendedSessions.add(sessionId, sessionEffects);
1297 }
1298 } else {
1299 if (index < 0) {
1300 return;
1301 }
1302 sessionEffects = mSuspendedSessions.editValueAt(index);
1303 }
1304
1305
1306 int key = EffectChain::kKeyForSuspendAll;
1307 if (type != NULL) {
1308 key = type->timeLow;
1309 }
1310 index = sessionEffects.indexOfKey(key);
1311
1312 sp <SuspendedSessionDesc> desc;
1313 if (suspend) {
1314 if (index >= 0) {
1315 desc = sessionEffects.valueAt(index);
1316 } else {
1317 desc = new SuspendedSessionDesc();
1318 if (type != NULL) {
1319 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1320 }
1321 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001322 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001323 }
1324 desc->mRefCount++;
1325 } else {
1326 if (index < 0) {
1327 return;
1328 }
1329 desc = sessionEffects.valueAt(index);
1330 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001331 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001332 sessionEffects.removeItemsAt(index);
1333 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001335 sessionId);
1336 mSuspendedSessions.removeItem(sessionId);
1337 }
1338 }
1339 }
1340 if (!sessionEffects.isEmpty()) {
1341 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1342 }
1343}
1344
1345void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1346 bool enabled,
1347 int sessionId)
1348{
1349 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001350 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1351}
Eric Laurent59255e42011-07-27 19:49:51 -07001352
Eric Laurenta85a74a2011-10-19 11:44:54 -07001353void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1354 bool enabled,
1355 int sessionId)
1356{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001357 if (mType != RECORD) {
1358 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1359 // another session. This gives the priority to well behaved effect control panels
1360 // and applications not using global effects.
1361 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1362 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1363 }
1364 }
Eric Laurent59255e42011-07-27 19:49:51 -07001365
1366 sp<EffectChain> chain = getEffectChain_l(sessionId);
1367 if (chain != 0) {
1368 chain->checkSuspendOnEffectEnabled(effect, enabled);
1369 }
1370}
1371
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372// ----------------------------------------------------------------------------
1373
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001374AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1375 AudioStreamOut* output,
1376 int id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001377 uint32_t device,
1378 type_t type)
1379 : ThreadBase(audioFlinger, id, device, type),
Glenn Kastene0feee32011-12-13 11:53:26 -08001380 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001381 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001383 snprintf(mName, kNameLength, "AudioOut_%d", id);
1384
Mathias Agopian65ab4712010-07-14 17:59:35 -07001385 readOutputParameters();
1386
Glenn Kasten98067102011-12-13 11:47:54 -08001387 // Assumes constructor is called by AudioFlinger with it's mLock held,
1388 // but it would be safer to explicitly pass these as parameters
1389 mMasterVolume = mAudioFlinger->masterVolume_l();
1390 mMasterMute = mAudioFlinger->masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391
Glenn Kasten263709e2012-01-06 08:40:01 -08001392 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001393 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1394 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1395 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1397 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001398 // initialized by stream_type_t default constructor
1399 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400 }
1401}
1402
1403AudioFlinger::PlaybackThread::~PlaybackThread()
1404{
1405 delete [] mMixBuffer;
1406}
1407
1408status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1409{
1410 dumpInternals(fd, args);
1411 dumpTracks(fd, args);
1412 dumpEffectChains(fd, args);
1413 return NO_ERROR;
1414}
1415
1416status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1417{
1418 const size_t SIZE = 256;
1419 char buffer[SIZE];
1420 String8 result;
1421
1422 snprintf(buffer, SIZE, "Output thread %p 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 < mTracks.size(); ++i) {
1426 sp<Track> track = mTracks[i];
1427 if (track != 0) {
1428 track->dump(buffer, SIZE);
1429 result.append(buffer);
1430 }
1431 }
1432
1433 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1434 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001435 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 -07001436 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1437 wp<Track> wTrack = mActiveTracks[i];
1438 if (wTrack != 0) {
1439 sp<Track> track = wTrack.promote();
1440 if (track != 0) {
1441 track->dump(buffer, SIZE);
1442 result.append(buffer);
1443 }
1444 }
1445 }
1446 write(fd, result.string(), result.size());
1447 return NO_ERROR;
1448}
1449
Mathias Agopian65ab4712010-07-14 17:59:35 -07001450status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1451{
1452 const size_t SIZE = 256;
1453 char buffer[SIZE];
1454 String8 result;
1455
1456 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1457 result.append(buffer);
1458 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1459 result.append(buffer);
1460 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1461 result.append(buffer);
1462 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1463 result.append(buffer);
1464 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1465 result.append(buffer);
1466 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1467 result.append(buffer);
1468 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1469 result.append(buffer);
1470 write(fd, result.string(), result.size());
1471
1472 dumpBase(fd, args);
1473
1474 return NO_ERROR;
1475}
1476
1477// Thread virtuals
1478status_t AudioFlinger::PlaybackThread::readyToRun()
1479{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001480 status_t status = initCheck();
1481 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001482 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001483 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001484 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001486 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487}
1488
1489void AudioFlinger::PlaybackThread::onFirstRef()
1490{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001491 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492}
1493
1494// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1495sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1496 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001497 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001499 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001500 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 int frameCount,
1502 const sp<IMemory>& sharedBuffer,
1503 int sessionId,
1504 status_t *status)
1505{
1506 sp<Track> track;
1507 status_t lStatus;
1508
1509 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001510 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1511 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001512 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001513 "for output %p with format %d",
1514 sampleRate, format, channelMask, mOutput, mFormat);
1515 lStatus = BAD_VALUE;
1516 goto Exit;
1517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 }
1519 } else {
1520 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1521 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001522 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 lStatus = BAD_VALUE;
1524 goto Exit;
1525 }
1526 }
1527
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001528 lStatus = initCheck();
1529 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001530 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531 goto Exit;
1532 }
1533
1534 { // scope for mLock
1535 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001536
1537 // all tracks in same audio session must share the same routing strategy otherwise
1538 // conflicts will happen when tracks are moved from one output to another by audio policy
1539 // manager
1540 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001541 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001542 for (size_t i = 0; i < mTracks.size(); ++i) {
1543 sp<Track> t = mTracks[i];
1544 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001545 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1546 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001547 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001548 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001549 lStatus = BAD_VALUE;
1550 goto Exit;
1551 }
1552 }
1553 }
1554
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001556 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 if (track->getCblk() == NULL || track->name() < 0) {
1558 lStatus = NO_MEMORY;
1559 goto Exit;
1560 }
1561 mTracks.add(track);
1562
1563 sp<EffectChain> chain = getEffectChain_l(sessionId);
1564 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001565 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001567 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001568 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001570
1571 // invalidate track immediately if the stream type was moved to another thread since
1572 // createTrack() was called by the client process.
1573 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001574 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001575 this, streamType);
1576 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 }
1579 lStatus = NO_ERROR;
1580
1581Exit:
1582 if(status) {
1583 *status = lStatus;
1584 }
1585 return track;
1586}
1587
1588uint32_t AudioFlinger::PlaybackThread::latency() const
1589{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001590 Mutex::Autolock _l(mLock);
1591 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001592 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001593 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 return 0;
1595 }
1596}
1597
1598status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1599{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001600 mMasterVolume = value;
1601 return NO_ERROR;
1602}
1603
1604status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1605{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 mMasterMute = muted;
1607 return NO_ERROR;
1608}
1609
1610float AudioFlinger::PlaybackThread::masterVolume() const
1611{
1612 return mMasterVolume;
1613}
1614
1615bool AudioFlinger::PlaybackThread::masterMute() const
1616{
1617 return mMasterMute;
1618}
1619
Glenn Kastenfff6d712012-01-12 16:38:12 -08001620status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 mStreamTypes[stream].volume = value;
1623 return NO_ERROR;
1624}
1625
Glenn Kastenfff6d712012-01-12 16:38:12 -08001626status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001628 mStreamTypes[stream].mute = muted;
1629 return NO_ERROR;
1630}
1631
Glenn Kastenfff6d712012-01-12 16:38:12 -08001632float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633{
1634 return mStreamTypes[stream].volume;
1635}
1636
Glenn Kastenfff6d712012-01-12 16:38:12 -08001637bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638{
1639 return mStreamTypes[stream].mute;
1640}
1641
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642// addTrack_l() must be called with ThreadBase::mLock held
1643status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1644{
1645 status_t status = ALREADY_EXISTS;
1646
1647 // set retry count for buffer fill
1648 track->mRetryCount = kMaxTrackStartupRetries;
1649 if (mActiveTracks.indexOf(track) < 0) {
1650 // the track is newly added, make sure it fills up all its
1651 // buffers before playing. This is to ensure the client will
1652 // effectively get the latency it requested.
1653 track->mFillingUpStatus = Track::FS_FILLING;
1654 track->mResetDone = false;
1655 mActiveTracks.add(track);
1656 if (track->mainBuffer() != mMixBuffer) {
1657 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1658 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001659 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001660 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661 }
1662 }
1663
1664 status = NO_ERROR;
1665 }
1666
Steve Block3856b092011-10-20 11:56:00 +01001667 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001668 mWaitWorkCV.broadcast();
1669
1670 return status;
1671}
1672
1673// destroyTrack_l() must be called with ThreadBase::mLock held
1674void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1675{
1676 track->mState = TrackBase::TERMINATED;
1677 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001678 removeTrack_l(track);
1679 }
1680}
1681
1682void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1683{
1684 mTracks.remove(track);
1685 deleteTrackName_l(track->name());
1686 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1687 if (chain != 0) {
1688 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 }
1690}
1691
1692String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1693{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001694 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001695 char *s;
1696
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001697 Mutex::Autolock _l(mLock);
1698 if (initCheck() != NO_ERROR) {
1699 return out_s8;
1700 }
1701
Dima Zavin799a70e2011-04-18 16:57:27 -07001702 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001703 out_s8 = String8(s);
1704 free(s);
1705 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706}
1707
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001708// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1710 AudioSystem::OutputDescriptor desc;
1711 void *param2 = 0;
1712
Steve Block3856b092011-10-20 11:56:00 +01001713 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714
1715 switch (event) {
1716 case AudioSystem::OUTPUT_OPENED:
1717 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001718 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719 desc.samplingRate = mSampleRate;
1720 desc.format = mFormat;
1721 desc.frameCount = mFrameCount;
1722 desc.latency = latency();
1723 param2 = &desc;
1724 break;
1725
1726 case AudioSystem::STREAM_CONFIG_CHANGED:
1727 param2 = &param;
1728 case AudioSystem::OUTPUT_CLOSED:
1729 default:
1730 break;
1731 }
1732 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1733}
1734
1735void AudioFlinger::PlaybackThread::readOutputParameters()
1736{
Dima Zavin799a70e2011-04-18 16:57:27 -07001737 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001738 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1739 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001740 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001741 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001742 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743
1744 // FIXME - Current mixer implementation only supports stereo output: Always
1745 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001746 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 mMixBuffer = new int16_t[mFrameCount * 2];
1748 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1749
Eric Laurentde070132010-07-13 04:45:46 -07001750 // force reconfiguration of effect chains and engines to take new buffer size and audio
1751 // parameters into account
1752 // Note that mLock is not held when readOutputParameters() is called from the constructor
1753 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1754 // matter.
1755 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1756 Vector< sp<EffectChain> > effectChains = mEffectChains;
1757 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001758 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001760}
1761
1762status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1763{
1764 if (halFrames == 0 || dspFrames == 0) {
1765 return BAD_VALUE;
1766 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001767 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001768 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 return INVALID_OPERATION;
1770 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001771 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772
Dima Zavin799a70e2011-04-18 16:57:27 -07001773 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774}
1775
Eric Laurent39e94f82010-07-28 01:32:47 -07001776uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777{
1778 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001779 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001781 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001782 }
1783
1784 for (size_t i = 0; i < mTracks.size(); ++i) {
1785 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001786 if (sessionId == track->sessionId() &&
1787 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001788 result |= TRACK_SESSION;
1789 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 }
1791 }
1792
Eric Laurent39e94f82010-07-28 01:32:47 -07001793 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794}
1795
Eric Laurentde070132010-07-13 04:45:46 -07001796uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1797{
Dima Zavinfce7a472011-04-19 22:30:36 -07001798 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001799 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001800 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1801 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001802 }
1803 for (size_t i = 0; i < mTracks.size(); i++) {
1804 sp<Track> track = mTracks[i];
1805 if (sessionId == track->sessionId() &&
1806 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001807 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001808 }
1809 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001810 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001811}
1812
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813
Glenn Kastenaed850d2012-01-26 09:46:34 -08001814AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001815{
1816 Mutex::Autolock _l(mLock);
1817 return mOutput;
1818}
1819
1820AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1821{
1822 Mutex::Autolock _l(mLock);
1823 AudioStreamOut *output = mOutput;
1824 mOutput = NULL;
1825 return output;
1826}
1827
1828// this method must always be called either with ThreadBase mLock held or inside the thread loop
1829audio_stream_t* AudioFlinger::PlaybackThread::stream()
1830{
1831 if (mOutput == NULL) {
1832 return NULL;
1833 }
1834 return &mOutput->stream->common;
1835}
1836
Eric Laurent162b40b2011-12-05 09:47:19 -08001837uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1838{
1839 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1840 // decoding and transfer time. So sleeping for half of the latency would likely cause
1841 // underruns
1842 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1843 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1844 } else {
1845 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1846 }
1847}
1848
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849// ----------------------------------------------------------------------------
1850
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001851AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1852 int id, uint32_t device, type_t type)
1853 : PlaybackThread(audioFlinger, output, id, device, type),
Eric Laurentaeeb7e22012-01-19 10:00:02 -08001854 mAudioMixer(NULL), mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1857
1858 // FIXME - Current mixer implementation only supports stereo output
1859 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001860 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 }
1862}
1863
1864AudioFlinger::MixerThread::~MixerThread()
1865{
1866 delete mAudioMixer;
1867}
1868
1869bool AudioFlinger::MixerThread::threadLoop()
1870{
1871 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001872 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 nsecs_t standbyTime = systemTime();
1874 size_t mixBufferSize = mFrameCount * mFrameSize;
1875 // FIXME: Relaxed timing because of a certain device that can't meet latency
1876 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001877 // increase threshold again due to low power audio mode. The way this warning threshold is
1878 // calculated and its usefulness should be reconsidered anyway.
1879 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880 nsecs_t lastWarning = 0;
1881 bool longStandbyExit = false;
1882 uint32_t activeSleepTime = activeSleepTimeUs();
1883 uint32_t idleSleepTime = idleSleepTimeUs();
1884 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001885 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001886 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001887#ifdef DEBUG_CPU_USAGE
1888 ThreadCpuUsage cpu;
1889 const CentralTendencyStatistics& stats = cpu.statistics();
1890#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001891
Eric Laurentfeb0db62011-07-22 09:04:31 -07001892 acquireWakeLock();
1893
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 while (!exitPending())
1895 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001896#ifdef DEBUG_CPU_USAGE
1897 cpu.sampleAndEnable();
1898 unsigned n = stats.n();
1899 // cpu.elapsed() is expensive, so don't call it every loop
1900 if ((n & 127) == 1) {
1901 long long elapsed = cpu.elapsed();
1902 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1903 double perLoop = elapsed / (double) n;
1904 double perLoop100 = perLoop * 0.01;
1905 double mean = stats.mean();
1906 double stddev = stats.stddev();
1907 double minimum = stats.minimum();
1908 double maximum = stats.maximum();
1909 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001910 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 -07001911 elapsed * .000000001, n, perLoop * .000001,
1912 mean * .001,
1913 stddev * .001,
1914 minimum * .001,
1915 maximum * .001,
1916 mean / perLoop100,
1917 stddev / perLoop100,
1918 minimum / perLoop100,
1919 maximum / perLoop100);
1920 }
1921 }
1922#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 processConfigEvents();
1924
1925 mixerStatus = MIXER_IDLE;
1926 { // scope for mLock
1927
1928 Mutex::Autolock _l(mLock);
1929
1930 if (checkForNewParameters_l()) {
1931 mixBufferSize = mFrameCount * mFrameSize;
1932 // FIXME: Relaxed timing because of a certain device that can't meet latency
1933 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001934 // increase threshold again due to low power audio mode. The way this warning
1935 // threshold is calculated and its usefulness should be reconsidered anyway.
1936 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 activeSleepTime = activeSleepTimeUs();
1938 idleSleepTime = idleSleepTimeUs();
1939 }
1940
1941 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1942
1943 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001944 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1945 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001947 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001948 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 mStandby = true;
1950 mBytesWritten = 0;
1951 }
1952
1953 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1954 // we're about to wait, flush the binder command buffer
1955 IPCThreadState::self()->flushCommands();
1956
1957 if (exitPending()) break;
1958
Eric Laurentfeb0db62011-07-22 09:04:31 -07001959 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001961 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001963 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001964 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965
Eric Laurent27741442012-01-17 19:20:12 -08001966 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001967 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 char value[PROPERTY_VALUE_MAX];
1969 property_get("ro.audio.silent", value, "0");
1970 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001971 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 setMasterMute(true);
1973 }
1974 }
1975
1976 standbyTime = systemTime() + kStandbyTimeInNsecs;
1977 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001978 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979 continue;
1980 }
1981 }
1982
1983 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1984
1985 // prevent any changes in effect chain list and in each effect chain
1986 // during mixing and effect process as the audio buffers could be deleted
1987 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001988 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990
Glenn Kastenf6b16782011-12-15 09:51:17 -08001991 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992 // mix buffers...
1993 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001994 // increase sleep time progressively when application underrun condition clears.
1995 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1996 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1997 // such that we would underrun the audio HAL.
1998 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001999 sleepTimeShift--;
2000 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002001 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002002 standbyTime = systemTime() + kStandbyTimeInNsecs;
2003 //TODO: delay standby when effects have a tail
2004 } else {
2005 // If no tracks are ready, sleep once for the duration of an output
2006 // buffer size, then write 0s to the output
2007 if (sleepTime == 0) {
2008 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002009 sleepTime = activeSleepTime >> sleepTimeShift;
2010 if (sleepTime < kMinThreadSleepTimeUs) {
2011 sleepTime = kMinThreadSleepTimeUs;
2012 }
2013 // reduce sleep time in case of consecutive application underruns to avoid
2014 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2015 // duration we would end up writing less data than needed by the audio HAL if
2016 // the condition persists.
2017 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2018 sleepTimeShift++;
2019 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 } else {
2021 sleepTime = idleSleepTime;
2022 }
2023 } else if (mBytesWritten != 0 ||
2024 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2025 memset (mMixBuffer, 0, mixBufferSize);
2026 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002027 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 }
2029 // TODO add standby time extension fct of effect tail
2030 }
2031
2032 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002033 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 }
2035 // sleepTime == 0 means we must write to audio hardware
2036 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002037 for (size_t i = 0; i < effectChains.size(); i ++) {
2038 effectChains[i]->process_l();
2039 }
2040 // enable changes in effect chain
2041 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 mLastWriteTime = systemTime();
2043 mInWrite = true;
2044 mBytesWritten += mixBufferSize;
2045
Dima Zavin799a70e2011-04-18 16:57:27 -07002046 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2048 mNumWrites++;
2049 mInWrite = false;
2050 nsecs_t now = systemTime();
2051 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002052 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002054 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002055 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 ns2ms(delta), mNumDelayedWrites, this);
2057 lastWarning = now;
2058 }
2059 if (mStandby) {
2060 longStandbyExit = true;
2061 }
2062 }
2063 mStandby = false;
2064 } else {
2065 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002066 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 usleep(sleepTime);
2068 }
2069
2070 // finally let go of all our tracks, without the lock held
2071 // since we can't guarantee the destructors won't acquire that
2072 // same lock.
2073 tracksToRemove.clear();
2074
2075 // Effect chains will be actually deleted here if they were removed from
2076 // mEffectChains list during mixing or effects processing
2077 effectChains.clear();
2078 }
2079
2080 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002081 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 }
2083
Eric Laurentfeb0db62011-07-22 09:04:31 -07002084 releaseWakeLock();
2085
Steve Block3856b092011-10-20 11:56:00 +01002086 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 return false;
2088}
2089
2090// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002091AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2092 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093{
2094
Glenn Kasten29c23c32012-01-26 13:37:52 -08002095 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 // find out which tracks need to be processed
2097 size_t count = activeTracks.size();
2098 size_t mixedTracks = 0;
2099 size_t tracksWithEffect = 0;
2100
2101 float masterVolume = mMasterVolume;
2102 bool masterMute = mMasterMute;
2103
Eric Laurent571d49c2010-08-11 05:20:11 -07002104 if (masterMute) {
2105 masterVolume = 0;
2106 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002108 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002110 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002111 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 masterVolume = (float)((v + (1 << 23)) >> 24);
2113 chain.clear();
2114 }
2115
2116 for (size_t i=0 ; i<count ; i++) {
2117 sp<Track> t = activeTracks[i].promote();
2118 if (t == 0) continue;
2119
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002120 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 Track* const track = t.get();
2122 audio_track_cblk_t* cblk = track->cblk();
2123
2124 // The first time a track is added we wait
2125 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002126 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002127 // make sure that we have enough frames to mix one full buffer.
2128 // enforce this condition only once to enable draining the buffer in case the client
2129 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002130 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002131 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002132 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002133 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002134 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002135 if (t->sampleRate() == (int)mSampleRate) {
2136 minFrames = mFrameCount;
2137 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002138 // +1 for rounding and +1 for additional sample needed for interpolation
2139 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2140 // add frames already consumed but not yet released by the resampler
2141 // because cblk->framesReady() will include these frames
2142 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2143 // the minimum track buffer size is normally twice the number of frames necessary
2144 // to fill one buffer and the resampler should not leave more than one buffer worth
2145 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002146 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002147 }
2148 }
2149 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 !track->isPaused() && !track->isTerminated())
2151 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002152 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153
2154 mixedTracks++;
2155
2156 // track->mainBuffer() != mMixBuffer means there is an effect chain
2157 // connected to the track
2158 chain.clear();
2159 if (track->mainBuffer() != mMixBuffer) {
2160 chain = getEffectChain_l(track->sessionId());
2161 // Delegate volume control to effect in track effect chain if needed
2162 if (chain != 0) {
2163 tracksWithEffect++;
2164 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002165 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002166 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 }
2168 }
2169
2170
2171 int param = AudioMixer::VOLUME;
2172 if (track->mFillingUpStatus == Track::FS_FILLED) {
2173 // no ramp for the first volume setting
2174 track->mFillingUpStatus = Track::FS_ACTIVE;
2175 if (track->mState == TrackBase::RESUMING) {
2176 track->mState = TrackBase::ACTIVE;
2177 param = AudioMixer::RAMP_VOLUME;
2178 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002179 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 } else if (cblk->server != 0) {
2181 // If the track is stopped before the first frame was mixed,
2182 // do not apply ramp
2183 param = AudioMixer::RAMP_VOLUME;
2184 }
2185
2186 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002187 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002188 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002190 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 if (track->isPausing()) {
2192 track->setPaused();
2193 }
2194 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002195
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 // read original volumes with volume control
2197 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002199 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002200 vl = vlr & 0xFFFF;
2201 vr = vlr >> 16;
2202 // track volumes come from shared memory, so can't be trusted and must be clamped
2203 if (vl > MAX_GAIN_INT) {
2204 ALOGV("Track left volume out of range: %04X", vl);
2205 vl = MAX_GAIN_INT;
2206 }
2207 if (vr > MAX_GAIN_INT) {
2208 ALOGV("Track right volume out of range: %04X", vr);
2209 vr = MAX_GAIN_INT;
2210 }
2211 // now apply the master volume and stream type volume
2212 vl = (uint32_t)(v * vl) << 12;
2213 vr = (uint32_t)(v * vr) << 12;
2214 // assuming master volume and stream type volume each go up to 1.0,
2215 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216
Glenn Kasten05632a52012-01-03 14:22:33 -08002217 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2218 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002219 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002220 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002221 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002222 }
2223 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002225 // Delegate volume control to effect in track effect chain if needed
2226 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2227 // Do not ramp volume if volume is controlled by effect
2228 param = AudioMixer::VOLUME;
2229 track->mHasVolumeController = true;
2230 } else {
2231 // force no volume ramp when volume controller was just disabled or removed
2232 // from effect chain to avoid volume spike
2233 if (track->mHasVolumeController) {
2234 param = AudioMixer::VOLUME;
2235 }
2236 track->mHasVolumeController = false;
2237 }
2238
2239 // Convert volumes from 8.24 to 4.12 format
2240 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002241 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002242 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2243 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2244 left = int16_t(v_clamped);
2245 v_clamped = (vr + (1 << 11)) >> 12;
2246 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2247 right = int16_t(v_clamped);
2248
2249 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2250 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002253 mAudioMixer->setBufferProvider(name, track);
2254 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002256 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2257 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2258 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002260 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 AudioMixer::TRACK,
2262 AudioMixer::FORMAT, (void *)track->format());
2263 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002264 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002266 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002268 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269 AudioMixer::RESAMPLE,
2270 AudioMixer::SAMPLE_RATE,
2271 (void *)(cblk->sampleRate));
2272 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002273 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 AudioMixer::TRACK,
2275 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2276 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002277 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 AudioMixer::TRACK,
2279 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2280
2281 // reset retry count
2282 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002283 // If one track is ready, set the mixer ready if:
2284 // - the mixer was not ready during previous round OR
2285 // - no other track is not ready
2286 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2287 mixerStatus != MIXER_TRACKS_ENABLED) {
2288 mixerStatus = MIXER_TRACKS_READY;
2289 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002291 //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 -07002292 if (track->isStopped()) {
2293 track->reset();
2294 }
2295 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2296 // We have consumed all the buffers of this track.
2297 // Remove it from the list of active tracks.
2298 tracksToRemove->add(track);
2299 } else {
2300 // No buffers for this track. Give it a few chances to
2301 // fill a buffer, then remove it from active list.
2302 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002303 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002305 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002306 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002307 // If one track is not ready, mark the mixer also not ready if:
2308 // - the mixer was ready during previous round OR
2309 // - no other track is ready
2310 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2311 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 mixerStatus = MIXER_TRACKS_ENABLED;
2313 }
2314 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002315 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 }
2317 }
2318
2319 // remove all the tracks that need to be...
2320 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002321 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 for (size_t i=0 ; i<count ; i++) {
2323 const sp<Track>& track = tracksToRemove->itemAt(i);
2324 mActiveTracks.remove(track);
2325 if (track->mainBuffer() != mMixBuffer) {
2326 chain = getEffectChain_l(track->sessionId());
2327 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002328 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002329 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 }
2331 }
2332 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002333 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 }
2335 }
2336 }
2337
2338 // mix buffer must be cleared if all tracks are connected to an
2339 // effect chain as in this case the mixer will not write to
2340 // mix buffer and track effects will accumulate into it
2341 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2342 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2343 }
2344
Eric Laurent27741442012-01-17 19:20:12 -08002345 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 return mixerStatus;
2347}
2348
Glenn Kastenfff6d712012-01-12 16:38:12 -08002349void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002350{
Steve Block3856b092011-10-20 11:56:00 +01002351 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002352 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002354
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 size_t size = mTracks.size();
2356 for (size_t i = 0; i < size; i++) {
2357 sp<Track> t = mTracks[i];
2358 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002359 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 }
2362 }
2363}
2364
Glenn Kastenfff6d712012-01-12 16:38:12 -08002365void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002366{
Steve Block3856b092011-10-20 11:56:00 +01002367 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002368 this, streamType, valid);
2369 Mutex::Autolock _l(mLock);
2370
2371 mStreamTypes[streamType].valid = valid;
2372}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002373
2374// getTrackName_l() must be called with ThreadBase::mLock held
2375int AudioFlinger::MixerThread::getTrackName_l()
2376{
2377 return mAudioMixer->getTrackName();
2378}
2379
2380// deleteTrackName_l() must be called with ThreadBase::mLock held
2381void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2382{
Steve Block3856b092011-10-20 11:56:00 +01002383 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 mAudioMixer->deleteTrackName(name);
2385}
2386
2387// checkForNewParameters_l() must be called with ThreadBase::mLock held
2388bool AudioFlinger::MixerThread::checkForNewParameters_l()
2389{
2390 bool reconfig = false;
2391
2392 while (!mNewParameters.isEmpty()) {
2393 status_t status = NO_ERROR;
2394 String8 keyValuePair = mNewParameters[0];
2395 AudioParameter param = AudioParameter(keyValuePair);
2396 int value;
2397
2398 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2399 reconfig = true;
2400 }
2401 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002402 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 status = BAD_VALUE;
2404 } else {
2405 reconfig = true;
2406 }
2407 }
2408 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002409 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 status = BAD_VALUE;
2411 } else {
2412 reconfig = true;
2413 }
2414 }
2415 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2416 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002417 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002418 // if frame count is changed after track creation
2419 if (!mTracks.isEmpty()) {
2420 status = INVALID_OPERATION;
2421 } else {
2422 reconfig = true;
2423 }
2424 }
2425 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002426 // when changing the audio output device, call addBatteryData to notify
2427 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002428 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002429 uint32_t params = 0;
2430 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002431 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002432 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2433 }
2434
2435 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002436 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002437 // check if any other device (except speaker) is on
2438 if (value & deviceWithoutSpeaker ) {
2439 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2440 }
2441
2442 if (params != 0) {
2443 addBatteryData(params);
2444 }
2445 }
2446
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 // forward device change to effects that have requested to be
2448 // aware of attached audio device.
2449 mDevice = (uint32_t)value;
2450 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002451 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452 }
2453 }
2454
2455 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002456 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002457 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002459 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 mStandby = true;
2461 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002462 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002463 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464 }
2465 if (status == NO_ERROR && reconfig) {
2466 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002467 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2468 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469 readOutputParameters();
2470 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2471 for (size_t i = 0; i < mTracks.size() ; i++) {
2472 int name = getTrackName_l();
2473 if (name < 0) break;
2474 mTracks[i]->mName = name;
2475 // limit track sample rate to 2 x new output sample rate
2476 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2477 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2478 }
2479 }
2480 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2481 }
2482 }
2483
2484 mNewParameters.removeAt(0);
2485
2486 mParamStatus = status;
2487 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002488 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2489 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002490 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491 }
2492 return reconfig;
2493}
2494
2495status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2496{
2497 const size_t SIZE = 256;
2498 char buffer[SIZE];
2499 String8 result;
2500
2501 PlaybackThread::dumpInternals(fd, args);
2502
2503 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2504 result.append(buffer);
2505 write(fd, result.string(), result.size());
2506 return NO_ERROR;
2507}
2508
Mathias Agopian65ab4712010-07-14 17:59:35 -07002509uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2510{
Eric Laurent60e18242010-07-29 06:50:24 -07002511 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512}
2513
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002514uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2515{
2516 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2517}
2518
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002520AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002521 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523}
2524
2525AudioFlinger::DirectOutputThread::~DirectOutputThread()
2526{
2527}
2528
Mathias Agopian65ab4712010-07-14 17:59:35 -07002529static inline
2530int32_t mul(int16_t in, int16_t v)
2531{
2532#if defined(__arm__) && !defined(__thumb__)
2533 int32_t out;
2534 asm( "smulbb %[out], %[in], %[v] \n"
2535 : [out]"=r"(out)
2536 : [in]"%r"(in), [v]"r"(v)
2537 : );
2538 return out;
2539#else
2540 return in * int32_t(v);
2541#endif
2542}
2543
2544void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2545{
2546 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002547 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 return;
2549 }
2550
2551 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002552 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002553 size_t count = mFrameCount * mChannelCount;
2554 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2555 int16_t *dst = mMixBuffer + count-1;
2556 while(count--) {
2557 *dst-- = (int16_t)(*src--^0x80) << 8;
2558 }
2559 }
2560
2561 size_t frameCount = mFrameCount;
2562 int16_t *out = mMixBuffer;
2563 if (ramp) {
2564 if (mChannelCount == 1) {
2565 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2566 int32_t vlInc = d / (int32_t)frameCount;
2567 int32_t vl = ((int32_t)mLeftVolShort << 16);
2568 do {
2569 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2570 out++;
2571 vl += vlInc;
2572 } while (--frameCount);
2573
2574 } else {
2575 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2576 int32_t vlInc = d / (int32_t)frameCount;
2577 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2578 int32_t vrInc = d / (int32_t)frameCount;
2579 int32_t vl = ((int32_t)mLeftVolShort << 16);
2580 int32_t vr = ((int32_t)mRightVolShort << 16);
2581 do {
2582 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2583 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2584 out += 2;
2585 vl += vlInc;
2586 vr += vrInc;
2587 } while (--frameCount);
2588 }
2589 } else {
2590 if (mChannelCount == 1) {
2591 do {
2592 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2593 out++;
2594 } while (--frameCount);
2595 } else {
2596 do {
2597 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2598 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2599 out += 2;
2600 } while (--frameCount);
2601 }
2602 }
2603
2604 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002605 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 size_t count = mFrameCount * mChannelCount;
2607 int16_t *src = mMixBuffer;
2608 uint8_t *dst = (uint8_t *)mMixBuffer;
2609 while(count--) {
2610 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2611 }
2612 }
2613
2614 mLeftVolShort = leftVol;
2615 mRightVolShort = rightVol;
2616}
2617
2618bool AudioFlinger::DirectOutputThread::threadLoop()
2619{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002620 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 sp<Track> trackToRemove;
2622 sp<Track> activeTrack;
2623 nsecs_t standbyTime = systemTime();
2624 int8_t *curBuf;
2625 size_t mixBufferSize = mFrameCount*mFrameSize;
2626 uint32_t activeSleepTime = activeSleepTimeUs();
2627 uint32_t idleSleepTime = idleSleepTimeUs();
2628 uint32_t sleepTime = idleSleepTime;
2629 // use shorter standby delay as on normal output to release
2630 // hardware resources as soon as possible
2631 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2632
Eric Laurentfeb0db62011-07-22 09:04:31 -07002633 acquireWakeLock();
2634
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 while (!exitPending())
2636 {
2637 bool rampVolume;
2638 uint16_t leftVol;
2639 uint16_t rightVol;
2640 Vector< sp<EffectChain> > effectChains;
2641
2642 processConfigEvents();
2643
2644 mixerStatus = MIXER_IDLE;
2645
2646 { // scope for the mLock
2647
2648 Mutex::Autolock _l(mLock);
2649
2650 if (checkForNewParameters_l()) {
2651 mixBufferSize = mFrameCount*mFrameSize;
2652 activeSleepTime = activeSleepTimeUs();
2653 idleSleepTime = idleSleepTimeUs();
2654 standbyDelay = microseconds(activeSleepTime*2);
2655 }
2656
2657 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002658 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2659 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 // wait until we have something to do...
2661 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002662 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002663 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 mStandby = true;
2665 mBytesWritten = 0;
2666 }
2667
2668 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2669 // we're about to wait, flush the binder command buffer
2670 IPCThreadState::self()->flushCommands();
2671
2672 if (exitPending()) break;
2673
Eric Laurentfeb0db62011-07-22 09:04:31 -07002674 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002675 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002676 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002677 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002678 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679
Glenn Kastenf1d45922012-01-13 15:54:24 -08002680 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002681 char value[PROPERTY_VALUE_MAX];
2682 property_get("ro.audio.silent", value, "0");
2683 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002684 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 setMasterMute(true);
2686 }
2687 }
2688
2689 standbyTime = systemTime() + standbyDelay;
2690 sleepTime = idleSleepTime;
2691 continue;
2692 }
2693 }
2694
2695 effectChains = mEffectChains;
2696
2697 // find out which tracks need to be processed
2698 if (mActiveTracks.size() != 0) {
2699 sp<Track> t = mActiveTracks[0].promote();
2700 if (t == 0) continue;
2701
2702 Track* const track = t.get();
2703 audio_track_cblk_t* cblk = track->cblk();
2704
2705 // The first time a track is added we wait
2706 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002707 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 !track->isPaused() && !track->isTerminated())
2709 {
Steve Block3856b092011-10-20 11:56:00 +01002710 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002711
2712 if (track->mFillingUpStatus == Track::FS_FILLED) {
2713 track->mFillingUpStatus = Track::FS_ACTIVE;
2714 mLeftVolFloat = mRightVolFloat = 0;
2715 mLeftVolShort = mRightVolShort = 0;
2716 if (track->mState == TrackBase::RESUMING) {
2717 track->mState = TrackBase::ACTIVE;
2718 rampVolume = true;
2719 }
2720 } else if (cblk->server != 0) {
2721 // If the track is stopped before the first frame was mixed,
2722 // do not apply ramp
2723 rampVolume = true;
2724 }
2725 // compute volume for this track
2726 float left, right;
2727 if (track->isMuted() || mMasterMute || track->isPausing() ||
2728 mStreamTypes[track->type()].mute) {
2729 left = right = 0;
2730 if (track->isPausing()) {
2731 track->setPaused();
2732 }
2733 } else {
2734 float typeVolume = mStreamTypes[track->type()].volume;
2735 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002736 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002737 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2739 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002740 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2742 right = v_clamped/MAX_GAIN;
2743 }
2744
2745 if (left != mLeftVolFloat || right != mRightVolFloat) {
2746 mLeftVolFloat = left;
2747 mRightVolFloat = right;
2748
2749 // If audio HAL implements volume control,
2750 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002751 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752 left = 1.0f;
2753 right = 1.0f;
2754 }
2755
2756 // Convert volumes from float to 8.24
2757 uint32_t vl = (uint32_t)(left * (1 << 24));
2758 uint32_t vr = (uint32_t)(right * (1 << 24));
2759
2760 // Delegate volume control to effect in track effect chain if needed
2761 // only one effect chain can be present on DirectOutputThread, so if
2762 // there is one, the track is connected to it
2763 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002764 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002765 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 rampVolume = false;
2767 }
2768 }
2769
2770 // Convert volumes from 8.24 to 4.12 format
2771 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2772 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2773 leftVol = (uint16_t)v_clamped;
2774 v_clamped = (vr + (1 << 11)) >> 12;
2775 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2776 rightVol = (uint16_t)v_clamped;
2777 } else {
2778 leftVol = mLeftVolShort;
2779 rightVol = mRightVolShort;
2780 rampVolume = false;
2781 }
2782
2783 // reset retry count
2784 track->mRetryCount = kMaxTrackRetriesDirect;
2785 activeTrack = t;
2786 mixerStatus = MIXER_TRACKS_READY;
2787 } else {
Steve Block3856b092011-10-20 11:56:00 +01002788 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 if (track->isStopped()) {
2790 track->reset();
2791 }
2792 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2793 // We have consumed all the buffers of this track.
2794 // Remove it from the list of active tracks.
2795 trackToRemove = track;
2796 } else {
2797 // No buffers for this track. Give it a few chances to
2798 // fill a buffer, then remove it from active list.
2799 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002800 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 trackToRemove = track;
2802 } else {
2803 mixerStatus = MIXER_TRACKS_ENABLED;
2804 }
2805 }
2806 }
2807 }
2808
2809 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002810 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002811 mActiveTracks.remove(trackToRemove);
2812 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002813 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002814 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002815 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816 }
2817 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002818 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002819 }
2820 }
2821
Eric Laurentde070132010-07-13 04:45:46 -07002822 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 }
2824
Glenn Kastenf6b16782011-12-15 09:51:17 -08002825 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 AudioBufferProvider::Buffer buffer;
2827 size_t frameCount = mFrameCount;
2828 curBuf = (int8_t *)mMixBuffer;
2829 // output audio to hardware
2830 while (frameCount) {
2831 buffer.frameCount = frameCount;
2832 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002833 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 memset(curBuf, 0, frameCount * mFrameSize);
2835 break;
2836 }
2837 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2838 frameCount -= buffer.frameCount;
2839 curBuf += buffer.frameCount * mFrameSize;
2840 activeTrack->releaseBuffer(&buffer);
2841 }
2842 sleepTime = 0;
2843 standbyTime = systemTime() + standbyDelay;
2844 } else {
2845 if (sleepTime == 0) {
2846 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2847 sleepTime = activeSleepTime;
2848 } else {
2849 sleepTime = idleSleepTime;
2850 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002851 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2853 sleepTime = 0;
2854 }
2855 }
2856
2857 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002858 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859 }
2860 // sleepTime == 0 means we must write to audio hardware
2861 if (sleepTime == 0) {
2862 if (mixerStatus == MIXER_TRACKS_READY) {
2863 applyVolume(leftVol, rightVol, rampVolume);
2864 }
2865 for (size_t i = 0; i < effectChains.size(); i ++) {
2866 effectChains[i]->process_l();
2867 }
Eric Laurentde070132010-07-13 04:45:46 -07002868 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869
2870 mLastWriteTime = systemTime();
2871 mInWrite = true;
2872 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002873 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2875 mNumWrites++;
2876 mInWrite = false;
2877 mStandby = false;
2878 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002879 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 usleep(sleepTime);
2881 }
2882
2883 // finally let go of removed track, without the lock held
2884 // since we can't guarantee the destructors won't acquire that
2885 // same lock.
2886 trackToRemove.clear();
2887 activeTrack.clear();
2888
2889 // Effect chains will be actually deleted here if they were removed from
2890 // mEffectChains list during mixing or effects processing
2891 effectChains.clear();
2892 }
2893
2894 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002895 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 }
2897
Eric Laurentfeb0db62011-07-22 09:04:31 -07002898 releaseWakeLock();
2899
Steve Block3856b092011-10-20 11:56:00 +01002900 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901 return false;
2902}
2903
2904// getTrackName_l() must be called with ThreadBase::mLock held
2905int AudioFlinger::DirectOutputThread::getTrackName_l()
2906{
2907 return 0;
2908}
2909
2910// deleteTrackName_l() must be called with ThreadBase::mLock held
2911void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2912{
2913}
2914
2915// checkForNewParameters_l() must be called with ThreadBase::mLock held
2916bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2917{
2918 bool reconfig = false;
2919
2920 while (!mNewParameters.isEmpty()) {
2921 status_t status = NO_ERROR;
2922 String8 keyValuePair = mNewParameters[0];
2923 AudioParameter param = AudioParameter(keyValuePair);
2924 int value;
2925
2926 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2927 // do not accept frame count changes if tracks are open as the track buffer
2928 // size depends on frame count and correct behavior would not be garantied
2929 // if frame count is changed after track creation
2930 if (!mTracks.isEmpty()) {
2931 status = INVALID_OPERATION;
2932 } else {
2933 reconfig = true;
2934 }
2935 }
2936 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002937 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002938 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002939 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002940 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 mStandby = true;
2942 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002943 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002944 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 }
2946 if (status == NO_ERROR && reconfig) {
2947 readOutputParameters();
2948 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2949 }
2950 }
2951
2952 mNewParameters.removeAt(0);
2953
2954 mParamStatus = status;
2955 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002956 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2957 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002958 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 }
2960 return reconfig;
2961}
2962
2963uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2964{
2965 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002966 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002967 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968 } else {
2969 time = 10000;
2970 }
2971 return time;
2972}
2973
2974uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2975{
2976 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002977 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002978 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 } else {
2980 time = 10000;
2981 }
2982 return time;
2983}
2984
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002985uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2986{
2987 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002988 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002989 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2990 } else {
2991 time = 10000;
2992 }
2993 return time;
2994}
2995
2996
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997// ----------------------------------------------------------------------------
2998
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002999AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3000 AudioFlinger::MixerThread* mainThread, int id)
3001 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3002 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003004 addOutputTrack(mainThread);
3005}
3006
3007AudioFlinger::DuplicatingThread::~DuplicatingThread()
3008{
3009 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3010 mOutputTracks[i]->destroy();
3011 }
3012 mOutputTracks.clear();
3013}
3014
3015bool AudioFlinger::DuplicatingThread::threadLoop()
3016{
3017 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003018 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 nsecs_t standbyTime = systemTime();
3020 size_t mixBufferSize = mFrameCount*mFrameSize;
3021 SortedVector< sp<OutputTrack> > outputTracks;
3022 uint32_t writeFrames = 0;
3023 uint32_t activeSleepTime = activeSleepTimeUs();
3024 uint32_t idleSleepTime = idleSleepTimeUs();
3025 uint32_t sleepTime = idleSleepTime;
3026 Vector< sp<EffectChain> > effectChains;
3027
Eric Laurentfeb0db62011-07-22 09:04:31 -07003028 acquireWakeLock();
3029
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 while (!exitPending())
3031 {
3032 processConfigEvents();
3033
3034 mixerStatus = MIXER_IDLE;
3035 { // scope for the mLock
3036
3037 Mutex::Autolock _l(mLock);
3038
3039 if (checkForNewParameters_l()) {
3040 mixBufferSize = mFrameCount*mFrameSize;
3041 updateWaitTime();
3042 activeSleepTime = activeSleepTimeUs();
3043 idleSleepTime = idleSleepTimeUs();
3044 }
3045
3046 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3047
3048 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3049 outputTracks.add(mOutputTracks[i]);
3050 }
3051
3052 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003053 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3054 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 if (!mStandby) {
3056 for (size_t i = 0; i < outputTracks.size(); i++) {
3057 outputTracks[i]->stop();
3058 }
3059 mStandby = true;
3060 mBytesWritten = 0;
3061 }
3062
3063 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3064 // we're about to wait, flush the binder command buffer
3065 IPCThreadState::self()->flushCommands();
3066 outputTracks.clear();
3067
3068 if (exitPending()) break;
3069
Eric Laurentfeb0db62011-07-22 09:04:31 -07003070 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003071 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003073 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003074 acquireWakeLock_l();
3075
Eric Laurent27741442012-01-17 19:20:12 -08003076 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003077 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 char value[PROPERTY_VALUE_MAX];
3079 property_get("ro.audio.silent", value, "0");
3080 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003081 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 setMasterMute(true);
3083 }
3084 }
3085
3086 standbyTime = systemTime() + kStandbyTimeInNsecs;
3087 sleepTime = idleSleepTime;
3088 continue;
3089 }
3090 }
3091
3092 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3093
3094 // prevent any changes in effect chain list and in each effect chain
3095 // during mixing and effect process as the audio buffers could be deleted
3096 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003097 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 }
3099
Glenn Kastenf6b16782011-12-15 09:51:17 -08003100 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101 // mix buffers...
3102 if (outputsReady(outputTracks)) {
3103 mAudioMixer->process();
3104 } else {
3105 memset(mMixBuffer, 0, mixBufferSize);
3106 }
3107 sleepTime = 0;
3108 writeFrames = mFrameCount;
3109 } else {
3110 if (sleepTime == 0) {
3111 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3112 sleepTime = activeSleepTime;
3113 } else {
3114 sleepTime = idleSleepTime;
3115 }
3116 } else if (mBytesWritten != 0) {
3117 // flush remaining overflow buffers in output tracks
3118 for (size_t i = 0; i < outputTracks.size(); i++) {
3119 if (outputTracks[i]->isActive()) {
3120 sleepTime = 0;
3121 writeFrames = 0;
3122 memset(mMixBuffer, 0, mixBufferSize);
3123 break;
3124 }
3125 }
3126 }
3127 }
3128
3129 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003130 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131 }
3132 // sleepTime == 0 means we must write to audio hardware
3133 if (sleepTime == 0) {
3134 for (size_t i = 0; i < effectChains.size(); i ++) {
3135 effectChains[i]->process_l();
3136 }
3137 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003138 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139
3140 standbyTime = systemTime() + kStandbyTimeInNsecs;
3141 for (size_t i = 0; i < outputTracks.size(); i++) {
3142 outputTracks[i]->write(mMixBuffer, writeFrames);
3143 }
3144 mStandby = false;
3145 mBytesWritten += mixBufferSize;
3146 } else {
3147 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003148 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 usleep(sleepTime);
3150 }
3151
3152 // finally let go of all our tracks, without the lock held
3153 // since we can't guarantee the destructors won't acquire that
3154 // same lock.
3155 tracksToRemove.clear();
3156 outputTracks.clear();
3157
3158 // Effect chains will be actually deleted here if they were removed from
3159 // mEffectChains list during mixing or effects processing
3160 effectChains.clear();
3161 }
3162
Eric Laurentfeb0db62011-07-22 09:04:31 -07003163 releaseWakeLock();
3164
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 return false;
3166}
3167
3168void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3169{
3170 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3171 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3172 this,
3173 mSampleRate,
3174 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003175 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003176 frameCount);
3177 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003178 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003180 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 updateWaitTime();
3182 }
3183}
3184
3185void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3186{
3187 Mutex::Autolock _l(mLock);
3188 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3189 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3190 mOutputTracks[i]->destroy();
3191 mOutputTracks.removeAt(i);
3192 updateWaitTime();
3193 return;
3194 }
3195 }
Steve Block3856b092011-10-20 11:56:00 +01003196 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197}
3198
3199void AudioFlinger::DuplicatingThread::updateWaitTime()
3200{
3201 mWaitTimeMs = UINT_MAX;
3202 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3203 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3204 if (strong != NULL) {
3205 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3206 if (waitTimeMs < mWaitTimeMs) {
3207 mWaitTimeMs = waitTimeMs;
3208 }
3209 }
3210 }
3211}
3212
3213
3214bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3215{
3216 for (size_t i = 0; i < outputTracks.size(); i++) {
3217 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3218 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003219 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 return false;
3221 }
3222 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3223 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003224 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 return false;
3226 }
3227 }
3228 return true;
3229}
3230
3231uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3232{
3233 return (mWaitTimeMs * 1000) / 2;
3234}
3235
3236// ----------------------------------------------------------------------------
3237
3238// TrackBase constructor must be called with AudioFlinger::mLock held
3239AudioFlinger::ThreadBase::TrackBase::TrackBase(
3240 const wp<ThreadBase>& thread,
3241 const sp<Client>& client,
3242 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003243 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003244 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 int frameCount,
3246 uint32_t flags,
3247 const sp<IMemory>& sharedBuffer,
3248 int sessionId)
3249 : RefBase(),
3250 mThread(thread),
3251 mClient(client),
3252 mCblk(0),
3253 mFrameCount(0),
3254 mState(IDLE),
3255 mClientTid(-1),
3256 mFormat(format),
3257 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3258 mSessionId(sessionId)
3259{
Steve Block3856b092011-10-20 11:56:00 +01003260 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261
Steve Blockb8a80522011-12-20 16:23:08 +00003262 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003264 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3266 if (sharedBuffer == 0) {
3267 size += bufferSize;
3268 }
3269
3270 if (client != NULL) {
3271 mCblkMemory = client->heap()->allocate(size);
3272 if (mCblkMemory != 0) {
3273 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3274 if (mCblk) { // construct the shared structure in-place.
3275 new(mCblk) audio_track_cblk_t();
3276 // clear all buffers
3277 mCblk->frameCount = frameCount;
3278 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003279 mChannelCount = channelCount;
3280 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 if (sharedBuffer == 0) {
3282 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3283 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3284 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003285 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 mCblk->flags = CBLK_UNDERRUN_ON;
3287 } else {
3288 mBuffer = sharedBuffer->pointer();
3289 }
3290 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3291 }
3292 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003293 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 client->heap()->dump("AudioTrack");
3295 return;
3296 }
3297 } else {
3298 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003299 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 new(mCblk) audio_track_cblk_t();
3301 // clear all buffers
3302 mCblk->frameCount = frameCount;
3303 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003304 mChannelCount = channelCount;
3305 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003306 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3307 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3308 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003309 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003310 mCblk->flags = CBLK_UNDERRUN_ON;
3311 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 }
3313}
3314
3315AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3316{
3317 if (mCblk) {
3318 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3319 if (mClient == NULL) {
3320 delete mCblk;
3321 }
3322 }
3323 mCblkMemory.clear(); // and free the shared memory
3324 if (mClient != NULL) {
3325 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3326 mClient.clear();
3327 }
3328}
3329
3330void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3331{
Glenn Kastene0feee32011-12-13 11:53:26 -08003332 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003333 mFrameCount = buffer->frameCount;
3334 step();
3335 buffer->frameCount = 0;
3336}
3337
3338bool AudioFlinger::ThreadBase::TrackBase::step() {
3339 bool result;
3340 audio_track_cblk_t* cblk = this->cblk();
3341
3342 result = cblk->stepServer(mFrameCount);
3343 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003344 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 mFlags |= STEPSERVER_FAILED;
3346 }
3347 return result;
3348}
3349
3350void AudioFlinger::ThreadBase::TrackBase::reset() {
3351 audio_track_cblk_t* cblk = this->cblk();
3352
3353 cblk->user = 0;
3354 cblk->server = 0;
3355 cblk->userBase = 0;
3356 cblk->serverBase = 0;
3357 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003358 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359}
3360
3361sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3362{
3363 return mCblkMemory;
3364}
3365
3366int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3367 return (int)mCblk->sampleRate;
3368}
3369
3370int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003371 return (const int)mChannelCount;
3372}
3373
3374uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3375 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376}
3377
3378void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3379 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003380 size_t frameSize = cblk->frameSize;
3381 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3382 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383
3384 // Check validity of returned pointer in case the track control block would have been corrupted.
3385 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003386 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003387 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 -07003388 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003390 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 return 0;
3392 }
3393
3394 return bufferStart;
3395}
3396
3397// ----------------------------------------------------------------------------
3398
3399// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3400AudioFlinger::PlaybackThread::Track::Track(
3401 const wp<ThreadBase>& thread,
3402 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003403 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003405 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003406 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 int frameCount,
3408 const sp<IMemory>& sharedBuffer,
3409 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003410 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003411 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3412 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003413{
3414 if (mCblk != NULL) {
3415 sp<ThreadBase> baseThread = thread.promote();
3416 if (baseThread != 0) {
3417 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3418 mName = playbackThread->getTrackName_l();
3419 mMainBuffer = playbackThread->mixBuffer();
3420 }
Steve Block3856b092011-10-20 11:56:00 +01003421 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003423 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 mStreamType = streamType;
3426 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3427 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003428 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
3430}
3431
3432AudioFlinger::PlaybackThread::Track::~Track()
3433{
Steve Block3856b092011-10-20 11:56:00 +01003434 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003435 sp<ThreadBase> thread = mThread.promote();
3436 if (thread != 0) {
3437 Mutex::Autolock _l(thread->mLock);
3438 mState = TERMINATED;
3439 }
3440}
3441
3442void AudioFlinger::PlaybackThread::Track::destroy()
3443{
3444 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3445 // by removing it from mTracks vector, so there is a risk that this Tracks's
3446 // desctructor is called. As the destructor needs to lock mLock,
3447 // we must acquire a strong reference on this Track before locking mLock
3448 // here so that the destructor is called only when exiting this function.
3449 // On the other hand, as long as Track::destroy() is only called by
3450 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3451 // this Track with its member mTrack.
3452 sp<Track> keep(this);
3453 { // scope for mLock
3454 sp<ThreadBase> thread = mThread.promote();
3455 if (thread != 0) {
3456 if (!isOutputTrack()) {
3457 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003458 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003459 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003460 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003461
3462 // to track the speaker usage
3463 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 }
3465 AudioSystem::releaseOutput(thread->id());
3466 }
3467 Mutex::Autolock _l(thread->mLock);
3468 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3469 playbackThread->destroyTrack_l(this);
3470 }
3471 }
3472}
3473
3474void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3475{
Glenn Kasten83d86532012-01-17 14:39:34 -08003476 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003477 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 -07003478 mName - AudioMixer::TRACK0,
3479 (mClient == NULL) ? getpid() : mClient->pid(),
3480 mStreamType,
3481 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003482 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 mSessionId,
3484 mFrameCount,
3485 mState,
3486 mMute,
3487 mFillingUpStatus,
3488 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003489 vlr & 0xFFFF,
3490 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003491 mCblk->server,
3492 mCblk->user,
3493 (int)mMainBuffer,
3494 (int)mAuxBuffer);
3495}
3496
3497status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3498{
3499 audio_track_cblk_t* cblk = this->cblk();
3500 uint32_t framesReady;
3501 uint32_t framesReq = buffer->frameCount;
3502
3503 // Check if last stepServer failed, try to step now
3504 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3505 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003506 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3508 }
3509
3510 framesReady = cblk->framesReady();
3511
Glenn Kastenf6b16782011-12-15 09:51:17 -08003512 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 uint32_t s = cblk->server;
3514 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3515
3516 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3517 if (framesReq > framesReady) {
3518 framesReq = framesReady;
3519 }
3520 if (s + framesReq > bufferEnd) {
3521 framesReq = bufferEnd - s;
3522 }
3523
3524 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003525 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526
3527 buffer->frameCount = framesReq;
3528 return NO_ERROR;
3529 }
3530
3531getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003532 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003534 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 return NOT_ENOUGH_DATA;
3536}
3537
3538bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003539 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540
3541 if (mCblk->framesReady() >= mCblk->frameCount ||
3542 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3543 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003544 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 return true;
3546 }
3547 return false;
3548}
3549
3550status_t AudioFlinger::PlaybackThread::Track::start()
3551{
3552 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003553 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003554 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555 sp<ThreadBase> thread = mThread.promote();
3556 if (thread != 0) {
3557 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003558 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559 // here the track could be either new, or restarted
3560 // in both cases "unstop" the track
3561 if (mState == PAUSED) {
3562 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003563 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 } else {
3565 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003566 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 }
3568
3569 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3570 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003571 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003572 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003573 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003575
3576 // to track the speaker usage
3577 if (status == NO_ERROR) {
3578 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3579 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 }
3581 if (status == NO_ERROR) {
3582 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3583 playbackThread->addTrack_l(this);
3584 } else {
3585 mState = state;
3586 }
3587 } else {
3588 status = BAD_VALUE;
3589 }
3590 return status;
3591}
3592
3593void AudioFlinger::PlaybackThread::Track::stop()
3594{
Steve Block3856b092011-10-20 11:56:00 +01003595 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 sp<ThreadBase> thread = mThread.promote();
3597 if (thread != 0) {
3598 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003599 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 if (mState > STOPPED) {
3601 mState = STOPPED;
3602 // If the track is not active (PAUSED and buffers full), flush buffers
3603 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3604 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3605 reset();
3606 }
Steve Block3856b092011-10-20 11:56:00 +01003607 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 }
3609 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3610 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003611 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003612 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003613 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003615
3616 // to track the speaker usage
3617 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 }
3619 }
3620}
3621
3622void AudioFlinger::PlaybackThread::Track::pause()
3623{
Steve Block3856b092011-10-20 11:56:00 +01003624 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003625 sp<ThreadBase> thread = mThread.promote();
3626 if (thread != 0) {
3627 Mutex::Autolock _l(thread->mLock);
3628 if (mState == ACTIVE || mState == RESUMING) {
3629 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003630 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631 if (!isOutputTrack()) {
3632 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003633 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003634 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003635 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003637
3638 // to track the speaker usage
3639 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640 }
3641 }
3642 }
3643}
3644
3645void AudioFlinger::PlaybackThread::Track::flush()
3646{
Steve Block3856b092011-10-20 11:56:00 +01003647 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648 sp<ThreadBase> thread = mThread.promote();
3649 if (thread != 0) {
3650 Mutex::Autolock _l(thread->mLock);
3651 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3652 return;
3653 }
3654 // No point remaining in PAUSED state after a flush => go to
3655 // STOPPED state
3656 mState = STOPPED;
3657
Eric Laurent38ccae22011-03-28 18:37:07 -07003658 // do not reset the track if it is still in the process of being stopped or paused.
3659 // this will be done by prepareTracks_l() when the track is stopped.
3660 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3661 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3662 reset();
3663 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 }
3665}
3666
3667void AudioFlinger::PlaybackThread::Track::reset()
3668{
3669 // Do not reset twice to avoid discarding data written just after a flush and before
3670 // the audioflinger thread detects the track is stopped.
3671 if (!mResetDone) {
3672 TrackBase::reset();
3673 // Force underrun condition to avoid false underrun callback until first data is
3674 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003675 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3676 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677 mFillingUpStatus = FS_FILLING;
3678 mResetDone = true;
3679 }
3680}
3681
3682void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3683{
3684 mMute = muted;
3685}
3686
Mathias Agopian65ab4712010-07-14 17:59:35 -07003687status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3688{
3689 status_t status = DEAD_OBJECT;
3690 sp<ThreadBase> thread = mThread.promote();
3691 if (thread != 0) {
3692 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3693 status = playbackThread->attachAuxEffect(this, EffectId);
3694 }
3695 return status;
3696}
3697
3698void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3699{
3700 mAuxEffectId = EffectId;
3701 mAuxBuffer = buffer;
3702}
3703
3704// ----------------------------------------------------------------------------
3705
3706// RecordTrack constructor must be called with AudioFlinger::mLock held
3707AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3708 const wp<ThreadBase>& thread,
3709 const sp<Client>& client,
3710 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003711 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003712 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 int frameCount,
3714 uint32_t flags,
3715 int sessionId)
3716 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003717 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 mOverflow(false)
3719{
3720 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003721 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003722 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003723 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003724 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003725 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726 } else {
3727 mCblk->frameSize = sizeof(int8_t);
3728 }
3729 }
3730}
3731
3732AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3733{
3734 sp<ThreadBase> thread = mThread.promote();
3735 if (thread != 0) {
3736 AudioSystem::releaseInput(thread->id());
3737 }
3738}
3739
3740status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3741{
3742 audio_track_cblk_t* cblk = this->cblk();
3743 uint32_t framesAvail;
3744 uint32_t framesReq = buffer->frameCount;
3745
3746 // Check if last stepServer failed, try to step now
3747 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3748 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003749 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3751 }
3752
3753 framesAvail = cblk->framesAvailable_l();
3754
Glenn Kastenf6b16782011-12-15 09:51:17 -08003755 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003756 uint32_t s = cblk->server;
3757 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3758
3759 if (framesReq > framesAvail) {
3760 framesReq = framesAvail;
3761 }
3762 if (s + framesReq > bufferEnd) {
3763 framesReq = bufferEnd - s;
3764 }
3765
3766 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003767 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768
3769 buffer->frameCount = framesReq;
3770 return NO_ERROR;
3771 }
3772
3773getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003774 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003775 buffer->frameCount = 0;
3776 return NOT_ENOUGH_DATA;
3777}
3778
3779status_t AudioFlinger::RecordThread::RecordTrack::start()
3780{
3781 sp<ThreadBase> thread = mThread.promote();
3782 if (thread != 0) {
3783 RecordThread *recordThread = (RecordThread *)thread.get();
3784 return recordThread->start(this);
3785 } else {
3786 return BAD_VALUE;
3787 }
3788}
3789
3790void AudioFlinger::RecordThread::RecordTrack::stop()
3791{
3792 sp<ThreadBase> thread = mThread.promote();
3793 if (thread != 0) {
3794 RecordThread *recordThread = (RecordThread *)thread.get();
3795 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003796 TrackBase::reset();
3797 // Force overerrun condition to avoid false overrun callback until first data is
3798 // read from buffer
3799 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800 }
3801}
3802
3803void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3804{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003805 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003806 (mClient == NULL) ? getpid() : mClient->pid(),
3807 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003808 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809 mSessionId,
3810 mFrameCount,
3811 mState,
3812 mCblk->sampleRate,
3813 mCblk->server,
3814 mCblk->user);
3815}
3816
3817
3818// ----------------------------------------------------------------------------
3819
3820AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3821 const wp<ThreadBase>& thread,
3822 DuplicatingThread *sourceThread,
3823 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003824 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003825 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003827 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828 mActive(false), mSourceThread(sourceThread)
3829{
3830
3831 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3832 if (mCblk != NULL) {
3833 mCblk->flags |= CBLK_DIRECTION_OUT;
3834 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003835 mOutBuffer.frameCount = 0;
3836 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003837 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003838 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3839 mCblk, mBuffer, mCblk->buffers,
3840 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003842 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 }
3844}
3845
3846AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3847{
3848 clearBufferQueue();
3849}
3850
3851status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3852{
3853 status_t status = Track::start();
3854 if (status != NO_ERROR) {
3855 return status;
3856 }
3857
3858 mActive = true;
3859 mRetryCount = 127;
3860 return status;
3861}
3862
3863void AudioFlinger::PlaybackThread::OutputTrack::stop()
3864{
3865 Track::stop();
3866 clearBufferQueue();
3867 mOutBuffer.frameCount = 0;
3868 mActive = false;
3869}
3870
3871bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3872{
3873 Buffer *pInBuffer;
3874 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003875 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003876 bool outputBufferFull = false;
3877 inBuffer.frameCount = frames;
3878 inBuffer.i16 = data;
3879
3880 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3881
3882 if (!mActive && frames != 0) {
3883 start();
3884 sp<ThreadBase> thread = mThread.promote();
3885 if (thread != 0) {
3886 MixerThread *mixerThread = (MixerThread *)thread.get();
3887 if (mCblk->frameCount > frames){
3888 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3889 uint32_t startFrames = (mCblk->frameCount - frames);
3890 pInBuffer = new Buffer;
3891 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3892 pInBuffer->frameCount = startFrames;
3893 pInBuffer->i16 = pInBuffer->mBuffer;
3894 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3895 mBufferQueue.add(pInBuffer);
3896 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003897 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898 }
3899 }
3900 }
3901 }
3902
3903 while (waitTimeLeftMs) {
3904 // First write pending buffers, then new data
3905 if (mBufferQueue.size()) {
3906 pInBuffer = mBufferQueue.itemAt(0);
3907 } else {
3908 pInBuffer = &inBuffer;
3909 }
3910
3911 if (pInBuffer->frameCount == 0) {
3912 break;
3913 }
3914
3915 if (mOutBuffer.frameCount == 0) {
3916 mOutBuffer.frameCount = pInBuffer->frameCount;
3917 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003918 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003919 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 outputBufferFull = true;
3921 break;
3922 }
3923 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3924 if (waitTimeLeftMs >= waitTimeMs) {
3925 waitTimeLeftMs -= waitTimeMs;
3926 } else {
3927 waitTimeLeftMs = 0;
3928 }
3929 }
3930
3931 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3932 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3933 mCblk->stepUser(outFrames);
3934 pInBuffer->frameCount -= outFrames;
3935 pInBuffer->i16 += outFrames * channelCount;
3936 mOutBuffer.frameCount -= outFrames;
3937 mOutBuffer.i16 += outFrames * channelCount;
3938
3939 if (pInBuffer->frameCount == 0) {
3940 if (mBufferQueue.size()) {
3941 mBufferQueue.removeAt(0);
3942 delete [] pInBuffer->mBuffer;
3943 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003944 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 } else {
3946 break;
3947 }
3948 }
3949 }
3950
3951 // If we could not write all frames, allocate a buffer and queue it for next time.
3952 if (inBuffer.frameCount) {
3953 sp<ThreadBase> thread = mThread.promote();
3954 if (thread != 0 && !thread->standby()) {
3955 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3956 pInBuffer = new Buffer;
3957 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3958 pInBuffer->frameCount = inBuffer.frameCount;
3959 pInBuffer->i16 = pInBuffer->mBuffer;
3960 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3961 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003962 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003963 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003964 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003965 }
3966 }
3967 }
3968
3969 // Calling write() with a 0 length buffer, means that no more data will be written:
3970 // If no more buffers are pending, fill output track buffer to make sure it is started
3971 // by output mixer.
3972 if (frames == 0 && mBufferQueue.size() == 0) {
3973 if (mCblk->user < mCblk->frameCount) {
3974 frames = mCblk->frameCount - mCblk->user;
3975 pInBuffer = new Buffer;
3976 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3977 pInBuffer->frameCount = frames;
3978 pInBuffer->i16 = pInBuffer->mBuffer;
3979 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3980 mBufferQueue.add(pInBuffer);
3981 } else if (mActive) {
3982 stop();
3983 }
3984 }
3985
3986 return outputBufferFull;
3987}
3988
3989status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3990{
3991 int active;
3992 status_t result;
3993 audio_track_cblk_t* cblk = mCblk;
3994 uint32_t framesReq = buffer->frameCount;
3995
Steve Block3856b092011-10-20 11:56:00 +01003996// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997 buffer->frameCount = 0;
3998
3999 uint32_t framesAvail = cblk->framesAvailable();
4000
4001
4002 if (framesAvail == 0) {
4003 Mutex::Autolock _l(cblk->lock);
4004 goto start_loop_here;
4005 while (framesAvail == 0) {
4006 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004007 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004008 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004009 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010 }
4011 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4012 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004013 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014 }
4015 // read the server count again
4016 start_loop_here:
4017 framesAvail = cblk->framesAvailable_l();
4018 }
4019 }
4020
4021// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004022// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023// }
4024
4025 if (framesReq > framesAvail) {
4026 framesReq = framesAvail;
4027 }
4028
4029 uint32_t u = cblk->user;
4030 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4031
4032 if (u + framesReq > bufferEnd) {
4033 framesReq = bufferEnd - u;
4034 }
4035
4036 buffer->frameCount = framesReq;
4037 buffer->raw = (void *)cblk->buffer(u);
4038 return NO_ERROR;
4039}
4040
4041
4042void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4043{
4044 size_t size = mBufferQueue.size();
4045 Buffer *pBuffer;
4046
4047 for (size_t i = 0; i < size; i++) {
4048 pBuffer = mBufferQueue.itemAt(i);
4049 delete [] pBuffer->mBuffer;
4050 delete pBuffer;
4051 }
4052 mBufferQueue.clear();
4053}
4054
4055// ----------------------------------------------------------------------------
4056
4057AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4058 : RefBase(),
4059 mAudioFlinger(audioFlinger),
4060 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4061 mPid(pid)
4062{
4063 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4064}
4065
4066// Client destructor must be called with AudioFlinger::mLock held
4067AudioFlinger::Client::~Client()
4068{
4069 mAudioFlinger->removeClient_l(mPid);
4070}
4071
Glenn Kasten435dbe62012-01-30 10:15:48 -08004072sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073{
4074 return mMemoryDealer;
4075}
4076
4077// ----------------------------------------------------------------------------
4078
4079AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4080 const sp<IAudioFlingerClient>& client,
4081 pid_t pid)
4082 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4083{
4084}
4085
4086AudioFlinger::NotificationClient::~NotificationClient()
4087{
4088 mClient.clear();
4089}
4090
4091void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4092{
4093 sp<NotificationClient> keep(this);
4094 {
4095 mAudioFlinger->removeNotificationClient(mPid);
4096 }
4097}
4098
4099// ----------------------------------------------------------------------------
4100
4101AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4102 : BnAudioTrack(),
4103 mTrack(track)
4104{
4105}
4106
4107AudioFlinger::TrackHandle::~TrackHandle() {
4108 // just stop the track on deletion, associated resources
4109 // will be freed from the main thread once all pending buffers have
4110 // been played. Unless it's not in the active track list, in which
4111 // case we free everything now...
4112 mTrack->destroy();
4113}
4114
Glenn Kasten90716c52012-01-26 13:40:12 -08004115sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4116 return mTrack->getCblk();
4117}
4118
Mathias Agopian65ab4712010-07-14 17:59:35 -07004119status_t AudioFlinger::TrackHandle::start() {
4120 return mTrack->start();
4121}
4122
4123void AudioFlinger::TrackHandle::stop() {
4124 mTrack->stop();
4125}
4126
4127void AudioFlinger::TrackHandle::flush() {
4128 mTrack->flush();
4129}
4130
4131void AudioFlinger::TrackHandle::mute(bool e) {
4132 mTrack->mute(e);
4133}
4134
4135void AudioFlinger::TrackHandle::pause() {
4136 mTrack->pause();
4137}
4138
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4140{
4141 return mTrack->attachAuxEffect(EffectId);
4142}
4143
4144status_t AudioFlinger::TrackHandle::onTransact(
4145 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4146{
4147 return BnAudioTrack::onTransact(code, data, reply, flags);
4148}
4149
4150// ----------------------------------------------------------------------------
4151
4152sp<IAudioRecord> AudioFlinger::openRecord(
4153 pid_t pid,
4154 int input,
4155 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004156 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004157 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158 int frameCount,
4159 uint32_t flags,
4160 int *sessionId,
4161 status_t *status)
4162{
4163 sp<RecordThread::RecordTrack> recordTrack;
4164 sp<RecordHandle> recordHandle;
4165 sp<Client> client;
4166 wp<Client> wclient;
4167 status_t lStatus;
4168 RecordThread *thread;
4169 size_t inFrameCount;
4170 int lSessionId;
4171
4172 // check calling permissions
4173 if (!recordingAllowed()) {
4174 lStatus = PERMISSION_DENIED;
4175 goto Exit;
4176 }
4177
4178 // add client to list
4179 { // scope for mLock
4180 Mutex::Autolock _l(mLock);
4181 thread = checkRecordThread_l(input);
4182 if (thread == NULL) {
4183 lStatus = BAD_VALUE;
4184 goto Exit;
4185 }
4186
4187 wclient = mClients.valueFor(pid);
4188 if (wclient != NULL) {
4189 client = wclient.promote();
4190 } else {
4191 client = new Client(this, pid);
4192 mClients.add(pid, client);
4193 }
4194
4195 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004196 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 lSessionId = *sessionId;
4198 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004199 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 if (sessionId != NULL) {
4201 *sessionId = lSessionId;
4202 }
4203 }
4204 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004205 recordTrack = thread->createRecordTrack_l(client,
4206 sampleRate,
4207 format,
4208 channelMask,
4209 frameCount,
4210 flags,
4211 lSessionId,
4212 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004214 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4216 // destructor is called by the TrackBase destructor with mLock held
4217 client.clear();
4218 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004219 goto Exit;
4220 }
4221
4222 // return to handle to client
4223 recordHandle = new RecordHandle(recordTrack);
4224 lStatus = NO_ERROR;
4225
4226Exit:
4227 if (status) {
4228 *status = lStatus;
4229 }
4230 return recordHandle;
4231}
4232
4233// ----------------------------------------------------------------------------
4234
4235AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4236 : BnAudioRecord(),
4237 mRecordTrack(recordTrack)
4238{
4239}
4240
4241AudioFlinger::RecordHandle::~RecordHandle() {
4242 stop();
4243}
4244
Glenn Kasten90716c52012-01-26 13:40:12 -08004245sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4246 return mRecordTrack->getCblk();
4247}
4248
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004250 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251 return mRecordTrack->start();
4252}
4253
4254void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004255 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 mRecordTrack->stop();
4257}
4258
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259status_t AudioFlinger::RecordHandle::onTransact(
4260 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4261{
4262 return BnAudioRecord::onTransact(code, data, reply, flags);
4263}
4264
4265// ----------------------------------------------------------------------------
4266
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004267AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4268 AudioStreamIn *input,
4269 uint32_t sampleRate,
4270 uint32_t channels,
4271 int id,
4272 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004273 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kastene0feee32011-12-13 11:53:26 -08004274 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004276 snprintf(mName, kNameLength, "AudioIn_%d", id);
4277
Dima Zavinfce7a472011-04-19 22:30:36 -07004278 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 mReqSampleRate = sampleRate;
4280 readInputParameters();
4281}
4282
4283
4284AudioFlinger::RecordThread::~RecordThread()
4285{
4286 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004287 delete mResampler;
4288 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289}
4290
4291void AudioFlinger::RecordThread::onFirstRef()
4292{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004293 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294}
4295
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004296status_t AudioFlinger::RecordThread::readyToRun()
4297{
4298 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004299 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004300 return status;
4301}
4302
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303bool AudioFlinger::RecordThread::threadLoop()
4304{
4305 AudioBufferProvider::Buffer buffer;
4306 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004307 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308
Eric Laurent44d98482010-09-30 16:12:31 -07004309 nsecs_t lastWarning = 0;
4310
Eric Laurentfeb0db62011-07-22 09:04:31 -07004311 acquireWakeLock();
4312
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 // start recording
4314 while (!exitPending()) {
4315
4316 processConfigEvents();
4317
4318 { // scope for mLock
4319 Mutex::Autolock _l(mLock);
4320 checkForNewParameters_l();
4321 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4322 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004323 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324 mStandby = true;
4325 }
4326
4327 if (exitPending()) break;
4328
Eric Laurentfeb0db62011-07-22 09:04:31 -07004329 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004330 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 // go to sleep
4332 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004333 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004334 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 continue;
4336 }
4337 if (mActiveTrack != 0) {
4338 if (mActiveTrack->mState == TrackBase::PAUSING) {
4339 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004340 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341 mStandby = true;
4342 }
4343 mActiveTrack.clear();
4344 mStartStopCond.broadcast();
4345 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4346 if (mReqChannelCount != mActiveTrack->channelCount()) {
4347 mActiveTrack.clear();
4348 mStartStopCond.broadcast();
4349 } else if (mBytesRead != 0) {
4350 // record start succeeds only if first read from audio input
4351 // succeeds
4352 if (mBytesRead > 0) {
4353 mActiveTrack->mState = TrackBase::ACTIVE;
4354 } else {
4355 mActiveTrack.clear();
4356 }
4357 mStartStopCond.broadcast();
4358 }
4359 mStandby = false;
4360 }
4361 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004362 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 }
4364
4365 if (mActiveTrack != 0) {
4366 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4367 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004368 unlockEffectChains(effectChains);
4369 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 continue;
4371 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004372 for (size_t i = 0; i < effectChains.size(); i ++) {
4373 effectChains[i]->process_l();
4374 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004375
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004377 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004379 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 // no resampling
4381 while (framesOut) {
4382 size_t framesIn = mFrameCount - mRsmpInIndex;
4383 if (framesIn) {
4384 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4385 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4386 if (framesIn > framesOut)
4387 framesIn = framesOut;
4388 mRsmpInIndex += framesIn;
4389 framesOut -= framesIn;
4390 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004391 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 memcpy(dst, src, framesIn * mFrameSize);
4393 } else {
4394 int16_t *src16 = (int16_t *)src;
4395 int16_t *dst16 = (int16_t *)dst;
4396 if (mChannelCount == 1) {
4397 while (framesIn--) {
4398 *dst16++ = *src16;
4399 *dst16++ = *src16++;
4400 }
4401 } else {
4402 while (framesIn--) {
4403 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4404 src16 += 2;
4405 }
4406 }
4407 }
4408 }
4409 if (framesOut && mFrameCount == mRsmpInIndex) {
4410 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004411 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004412 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 framesOut = 0;
4414 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004415 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004416 mRsmpInIndex = 0;
4417 }
4418 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004419 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004420 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4421 // Force input into standby so that it tries to
4422 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004423 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004424 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 }
4426 mRsmpInIndex = mFrameCount;
4427 framesOut = 0;
4428 buffer.frameCount = 0;
4429 }
4430 }
4431 }
4432 } else {
4433 // resampling
4434
4435 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4436 // alter output frame count as if we were expecting stereo samples
4437 if (mChannelCount == 1 && mReqChannelCount == 1) {
4438 framesOut >>= 1;
4439 }
4440 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4441 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4442 // are 32 bit aligned which should be always true.
4443 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004444 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 // the resampler always outputs stereo samples: do post stereo to mono conversion
4446 int16_t *src = (int16_t *)mRsmpOutBuffer;
4447 int16_t *dst = buffer.i16;
4448 while (framesOut--) {
4449 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4450 src += 2;
4451 }
4452 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004453 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454 }
4455
4456 }
4457 mActiveTrack->releaseBuffer(&buffer);
4458 mActiveTrack->overflow();
4459 }
4460 // client isn't retrieving buffers fast enough
4461 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004462 if (!mActiveTrack->setOverflow()) {
4463 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004464 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004465 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004466 lastWarning = now;
4467 }
4468 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469 // Release the processor for a while before asking for a new buffer.
4470 // This will give the application more chance to read from the buffer and
4471 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004472 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004473 }
4474 }
Eric Laurentec437d82011-07-26 20:54:46 -07004475 // enable changes in effect chain
4476 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004477 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478 }
4479
4480 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004481 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004482 }
4483 mActiveTrack.clear();
4484
4485 mStartStopCond.broadcast();
4486
Eric Laurentfeb0db62011-07-22 09:04:31 -07004487 releaseWakeLock();
4488
Steve Block3856b092011-10-20 11:56:00 +01004489 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 return false;
4491}
4492
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004493
4494sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4495 const sp<AudioFlinger::Client>& client,
4496 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004497 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004498 int channelMask,
4499 int frameCount,
4500 uint32_t flags,
4501 int sessionId,
4502 status_t *status)
4503{
4504 sp<RecordTrack> track;
4505 status_t lStatus;
4506
4507 lStatus = initCheck();
4508 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004509 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004510 goto Exit;
4511 }
4512
4513 { // scope for mLock
4514 Mutex::Autolock _l(mLock);
4515
4516 track = new RecordTrack(this, client, sampleRate,
4517 format, channelMask, frameCount, flags, sessionId);
4518
4519 if (track->getCblk() == NULL) {
4520 lStatus = NO_MEMORY;
4521 goto Exit;
4522 }
4523
4524 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004525 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4526 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004527 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004528 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4529 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004530 }
4531 lStatus = NO_ERROR;
4532
4533Exit:
4534 if (status) {
4535 *status = lStatus;
4536 }
4537 return track;
4538}
4539
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4541{
Steve Block3856b092011-10-20 11:56:00 +01004542 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543 sp <ThreadBase> strongMe = this;
4544 status_t status = NO_ERROR;
4545 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004546 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004547 if (mActiveTrack != 0) {
4548 if (recordTrack != mActiveTrack.get()) {
4549 status = -EBUSY;
4550 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4551 mActiveTrack->mState = TrackBase::ACTIVE;
4552 }
4553 return status;
4554 }
4555
4556 recordTrack->mState = TrackBase::IDLE;
4557 mActiveTrack = recordTrack;
4558 mLock.unlock();
4559 status_t status = AudioSystem::startInput(mId);
4560 mLock.lock();
4561 if (status != NO_ERROR) {
4562 mActiveTrack.clear();
4563 return status;
4564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 mRsmpInIndex = mFrameCount;
4566 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004567 if (mResampler != NULL) {
4568 mResampler->reset();
4569 }
4570 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004572 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 mWaitWorkCV.signal();
4574 // do not wait for mStartStopCond if exiting
4575 if (mExiting) {
4576 mActiveTrack.clear();
4577 status = INVALID_OPERATION;
4578 goto startError;
4579 }
4580 mStartStopCond.wait(mLock);
4581 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004582 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583 status = BAD_VALUE;
4584 goto startError;
4585 }
Steve Block3856b092011-10-20 11:56:00 +01004586 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 return status;
4588 }
4589startError:
4590 AudioSystem::stopInput(mId);
4591 return status;
4592}
4593
4594void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004595 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 sp <ThreadBase> strongMe = this;
4597 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004598 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4600 mActiveTrack->mState = TrackBase::PAUSING;
4601 // do not wait for mStartStopCond if exiting
4602 if (mExiting) {
4603 return;
4604 }
4605 mStartStopCond.wait(mLock);
4606 // if we have been restarted, recordTrack == mActiveTrack.get() here
4607 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4608 mLock.unlock();
4609 AudioSystem::stopInput(mId);
4610 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004611 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 }
4613 }
4614 }
4615}
4616
4617status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4618{
4619 const size_t SIZE = 256;
4620 char buffer[SIZE];
4621 String8 result;
4622 pid_t pid = 0;
4623
4624 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4625 result.append(buffer);
4626
4627 if (mActiveTrack != 0) {
4628 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004629 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 mActiveTrack->dump(buffer, SIZE);
4631 result.append(buffer);
4632
4633 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4634 result.append(buffer);
4635 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4636 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004637 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 result.append(buffer);
4639 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4640 result.append(buffer);
4641 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4642 result.append(buffer);
4643
4644
4645 } else {
4646 result.append("No record client\n");
4647 }
4648 write(fd, result.string(), result.size());
4649
4650 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004651 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652
4653 return NO_ERROR;
4654}
4655
4656status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4657{
4658 size_t framesReq = buffer->frameCount;
4659 size_t framesReady = mFrameCount - mRsmpInIndex;
4660 int channelCount;
4661
4662 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004663 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004664 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004665 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4667 // Force input into standby so that it tries to
4668 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004669 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004670 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004672 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 buffer->frameCount = 0;
4674 return NOT_ENOUGH_DATA;
4675 }
4676 mRsmpInIndex = 0;
4677 framesReady = mFrameCount;
4678 }
4679
4680 if (framesReq > framesReady) {
4681 framesReq = framesReady;
4682 }
4683
4684 if (mChannelCount == 1 && mReqChannelCount == 2) {
4685 channelCount = 1;
4686 } else {
4687 channelCount = 2;
4688 }
4689 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4690 buffer->frameCount = framesReq;
4691 return NO_ERROR;
4692}
4693
4694void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4695{
4696 mRsmpInIndex += buffer->frameCount;
4697 buffer->frameCount = 0;
4698}
4699
4700bool AudioFlinger::RecordThread::checkForNewParameters_l()
4701{
4702 bool reconfig = false;
4703
4704 while (!mNewParameters.isEmpty()) {
4705 status_t status = NO_ERROR;
4706 String8 keyValuePair = mNewParameters[0];
4707 AudioParameter param = AudioParameter(keyValuePair);
4708 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004709 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 int reqSamplingRate = mReqSampleRate;
4711 int reqChannelCount = mReqChannelCount;
4712
4713 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4714 reqSamplingRate = value;
4715 reconfig = true;
4716 }
4717 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004718 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 reconfig = true;
4720 }
4721 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004722 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 reconfig = true;
4724 }
4725 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4726 // do not accept frame count changes if tracks are open as the track buffer
4727 // size depends on frame count and correct behavior would not be garantied
4728 // if frame count is changed after track creation
4729 if (mActiveTrack != 0) {
4730 status = INVALID_OPERATION;
4731 } else {
4732 reconfig = true;
4733 }
4734 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004735 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4736 // forward device change to effects that have requested to be
4737 // aware of attached audio device.
4738 for (size_t i = 0; i < mEffectChains.size(); i++) {
4739 mEffectChains[i]->setDevice_l(value);
4740 }
4741 // store input device and output device but do not forward output device to audio HAL.
4742 // Note that status is ignored by the caller for output device
4743 // (see AudioFlinger::setParameters()
4744 if (value & AUDIO_DEVICE_OUT_ALL) {
4745 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4746 status = BAD_VALUE;
4747 } else {
4748 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004749 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4750 if (mTrack != NULL) {
4751 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004752 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004753 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4754 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4755 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004756 }
4757 mDevice |= (uint32_t)value;
4758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004759 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004760 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004762 mInput->stream->common.standby(&mInput->stream->common);
4763 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004764 }
4765 if (reconfig) {
4766 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004767 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004768 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004769 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4770 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004771 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772 status = NO_ERROR;
4773 }
4774 if (status == NO_ERROR) {
4775 readInputParameters();
4776 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4777 }
4778 }
4779 }
4780
4781 mNewParameters.removeAt(0);
4782
4783 mParamStatus = status;
4784 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004785 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4786 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004787 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004788 }
4789 return reconfig;
4790}
4791
4792String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4793{
Dima Zavinfce7a472011-04-19 22:30:36 -07004794 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004795 String8 out_s8 = String8();
4796
4797 Mutex::Autolock _l(mLock);
4798 if (initCheck() != NO_ERROR) {
4799 return out_s8;
4800 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004801
Dima Zavin799a70e2011-04-18 16:57:27 -07004802 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004803 out_s8 = String8(s);
4804 free(s);
4805 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004806}
4807
4808void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4809 AudioSystem::OutputDescriptor desc;
4810 void *param2 = 0;
4811
4812 switch (event) {
4813 case AudioSystem::INPUT_OPENED:
4814 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004815 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004816 desc.samplingRate = mSampleRate;
4817 desc.format = mFormat;
4818 desc.frameCount = mFrameCount;
4819 desc.latency = 0;
4820 param2 = &desc;
4821 break;
4822
4823 case AudioSystem::INPUT_CLOSED:
4824 default:
4825 break;
4826 }
4827 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4828}
4829
4830void AudioFlinger::RecordThread::readInputParameters()
4831{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004832 delete mRsmpInBuffer;
4833 // mRsmpInBuffer is always assigned a new[] below
4834 delete mRsmpOutBuffer;
4835 mRsmpOutBuffer = NULL;
4836 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004837 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004838
Dima Zavin799a70e2011-04-18 16:57:27 -07004839 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004840 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4841 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004842 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004843 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004844 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004845 mFrameCount = mInputBytes / mFrameSize;
4846 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4847
4848 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4849 {
4850 int channelCount;
4851 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4852 // stereo to mono post process as the resampler always outputs stereo.
4853 if (mChannelCount == 1 && mReqChannelCount == 2) {
4854 channelCount = 1;
4855 } else {
4856 channelCount = 2;
4857 }
4858 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4859 mResampler->setSampleRate(mSampleRate);
4860 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4861 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4862
4863 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4864 if (mChannelCount == 1 && mReqChannelCount == 1) {
4865 mFrameCount >>= 1;
4866 }
4867
4868 }
4869 mRsmpInIndex = mFrameCount;
4870}
4871
4872unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4873{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004874 Mutex::Autolock _l(mLock);
4875 if (initCheck() != NO_ERROR) {
4876 return 0;
4877 }
4878
Dima Zavin799a70e2011-04-18 16:57:27 -07004879 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880}
4881
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004882uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4883{
4884 Mutex::Autolock _l(mLock);
4885 uint32_t result = 0;
4886 if (getEffectChain_l(sessionId) != 0) {
4887 result = EFFECT_SESSION;
4888 }
4889
4890 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4891 result |= TRACK_SESSION;
4892 }
4893
4894 return result;
4895}
4896
Eric Laurent59bd0da2011-08-01 09:52:20 -07004897AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4898{
4899 Mutex::Autolock _l(mLock);
4900 return mTrack;
4901}
4902
Glenn Kastenaed850d2012-01-26 09:46:34 -08004903AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004904{
4905 Mutex::Autolock _l(mLock);
4906 return mInput;
4907}
4908
4909AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4910{
4911 Mutex::Autolock _l(mLock);
4912 AudioStreamIn *input = mInput;
4913 mInput = NULL;
4914 return input;
4915}
4916
4917// this method must always be called either with ThreadBase mLock held or inside the thread loop
4918audio_stream_t* AudioFlinger::RecordThread::stream()
4919{
4920 if (mInput == NULL) {
4921 return NULL;
4922 }
4923 return &mInput->stream->common;
4924}
4925
4926
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927// ----------------------------------------------------------------------------
4928
4929int AudioFlinger::openOutput(uint32_t *pDevices,
4930 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004931 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004932 uint32_t *pChannels,
4933 uint32_t *pLatencyMs,
4934 uint32_t flags)
4935{
4936 status_t status;
4937 PlaybackThread *thread = NULL;
4938 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4939 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004940 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941 uint32_t channels = pChannels ? *pChannels : 0;
4942 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004943 audio_stream_out_t *outStream;
4944 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945
Steve Block3856b092011-10-20 11:56:00 +01004946 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947 pDevices ? *pDevices : 0,
4948 samplingRate,
4949 format,
4950 channels,
4951 flags);
4952
4953 if (pDevices == NULL || *pDevices == 0) {
4954 return 0;
4955 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004956
Mathias Agopian65ab4712010-07-14 17:59:35 -07004957 Mutex::Autolock _l(mLock);
4958
Dima Zavin799a70e2011-04-18 16:57:27 -07004959 outHwDev = findSuitableHwDev_l(*pDevices);
4960 if (outHwDev == NULL)
4961 return 0;
4962
Glenn Kasten58f30212012-01-12 12:27:51 -08004963 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004964 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004965 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004966 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004967 samplingRate,
4968 format,
4969 channels,
4970 status);
4971
4972 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004973 if (outStream != NULL) {
4974 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004975 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004976
Dima Zavinfce7a472011-04-19 22:30:36 -07004977 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4978 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4979 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004981 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 } else {
4983 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004984 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 }
4986 mPlaybackThreads.add(id, thread);
4987
4988 if (pSamplingRate) *pSamplingRate = samplingRate;
4989 if (pFormat) *pFormat = format;
4990 if (pChannels) *pChannels = channels;
4991 if (pLatencyMs) *pLatencyMs = thread->latency();
4992
4993 // notify client processes of the new output creation
4994 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4995 return id;
4996 }
4997
4998 return 0;
4999}
5000
5001int AudioFlinger::openDuplicateOutput(int output1, int output2)
5002{
5003 Mutex::Autolock _l(mLock);
5004 MixerThread *thread1 = checkMixerThread_l(output1);
5005 MixerThread *thread2 = checkMixerThread_l(output2);
5006
5007 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005008 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 return 0;
5010 }
5011
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005012 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5014 thread->addOutputTrack(thread2);
5015 mPlaybackThreads.add(id, thread);
5016 // notify client processes of the new output creation
5017 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5018 return id;
5019}
5020
5021status_t AudioFlinger::closeOutput(int output)
5022{
5023 // keep strong reference on the playback thread so that
5024 // it is not destroyed while exit() is executed
5025 sp <PlaybackThread> thread;
5026 {
5027 Mutex::Autolock _l(mLock);
5028 thread = checkPlaybackThread_l(output);
5029 if (thread == NULL) {
5030 return BAD_VALUE;
5031 }
5032
Steve Block3856b092011-10-20 11:56:00 +01005033 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005035 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005037 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5039 dupThread->removeOutputTrack((MixerThread *)thread.get());
5040 }
5041 }
5042 }
5043 void *param2 = 0;
5044 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5045 mPlaybackThreads.removeItem(output);
5046 }
5047 thread->exit();
5048
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005049 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005050 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005051 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005052 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005053 out->hwDev->close_output_stream(out->hwDev, out->stream);
5054 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 }
5056 return NO_ERROR;
5057}
5058
5059status_t AudioFlinger::suspendOutput(int output)
5060{
5061 Mutex::Autolock _l(mLock);
5062 PlaybackThread *thread = checkPlaybackThread_l(output);
5063
5064 if (thread == NULL) {
5065 return BAD_VALUE;
5066 }
5067
Steve Block3856b092011-10-20 11:56:00 +01005068 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 thread->suspend();
5070
5071 return NO_ERROR;
5072}
5073
5074status_t AudioFlinger::restoreOutput(int output)
5075{
5076 Mutex::Autolock _l(mLock);
5077 PlaybackThread *thread = checkPlaybackThread_l(output);
5078
5079 if (thread == NULL) {
5080 return BAD_VALUE;
5081 }
5082
Steve Block3856b092011-10-20 11:56:00 +01005083 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084
5085 thread->restore();
5086
5087 return NO_ERROR;
5088}
5089
5090int AudioFlinger::openInput(uint32_t *pDevices,
5091 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005092 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 uint32_t *pChannels,
5094 uint32_t acoustics)
5095{
5096 status_t status;
5097 RecordThread *thread = NULL;
5098 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005099 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 uint32_t channels = pChannels ? *pChannels : 0;
5101 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005102 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005104 audio_stream_in_t *inStream;
5105 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106
5107 if (pDevices == NULL || *pDevices == 0) {
5108 return 0;
5109 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005110
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 Mutex::Autolock _l(mLock);
5112
Dima Zavin799a70e2011-04-18 16:57:27 -07005113 inHwDev = findSuitableHwDev_l(*pDevices);
5114 if (inHwDev == NULL)
5115 return 0;
5116
Glenn Kasten58f30212012-01-12 12:27:51 -08005117 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005118 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005119 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005120 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005121 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005122 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 samplingRate,
5124 format,
5125 channels,
5126 acoustics,
5127 status);
5128
5129 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5130 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5131 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005132 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005133 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005134 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005135 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005136 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005137 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005138 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005139 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005140 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005141 }
5142
Dima Zavin799a70e2011-04-18 16:57:27 -07005143 if (inStream != NULL) {
5144 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5145
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005146 int id = nextUniqueId();
5147 // Start record thread
5148 // RecorThread require both input and output device indication to forward to audio
5149 // pre processing modules
5150 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5151 thread = new RecordThread(this,
5152 input,
5153 reqSamplingRate,
5154 reqChannels,
5155 id,
5156 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005157 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005158 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5160 if (pFormat) *pFormat = format;
5161 if (pChannels) *pChannels = reqChannels;
5162
Dima Zavin799a70e2011-04-18 16:57:27 -07005163 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164
5165 // notify client processes of the new input creation
5166 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5167 return id;
5168 }
5169
5170 return 0;
5171}
5172
5173status_t AudioFlinger::closeInput(int input)
5174{
5175 // keep strong reference on the record thread so that
5176 // it is not destroyed while exit() is executed
5177 sp <RecordThread> thread;
5178 {
5179 Mutex::Autolock _l(mLock);
5180 thread = checkRecordThread_l(input);
5181 if (thread == NULL) {
5182 return BAD_VALUE;
5183 }
5184
Steve Block3856b092011-10-20 11:56:00 +01005185 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 void *param2 = 0;
5187 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5188 mRecordThreads.removeItem(input);
5189 }
5190 thread->exit();
5191
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005192 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005193 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005194 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005195 in->hwDev->close_input_stream(in->hwDev, in->stream);
5196 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005197
5198 return NO_ERROR;
5199}
5200
Glenn Kastenfff6d712012-01-12 16:38:12 -08005201status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202{
5203 Mutex::Autolock _l(mLock);
5204 MixerThread *dstThread = checkMixerThread_l(output);
5205 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005206 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005207 return BAD_VALUE;
5208 }
5209
Steve Block3856b092011-10-20 11:56:00 +01005210 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5212
Eric Laurent9f6530f2011-08-30 10:18:54 -07005213 dstThread->setStreamValid(stream, true);
5214
Mathias Agopian65ab4712010-07-14 17:59:35 -07005215 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5216 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5217 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005218 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005219 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005220 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005221 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005222 }
Eric Laurentde070132010-07-13 04:45:46 -07005223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005224
5225 return NO_ERROR;
5226}
5227
5228
5229int AudioFlinger::newAudioSessionId()
5230{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005231 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005232}
5233
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005234void AudioFlinger::acquireAudioSessionId(int audioSession)
5235{
5236 Mutex::Autolock _l(mLock);
5237 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005238 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005239 int num = mAudioSessionRefs.size();
5240 for (int i = 0; i< num; i++) {
5241 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5242 if (ref->sessionid == audioSession && ref->pid == caller) {
5243 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005244 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005245 return;
5246 }
5247 }
5248 AudioSessionRef *ref = new AudioSessionRef();
5249 ref->sessionid = audioSession;
5250 ref->pid = caller;
5251 ref->cnt = 1;
5252 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005253 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005254}
5255
5256void AudioFlinger::releaseAudioSessionId(int audioSession)
5257{
5258 Mutex::Autolock _l(mLock);
5259 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005260 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005261 int num = mAudioSessionRefs.size();
5262 for (int i = 0; i< num; i++) {
5263 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5264 if (ref->sessionid == audioSession && ref->pid == caller) {
5265 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005266 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005267 if (ref->cnt == 0) {
5268 mAudioSessionRefs.removeAt(i);
5269 delete ref;
5270 purgeStaleEffects_l();
5271 }
5272 return;
5273 }
5274 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005275 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005276}
5277
5278void AudioFlinger::purgeStaleEffects_l() {
5279
Steve Block3856b092011-10-20 11:56:00 +01005280 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005281
5282 Vector< sp<EffectChain> > chains;
5283
5284 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5285 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5286 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5287 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005288 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5289 chains.push(ec);
5290 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005291 }
5292 }
5293 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5294 sp<RecordThread> t = mRecordThreads.valueAt(i);
5295 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5296 sp<EffectChain> ec = t->mEffectChains[j];
5297 chains.push(ec);
5298 }
5299 }
5300
5301 for (size_t i = 0; i < chains.size(); i++) {
5302 sp<EffectChain> ec = chains[i];
5303 int sessionid = ec->sessionId();
5304 sp<ThreadBase> t = ec->mThread.promote();
5305 if (t == 0) {
5306 continue;
5307 }
5308 size_t numsessionrefs = mAudioSessionRefs.size();
5309 bool found = false;
5310 for (size_t k = 0; k < numsessionrefs; k++) {
5311 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5312 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005313 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005314 sessionid, ref->pid, ref->cnt);
5315 found = true;
5316 break;
5317 }
5318 }
5319 if (!found) {
5320 // remove all effects from the chain
5321 while (ec->mEffects.size()) {
5322 sp<EffectModule> effect = ec->mEffects[0];
5323 effect->unPin();
5324 Mutex::Autolock _l (t->mLock);
5325 t->removeEffect_l(effect);
5326 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5327 sp<EffectHandle> handle = effect->mHandles[j].promote();
5328 if (handle != 0) {
5329 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005330 if (handle->mHasControl && handle->mEnabled) {
5331 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5332 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005333 }
5334 }
5335 AudioSystem::unregisterEffect(effect->id());
5336 }
5337 }
5338 }
5339 return;
5340}
5341
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5343AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5344{
5345 PlaybackThread *thread = NULL;
5346 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5347 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5348 }
5349 return thread;
5350}
5351
5352// checkMixerThread_l() must be called with AudioFlinger::mLock held
5353AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5354{
5355 PlaybackThread *thread = checkPlaybackThread_l(output);
5356 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005357 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358 thread = NULL;
5359 }
5360 }
5361 return (MixerThread *)thread;
5362}
5363
5364// checkRecordThread_l() must be called with AudioFlinger::mLock held
5365AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5366{
5367 RecordThread *thread = NULL;
5368 if (mRecordThreads.indexOfKey(input) >= 0) {
5369 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5370 }
5371 return thread;
5372}
5373
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005374uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005376 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377}
5378
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005379AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5380{
5381 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5382 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005383 AudioStreamOut *output = thread->getOutput();
5384 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005385 return thread;
5386 }
5387 }
5388 return NULL;
5389}
5390
5391uint32_t AudioFlinger::primaryOutputDevice_l()
5392{
5393 PlaybackThread *thread = primaryPlaybackThread_l();
5394
5395 if (thread == NULL) {
5396 return 0;
5397 }
5398
5399 return thread->device();
5400}
5401
5402
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403// ----------------------------------------------------------------------------
5404// Effect management
5405// ----------------------------------------------------------------------------
5406
5407
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5409{
5410 Mutex::Autolock _l(mLock);
5411 return EffectQueryNumberEffects(numEffects);
5412}
5413
5414status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5415{
5416 Mutex::Autolock _l(mLock);
5417 return EffectQueryEffect(index, descriptor);
5418}
5419
5420status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5421{
5422 Mutex::Autolock _l(mLock);
5423 return EffectGetDescriptor(pUuid, descriptor);
5424}
5425
5426
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5428 effect_descriptor_t *pDesc,
5429 const sp<IEffectClient>& effectClient,
5430 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005431 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432 int sessionId,
5433 status_t *status,
5434 int *id,
5435 int *enabled)
5436{
5437 status_t lStatus = NO_ERROR;
5438 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005439 effect_descriptor_t desc;
5440 sp<Client> client;
5441 wp<Client> wclient;
5442
Steve Block3856b092011-10-20 11:56:00 +01005443 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005444 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445
5446 if (pDesc == NULL) {
5447 lStatus = BAD_VALUE;
5448 goto Exit;
5449 }
5450
Eric Laurent84e9a102010-09-23 16:10:16 -07005451 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005452 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005453 lStatus = PERMISSION_DENIED;
5454 goto Exit;
5455 }
5456
Dima Zavinfce7a472011-04-19 22:30:36 -07005457 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005458 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005459 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005460 lStatus = PERMISSION_DENIED;
5461 goto Exit;
5462 }
5463
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005464 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005465 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005466 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005468 lStatus = BAD_VALUE;
5469 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005470 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005471 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005472 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005473 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005474 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005475 }
5476 }
5477
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 {
5479 Mutex::Autolock _l(mLock);
5480
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481
5482 if (!EffectIsNullUuid(&pDesc->uuid)) {
5483 // if uuid is specified, request effect descriptor
5484 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5485 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005486 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 goto Exit;
5488 }
5489 } else {
5490 // if uuid is not specified, look for an available implementation
5491 // of the required type in effect factory
5492 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005493 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 lStatus = BAD_VALUE;
5495 goto Exit;
5496 }
5497 uint32_t numEffects = 0;
5498 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005499 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 bool found = false;
5501
5502 lStatus = EffectQueryNumberEffects(&numEffects);
5503 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005504 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 goto Exit;
5506 }
5507 for (uint32_t i = 0; i < numEffects; i++) {
5508 lStatus = EffectQueryEffect(i, &desc);
5509 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005510 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 continue;
5512 }
5513 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5514 // If matching type found save effect descriptor. If the session is
5515 // 0 and the effect is not auxiliary, continue enumeration in case
5516 // an auxiliary version of this effect type is available
5517 found = true;
5518 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005519 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5521 break;
5522 }
5523 }
5524 }
5525 if (!found) {
5526 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005527 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 goto Exit;
5529 }
5530 // For same effect type, chose auxiliary version over insert version if
5531 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005532 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5534 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5535 }
5536 }
5537
5538 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005539 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5541 lStatus = INVALID_OPERATION;
5542 goto Exit;
5543 }
5544
Eric Laurent59255e42011-07-27 19:49:51 -07005545 // check recording permission for visualizer
5546 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5547 !recordingAllowed()) {
5548 lStatus = PERMISSION_DENIED;
5549 goto Exit;
5550 }
5551
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 // return effect descriptor
5553 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5554
5555 // If output is not specified try to find a matching audio session ID in one of the
5556 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005557 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5558 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005559 // Note: io is never 0 when creating an effect on an input
5560 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005561 // look for the thread where the specified audio session is present
5562 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5563 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005564 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005565 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005568 if (io == 0) {
5569 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5570 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5571 io = mRecordThreads.keyAt(i);
5572 break;
5573 }
5574 }
5575 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005576 // If no output thread contains the requested session ID, default to
5577 // first output. The effect chain will be moved to the correct output
5578 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005579 if (io == 0 && mPlaybackThreads.size()) {
5580 io = mPlaybackThreads.keyAt(0);
5581 }
Steve Block3856b092011-10-20 11:56:00 +01005582 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005583 }
5584 ThreadBase *thread = checkRecordThread_l(io);
5585 if (thread == NULL) {
5586 thread = checkPlaybackThread_l(io);
5587 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005588 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005589 lStatus = BAD_VALUE;
5590 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005593
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 wclient = mClients.valueFor(pid);
5595
5596 if (wclient != NULL) {
5597 client = wclient.promote();
5598 } else {
5599 client = new Client(this, pid);
5600 mClients.add(pid, client);
5601 }
5602
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005603 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005604 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5605 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 if (handle != 0 && id != NULL) {
5607 *id = handle->id();
5608 }
5609 }
5610
5611Exit:
5612 if(status) {
5613 *status = lStatus;
5614 }
5615 return handle;
5616}
5617
Eric Laurent59255e42011-07-27 19:49:51 -07005618status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005619{
Steve Block3856b092011-10-20 11:56:00 +01005620 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005621 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005622 Mutex::Autolock _l(mLock);
5623 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005624 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005625 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626 }
Eric Laurentde070132010-07-13 04:45:46 -07005627 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5628 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005629 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005630 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 }
Eric Laurentde070132010-07-13 04:45:46 -07005632 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5633 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005634 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005635 return BAD_VALUE;
5636 }
5637
5638 Mutex::Autolock _dl(dstThread->mLock);
5639 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005640 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005641
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642 return NO_ERROR;
5643}
5644
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005645// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005646status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005647 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005648 AudioFlinger::PlaybackThread *dstThread,
5649 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005650{
Steve Block3856b092011-10-20 11:56:00 +01005651 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005652 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005653
Eric Laurent59255e42011-07-27 19:49:51 -07005654 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005655 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005656 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005657 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005658 return INVALID_OPERATION;
5659 }
5660
Eric Laurent39e94f82010-07-28 01:32:47 -07005661 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005662 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005663 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005664 // removed.
5665 srcThread->removeEffectChain_l(chain);
5666
5667 // transfer all effects one by one so that new effect chain is created on new thread with
5668 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005669 int dstOutput = dstThread->id();
5670 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005671 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005672 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5673 while (effect != 0) {
5674 srcThread->removeEffect_l(effect);
5675 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005676 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5677 if (effect->state() == EffectModule::ACTIVE ||
5678 effect->state() == EffectModule::STOPPING) {
5679 effect->start();
5680 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005681 // if the move request is not received from audio policy manager, the effect must be
5682 // re-registered with the new strategy and output
5683 if (dstChain == 0) {
5684 dstChain = effect->chain().promote();
5685 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005686 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005687 srcThread->addEffect_l(effect);
5688 return NO_INIT;
5689 }
5690 strategy = dstChain->strategy();
5691 }
5692 if (reRegister) {
5693 AudioSystem::unregisterEffect(effect->id());
5694 AudioSystem::registerEffect(&effect->desc(),
5695 dstOutput,
5696 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005697 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005698 effect->id());
5699 }
Eric Laurentde070132010-07-13 04:45:46 -07005700 effect = chain->getEffectFromId_l(0);
5701 }
5702
5703 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704}
5705
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005706
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005708sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 const sp<AudioFlinger::Client>& client,
5710 const sp<IEffectClient>& effectClient,
5711 int32_t priority,
5712 int sessionId,
5713 effect_descriptor_t *desc,
5714 int *enabled,
5715 status_t *status
5716 )
5717{
5718 sp<EffectModule> effect;
5719 sp<EffectHandle> handle;
5720 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005722 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 bool effectCreated = false;
5724 bool effectRegistered = false;
5725
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005726 lStatus = initCheck();
5727 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005728 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 goto Exit;
5730 }
5731
5732 // Do not allow effects with session ID 0 on direct output or duplicating threads
5733 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005734 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005735 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005736 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 lStatus = BAD_VALUE;
5738 goto Exit;
5739 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005740 // Only Pre processor effects are allowed on input threads and only on input threads
5741 if ((mType == RECORD &&
5742 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5743 (mType != RECORD &&
5744 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005745 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005746 desc->name, desc->flags, mType);
5747 lStatus = BAD_VALUE;
5748 goto Exit;
5749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750
Steve Block3856b092011-10-20 11:56:00 +01005751 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005752
5753 { // scope for mLock
5754 Mutex::Autolock _l(mLock);
5755
5756 // check for existing effect chain with the requested audio session
5757 chain = getEffectChain_l(sessionId);
5758 if (chain == 0) {
5759 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005760 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 chain = new EffectChain(this, sessionId);
5762 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005763 chain->setStrategy(getStrategyForSession_l(sessionId));
5764 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005765 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005766 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767 }
5768
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005769 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770
5771 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005772 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005773 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005774 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 if (lStatus != NO_ERROR) {
5776 goto Exit;
5777 }
5778 effectRegistered = true;
5779 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005780 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781 lStatus = effect->status();
5782 if (lStatus != NO_ERROR) {
5783 goto Exit;
5784 }
Eric Laurentcab11242010-07-15 12:50:15 -07005785 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786 if (lStatus != NO_ERROR) {
5787 goto Exit;
5788 }
5789 effectCreated = true;
5790
5791 effect->setDevice(mDevice);
5792 effect->setMode(mAudioFlinger->getMode());
5793 }
5794 // create effect handle and connect it to effect module
5795 handle = new EffectHandle(effect, client, effectClient, priority);
5796 lStatus = effect->addHandle(handle);
5797 if (enabled) {
5798 *enabled = (int)effect->isEnabled();
5799 }
5800 }
5801
5802Exit:
5803 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005804 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005806 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 }
5808 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005809 AudioSystem::unregisterEffect(effect->id());
5810 }
5811 if (chainCreated) {
5812 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 }
5814 handle.clear();
5815 }
5816
5817 if(status) {
5818 *status = lStatus;
5819 }
5820 return handle;
5821}
5822
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005823sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5824{
5825 sp<EffectModule> effect;
5826
5827 sp<EffectChain> chain = getEffectChain_l(sessionId);
5828 if (chain != 0) {
5829 effect = chain->getEffectFromId_l(effectId);
5830 }
5831 return effect;
5832}
5833
Eric Laurentde070132010-07-13 04:45:46 -07005834// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5835// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005836status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005837{
5838 // check for existing effect chain with the requested audio session
5839 int sessionId = effect->sessionId();
5840 sp<EffectChain> chain = getEffectChain_l(sessionId);
5841 bool chainCreated = false;
5842
5843 if (chain == 0) {
5844 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005845 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005846 chain = new EffectChain(this, sessionId);
5847 addEffectChain_l(chain);
5848 chain->setStrategy(getStrategyForSession_l(sessionId));
5849 chainCreated = true;
5850 }
Steve Block3856b092011-10-20 11:56:00 +01005851 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005852
5853 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005854 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005855 this, effect->desc().name, chain.get());
5856 return BAD_VALUE;
5857 }
5858
5859 status_t status = chain->addEffect_l(effect);
5860 if (status != NO_ERROR) {
5861 if (chainCreated) {
5862 removeEffectChain_l(chain);
5863 }
5864 return status;
5865 }
5866
5867 effect->setDevice(mDevice);
5868 effect->setMode(mAudioFlinger->getMode());
5869 return NO_ERROR;
5870}
5871
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005872void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005873
Steve Block3856b092011-10-20 11:56:00 +01005874 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005875 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005876 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5877 detachAuxEffect_l(effect->id());
5878 }
5879
5880 sp<EffectChain> chain = effect->chain().promote();
5881 if (chain != 0) {
5882 // remove effect chain if removing last effect
5883 if (chain->removeEffect_l(effect) == 0) {
5884 removeEffectChain_l(chain);
5885 }
5886 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005887 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005888 }
5889}
5890
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005891void AudioFlinger::ThreadBase::lockEffectChains_l(
5892 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5893{
5894 effectChains = mEffectChains;
5895 for (size_t i = 0; i < mEffectChains.size(); i++) {
5896 mEffectChains[i]->lock();
5897 }
5898}
5899
5900void AudioFlinger::ThreadBase::unlockEffectChains(
5901 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5902{
5903 for (size_t i = 0; i < effectChains.size(); i++) {
5904 effectChains[i]->unlock();
5905 }
5906}
5907
5908sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5909{
5910 Mutex::Autolock _l(mLock);
5911 return getEffectChain_l(sessionId);
5912}
5913
5914sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5915{
5916 sp<EffectChain> chain;
5917
5918 size_t size = mEffectChains.size();
5919 for (size_t i = 0; i < size; i++) {
5920 if (mEffectChains[i]->sessionId() == sessionId) {
5921 chain = mEffectChains[i];
5922 break;
5923 }
5924 }
5925 return chain;
5926}
5927
Glenn Kastenf78aee72012-01-04 11:00:47 -08005928void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005929{
5930 Mutex::Autolock _l(mLock);
5931 size_t size = mEffectChains.size();
5932 for (size_t i = 0; i < size; i++) {
5933 mEffectChains[i]->setMode_l(mode);
5934 }
5935}
5936
5937void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005938 const wp<EffectHandle>& handle,
5939 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005940
Mathias Agopian65ab4712010-07-14 17:59:35 -07005941 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005942 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 // delete the effect module if removing last handle on it
5944 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005945 if (!effect->isPinned() || unpiniflast) {
5946 removeEffect_l(effect);
5947 AudioSystem::unregisterEffect(effect->id());
5948 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949 }
5950}
5951
5952status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5953{
5954 int session = chain->sessionId();
5955 int16_t *buffer = mMixBuffer;
5956 bool ownsBuffer = false;
5957
Steve Block3856b092011-10-20 11:56:00 +01005958 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 if (session > 0) {
5960 // Only one effect chain can be present in direct output thread and it uses
5961 // the mix buffer as input
5962 if (mType != DIRECT) {
5963 size_t numSamples = mFrameCount * mChannelCount;
5964 buffer = new int16_t[numSamples];
5965 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005966 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 ownsBuffer = true;
5968 }
5969
5970 // Attach all tracks with same session ID to this chain.
5971 for (size_t i = 0; i < mTracks.size(); ++i) {
5972 sp<Track> track = mTracks[i];
5973 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005974 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005976 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 }
5978 }
5979
5980 // indicate all active tracks in the chain
5981 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5982 sp<Track> track = mActiveTracks[i].promote();
5983 if (track == 0) continue;
5984 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005985 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005986 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 }
5988 }
5989 }
5990
5991 chain->setInBuffer(buffer, ownsBuffer);
5992 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005993 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005994 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005995 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5996 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005998 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5999 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006000 // Effect chain for other sessions are inserted at beginning of effect
6001 // chains list to be processed before output mix effects. Relative order between other
6002 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 size_t size = mEffectChains.size();
6004 size_t i = 0;
6005 for (i = 0; i < size; i++) {
6006 if (mEffectChains[i]->sessionId() < session) break;
6007 }
6008 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006009 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010
6011 return NO_ERROR;
6012}
6013
6014size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6015{
6016 int session = chain->sessionId();
6017
Steve Block3856b092011-10-20 11:56:00 +01006018 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006019
6020 for (size_t i = 0; i < mEffectChains.size(); i++) {
6021 if (chain == mEffectChains[i]) {
6022 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006023 // detach all active tracks from the chain
6024 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6025 sp<Track> track = mActiveTracks[i].promote();
6026 if (track == 0) continue;
6027 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006028 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006029 chain.get(), session);
6030 chain->decActiveTrackCnt();
6031 }
6032 }
6033
Mathias Agopian65ab4712010-07-14 17:59:35 -07006034 // detach all tracks with same session ID from this chain
6035 for (size_t i = 0; i < mTracks.size(); ++i) {
6036 sp<Track> track = mTracks[i];
6037 if (session == track->sessionId()) {
6038 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006039 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 }
6041 }
Eric Laurentde070132010-07-13 04:45:46 -07006042 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 }
6044 }
6045 return mEffectChains.size();
6046}
6047
Eric Laurentde070132010-07-13 04:45:46 -07006048status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6049 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050{
6051 Mutex::Autolock _l(mLock);
6052 return attachAuxEffect_l(track, EffectId);
6053}
6054
Eric Laurentde070132010-07-13 04:45:46 -07006055status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6056 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006057{
6058 status_t status = NO_ERROR;
6059
6060 if (EffectId == 0) {
6061 track->setAuxBuffer(0, NULL);
6062 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006063 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6064 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065 if (effect != 0) {
6066 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6067 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6068 } else {
6069 status = INVALID_OPERATION;
6070 }
6071 } else {
6072 status = BAD_VALUE;
6073 }
6074 }
6075 return status;
6076}
6077
6078void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6079{
6080 for (size_t i = 0; i < mTracks.size(); ++i) {
6081 sp<Track> track = mTracks[i];
6082 if (track->auxEffectId() == effectId) {
6083 attachAuxEffect_l(track, 0);
6084 }
6085 }
6086}
6087
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006088status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6089{
6090 // only one chain per input thread
6091 if (mEffectChains.size() != 0) {
6092 return INVALID_OPERATION;
6093 }
Steve Block3856b092011-10-20 11:56:00 +01006094 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006095
6096 chain->setInBuffer(NULL);
6097 chain->setOutBuffer(NULL);
6098
Eric Laurent59255e42011-07-27 19:49:51 -07006099 checkSuspendOnAddEffectChain_l(chain);
6100
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006101 mEffectChains.add(chain);
6102
6103 return NO_ERROR;
6104}
6105
6106size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6107{
Steve Block3856b092011-10-20 11:56:00 +01006108 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006109 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006110 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6111 chain.get(), mEffectChains.size(), this);
6112 if (mEffectChains.size() == 1) {
6113 mEffectChains.removeAt(0);
6114 }
6115 return 0;
6116}
6117
Mathias Agopian65ab4712010-07-14 17:59:35 -07006118// ----------------------------------------------------------------------------
6119// EffectModule implementation
6120// ----------------------------------------------------------------------------
6121
6122#undef LOG_TAG
6123#define LOG_TAG "AudioFlinger::EffectModule"
6124
6125AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6126 const wp<AudioFlinger::EffectChain>& chain,
6127 effect_descriptor_t *desc,
6128 int id,
6129 int sessionId)
6130 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006131 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132{
Steve Block3856b092011-10-20 11:56:00 +01006133 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134 int lStatus;
6135 sp<ThreadBase> thread = mThread.promote();
6136 if (thread == 0) {
6137 return;
6138 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139
6140 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6141
6142 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006143 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144
6145 if (mStatus != NO_ERROR) {
6146 return;
6147 }
6148 lStatus = init();
6149 if (lStatus < 0) {
6150 mStatus = lStatus;
6151 goto Error;
6152 }
6153
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006154 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6155 mPinned = true;
6156 }
Steve Block3856b092011-10-20 11:56:00 +01006157 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 return;
6159Error:
6160 EffectRelease(mEffectInterface);
6161 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006162 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163}
6164
6165AudioFlinger::EffectModule::~EffectModule()
6166{
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006169 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6170 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6171 sp<ThreadBase> thread = mThread.promote();
6172 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006173 audio_stream_t *stream = thread->stream();
6174 if (stream != NULL) {
6175 stream->remove_audio_effect(stream, mEffectInterface);
6176 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006177 }
6178 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179 // release effect engine
6180 EffectRelease(mEffectInterface);
6181 }
6182}
6183
Glenn Kasten435dbe62012-01-30 10:15:48 -08006184status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185{
6186 status_t status;
6187
6188 Mutex::Autolock _l(mLock);
6189 // First handle in mHandles has highest priority and controls the effect module
6190 int priority = handle->priority();
6191 size_t size = mHandles.size();
6192 sp<EffectHandle> h;
6193 size_t i;
6194 for (i = 0; i < size; i++) {
6195 h = mHandles[i].promote();
6196 if (h == 0) continue;
6197 if (h->priority() <= priority) break;
6198 }
6199 // if inserted in first place, move effect control from previous owner to this handle
6200 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006201 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006203 enabled = h->enabled();
6204 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 }
Eric Laurent59255e42011-07-27 19:49:51 -07006206 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 status = NO_ERROR;
6208 } else {
6209 status = ALREADY_EXISTS;
6210 }
Steve Block3856b092011-10-20 11:56:00 +01006211 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 mHandles.insertAt(handle, i);
6213 return status;
6214}
6215
6216size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6217{
6218 Mutex::Autolock _l(mLock);
6219 size_t size = mHandles.size();
6220 size_t i;
6221 for (i = 0; i < size; i++) {
6222 if (mHandles[i] == handle) break;
6223 }
6224 if (i == size) {
6225 return size;
6226 }
Steve Block3856b092011-10-20 11:56:00 +01006227 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006228
6229 bool enabled = false;
6230 EffectHandle *hdl = handle.unsafe_get();
6231 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006232 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006233 enabled = hdl->enabled();
6234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 mHandles.removeAt(i);
6236 size = mHandles.size();
6237 // if removed from first place, move effect control from this handle to next in line
6238 if (i == 0 && size != 0) {
6239 sp<EffectHandle> h = mHandles[0].promote();
6240 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006241 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 }
6243 }
6244
Eric Laurentec437d82011-07-26 20:54:46 -07006245 // Prevent calls to process() and other functions on effect interface from now on.
6246 // The effect engine will be released by the destructor when the last strong reference on
6247 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006248 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006249 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006250 }
6251
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252 return size;
6253}
6254
Eric Laurent59255e42011-07-27 19:49:51 -07006255sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6256{
6257 Mutex::Autolock _l(mLock);
6258 sp<EffectHandle> handle;
6259 if (mHandles.size() != 0) {
6260 handle = mHandles[0].promote();
6261 }
6262 return handle;
6263}
6264
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006265void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266{
Steve Block3856b092011-10-20 11:56:00 +01006267 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268 // keep a strong reference on this EffectModule to avoid calling the
6269 // destructor before we exit
6270 sp<EffectModule> keep(this);
6271 {
6272 sp<ThreadBase> thread = mThread.promote();
6273 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006274 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 }
6276 }
6277}
6278
6279void AudioFlinger::EffectModule::updateState() {
6280 Mutex::Autolock _l(mLock);
6281
6282 switch (mState) {
6283 case RESTART:
6284 reset_l();
6285 // FALL THROUGH
6286
6287 case STARTING:
6288 // clear auxiliary effect input buffer for next accumulation
6289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6290 memset(mConfig.inputCfg.buffer.raw,
6291 0,
6292 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6293 }
6294 start_l();
6295 mState = ACTIVE;
6296 break;
6297 case STOPPING:
6298 stop_l();
6299 mDisableWaitCnt = mMaxDisableWaitCnt;
6300 mState = STOPPED;
6301 break;
6302 case STOPPED:
6303 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6304 // turn off sequence.
6305 if (--mDisableWaitCnt == 0) {
6306 reset_l();
6307 mState = IDLE;
6308 }
6309 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006310 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 break;
6312 }
6313}
6314
6315void AudioFlinger::EffectModule::process()
6316{
6317 Mutex::Autolock _l(mLock);
6318
Eric Laurentec437d82011-07-26 20:54:46 -07006319 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006320 mConfig.inputCfg.buffer.raw == NULL ||
6321 mConfig.outputCfg.buffer.raw == NULL) {
6322 return;
6323 }
6324
Eric Laurent8f45bd72010-08-31 13:50:07 -07006325 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006326 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6327 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006328 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006330 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 }
6332
6333 // do the actual processing in the effect engine
6334 int ret = (*mEffectInterface)->process(mEffectInterface,
6335 &mConfig.inputCfg.buffer,
6336 &mConfig.outputCfg.buffer);
6337
6338 // force transition to IDLE state when engine is ready
6339 if (mState == STOPPED && ret == -ENODATA) {
6340 mDisableWaitCnt = 1;
6341 }
6342
6343 // clear auxiliary effect input buffer for next accumulation
6344 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006345 memset(mConfig.inputCfg.buffer.raw, 0,
6346 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 }
6348 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006349 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6350 // If an insert effect is idle and input buffer is different from output buffer,
6351 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006353 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006354 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6355 int16_t *in = mConfig.inputCfg.buffer.s16;
6356 int16_t *out = mConfig.outputCfg.buffer.s16;
6357 for (size_t i = 0; i < frameCnt; i++) {
6358 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006359 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 }
6361 }
6362}
6363
6364void AudioFlinger::EffectModule::reset_l()
6365{
6366 if (mEffectInterface == NULL) {
6367 return;
6368 }
6369 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6370}
6371
6372status_t AudioFlinger::EffectModule::configure()
6373{
6374 uint32_t channels;
6375 if (mEffectInterface == NULL) {
6376 return NO_INIT;
6377 }
6378
6379 sp<ThreadBase> thread = mThread.promote();
6380 if (thread == 0) {
6381 return DEAD_OBJECT;
6382 }
6383
6384 // TODO: handle configuration of effects replacing track process
6385 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006386 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006387 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006388 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389 }
6390
6391 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006392 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393 } else {
6394 mConfig.inputCfg.channels = channels;
6395 }
6396 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006397 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6398 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 mConfig.inputCfg.samplingRate = thread->sampleRate();
6400 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6401 mConfig.inputCfg.bufferProvider.cookie = NULL;
6402 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6403 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6404 mConfig.outputCfg.bufferProvider.cookie = NULL;
6405 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6406 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6407 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6408 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006409 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006410 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006411 // - in other sessions:
6412 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6413 // other effect: overwrites output buffer: input buffer == output buffer
6414 // Auxiliary effect:
6415 // accumulates in output buffer: input buffer != output buffer
6416 // Therefore: accumulate <=> input buffer != output buffer
6417 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6418 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6419 } else {
6420 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6421 }
6422 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6423 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6424 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6425 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6426
Steve Block3856b092011-10-20 11:56:00 +01006427 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006428 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6429
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006431 uint32_t size = sizeof(int);
6432 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006433 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006434 sizeof(effect_config_t),
6435 &mConfig,
6436 &size,
6437 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438 if (status == 0) {
6439 status = cmdStatus;
6440 }
6441
6442 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6443 (1000 * mConfig.outputCfg.buffer.frameCount);
6444
6445 return status;
6446}
6447
6448status_t AudioFlinger::EffectModule::init()
6449{
6450 Mutex::Autolock _l(mLock);
6451 if (mEffectInterface == NULL) {
6452 return NO_INIT;
6453 }
6454 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006455 uint32_t size = sizeof(status_t);
6456 status_t status = (*mEffectInterface)->command(mEffectInterface,
6457 EFFECT_CMD_INIT,
6458 0,
6459 NULL,
6460 &size,
6461 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462 if (status == 0) {
6463 status = cmdStatus;
6464 }
6465 return status;
6466}
6467
Eric Laurentec35a142011-10-05 17:42:25 -07006468status_t AudioFlinger::EffectModule::start()
6469{
6470 Mutex::Autolock _l(mLock);
6471 return start_l();
6472}
6473
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474status_t AudioFlinger::EffectModule::start_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_ENABLE,
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->add_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 Laurentec437d82011-07-26 20:54:46 -07006504status_t AudioFlinger::EffectModule::stop()
6505{
6506 Mutex::Autolock _l(mLock);
6507 return stop_l();
6508}
6509
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510status_t AudioFlinger::EffectModule::stop_l()
6511{
6512 if (mEffectInterface == NULL) {
6513 return NO_INIT;
6514 }
6515 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006516 uint32_t size = sizeof(status_t);
6517 status_t status = (*mEffectInterface)->command(mEffectInterface,
6518 EFFECT_CMD_DISABLE,
6519 0,
6520 NULL,
6521 &size,
6522 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 if (status == 0) {
6524 status = cmdStatus;
6525 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006526 if (status == 0 &&
6527 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6528 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6529 sp<ThreadBase> thread = mThread.promote();
6530 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006531 audio_stream_t *stream = thread->stream();
6532 if (stream != NULL) {
6533 stream->remove_audio_effect(stream, mEffectInterface);
6534 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006535 }
6536 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537 return status;
6538}
6539
Eric Laurent25f43952010-07-28 05:40:18 -07006540status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6541 uint32_t cmdSize,
6542 void *pCmdData,
6543 uint32_t *replySize,
6544 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545{
6546 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006547// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548
Eric Laurentec437d82011-07-26 20:54:46 -07006549 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 return NO_INIT;
6551 }
Eric Laurent25f43952010-07-28 05:40:18 -07006552 status_t status = (*mEffectInterface)->command(mEffectInterface,
6553 cmdCode,
6554 cmdSize,
6555 pCmdData,
6556 replySize,
6557 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006559 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560 for (size_t i = 1; i < mHandles.size(); i++) {
6561 sp<EffectHandle> h = mHandles[i].promote();
6562 if (h != 0) {
6563 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6564 }
6565 }
6566 }
6567 return status;
6568}
6569
6570status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6571{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006572
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006574 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575
6576 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006577 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6578 if (enabled && status != NO_ERROR) {
6579 return status;
6580 }
6581
Mathias Agopian65ab4712010-07-14 17:59:35 -07006582 switch (mState) {
6583 // going from disabled to enabled
6584 case IDLE:
6585 mState = STARTING;
6586 break;
6587 case STOPPED:
6588 mState = RESTART;
6589 break;
6590 case STOPPING:
6591 mState = ACTIVE;
6592 break;
6593
6594 // going from enabled to disabled
6595 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006596 mState = STOPPED;
6597 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006598 case STARTING:
6599 mState = IDLE;
6600 break;
6601 case ACTIVE:
6602 mState = STOPPING;
6603 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006604 case DESTROYED:
6605 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 }
6607 for (size_t i = 1; i < mHandles.size(); i++) {
6608 sp<EffectHandle> h = mHandles[i].promote();
6609 if (h != 0) {
6610 h->setEnabled(enabled);
6611 }
6612 }
6613 }
6614 return NO_ERROR;
6615}
6616
6617bool AudioFlinger::EffectModule::isEnabled()
6618{
6619 switch (mState) {
6620 case RESTART:
6621 case STARTING:
6622 case ACTIVE:
6623 return true;
6624 case IDLE:
6625 case STOPPING:
6626 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006627 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 default:
6629 return false;
6630 }
6631}
6632
Eric Laurent8f45bd72010-08-31 13:50:07 -07006633bool AudioFlinger::EffectModule::isProcessEnabled()
6634{
6635 switch (mState) {
6636 case RESTART:
6637 case ACTIVE:
6638 case STOPPING:
6639 case STOPPED:
6640 return true;
6641 case IDLE:
6642 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006643 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006644 default:
6645 return false;
6646 }
6647}
6648
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6650{
6651 Mutex::Autolock _l(mLock);
6652 status_t status = NO_ERROR;
6653
6654 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6655 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006656 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006657 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6658 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659 status_t cmdStatus;
6660 uint32_t volume[2];
6661 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006662 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663 volume[0] = *left;
6664 volume[1] = *right;
6665 if (controller) {
6666 pVolume = volume;
6667 }
Eric Laurent25f43952010-07-28 05:40:18 -07006668 status = (*mEffectInterface)->command(mEffectInterface,
6669 EFFECT_CMD_SET_VOLUME,
6670 size,
6671 volume,
6672 &size,
6673 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6675 *left = volume[0];
6676 *right = volume[1];
6677 }
6678 }
6679 return status;
6680}
6681
6682status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6683{
6684 Mutex::Autolock _l(mLock);
6685 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006686 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6687 // audio pre processing modules on RecordThread can receive both output and
6688 // input device indication in the same call
6689 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6690 if (dev) {
6691 status_t cmdStatus;
6692 uint32_t size = sizeof(status_t);
6693
6694 status = (*mEffectInterface)->command(mEffectInterface,
6695 EFFECT_CMD_SET_DEVICE,
6696 sizeof(uint32_t),
6697 &dev,
6698 &size,
6699 &cmdStatus);
6700 if (status == NO_ERROR) {
6701 status = cmdStatus;
6702 }
6703 }
6704 dev = device & AUDIO_DEVICE_IN_ALL;
6705 if (dev) {
6706 status_t cmdStatus;
6707 uint32_t size = sizeof(status_t);
6708
6709 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6710 EFFECT_CMD_SET_INPUT_DEVICE,
6711 sizeof(uint32_t),
6712 &dev,
6713 &size,
6714 &cmdStatus);
6715 if (status2 == NO_ERROR) {
6716 status2 = cmdStatus;
6717 }
6718 if (status == NO_ERROR) {
6719 status = status2;
6720 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 }
6722 }
6723 return status;
6724}
6725
Glenn Kastenf78aee72012-01-04 11:00:47 -08006726status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006727{
6728 Mutex::Autolock _l(mLock);
6729 status_t status = NO_ERROR;
6730 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006732 uint32_t size = sizeof(status_t);
6733 status = (*mEffectInterface)->command(mEffectInterface,
6734 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006735 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006736 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006737 &size,
6738 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006739 if (status == NO_ERROR) {
6740 status = cmdStatus;
6741 }
6742 }
6743 return status;
6744}
6745
Eric Laurent59255e42011-07-27 19:49:51 -07006746void AudioFlinger::EffectModule::setSuspended(bool suspended)
6747{
6748 Mutex::Autolock _l(mLock);
6749 mSuspended = suspended;
6750}
Glenn Kastena3a85482012-01-04 11:01:11 -08006751
6752bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006753{
6754 Mutex::Autolock _l(mLock);
6755 return mSuspended;
6756}
6757
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6759{
6760 const size_t SIZE = 256;
6761 char buffer[SIZE];
6762 String8 result;
6763
6764 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6765 result.append(buffer);
6766
6767 bool locked = tryLock(mLock);
6768 // failed to lock - AudioFlinger is probably deadlocked
6769 if (!locked) {
6770 result.append("\t\tCould not lock Fx mutex:\n");
6771 }
6772
6773 result.append("\t\tSession Status State Engine:\n");
6774 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6775 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6776 result.append(buffer);
6777
6778 result.append("\t\tDescriptor:\n");
6779 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6780 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6781 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6782 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6783 result.append(buffer);
6784 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6785 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6786 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6787 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6788 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006789 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 mDescriptor.apiVersion,
6791 mDescriptor.flags);
6792 result.append(buffer);
6793 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6794 mDescriptor.name);
6795 result.append(buffer);
6796 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6797 mDescriptor.implementor);
6798 result.append(buffer);
6799
6800 result.append("\t\t- Input configuration:\n");
6801 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6802 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6803 (uint32_t)mConfig.inputCfg.buffer.raw,
6804 mConfig.inputCfg.buffer.frameCount,
6805 mConfig.inputCfg.samplingRate,
6806 mConfig.inputCfg.channels,
6807 mConfig.inputCfg.format);
6808 result.append(buffer);
6809
6810 result.append("\t\t- Output configuration:\n");
6811 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6812 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6813 (uint32_t)mConfig.outputCfg.buffer.raw,
6814 mConfig.outputCfg.buffer.frameCount,
6815 mConfig.outputCfg.samplingRate,
6816 mConfig.outputCfg.channels,
6817 mConfig.outputCfg.format);
6818 result.append(buffer);
6819
6820 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6821 result.append(buffer);
6822 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6823 for (size_t i = 0; i < mHandles.size(); ++i) {
6824 sp<EffectHandle> handle = mHandles[i].promote();
6825 if (handle != 0) {
6826 handle->dump(buffer, SIZE);
6827 result.append(buffer);
6828 }
6829 }
6830
6831 result.append("\n");
6832
6833 write(fd, result.string(), result.length());
6834
6835 if (locked) {
6836 mLock.unlock();
6837 }
6838
6839 return NO_ERROR;
6840}
6841
6842// ----------------------------------------------------------------------------
6843// EffectHandle implementation
6844// ----------------------------------------------------------------------------
6845
6846#undef LOG_TAG
6847#define LOG_TAG "AudioFlinger::EffectHandle"
6848
6849AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6850 const sp<AudioFlinger::Client>& client,
6851 const sp<IEffectClient>& effectClient,
6852 int32_t priority)
6853 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006854 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006855 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856{
Steve Block3856b092011-10-20 11:56:00 +01006857 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006859 if (client == 0) {
6860 return;
6861 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6863 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6864 if (mCblkMemory != 0) {
6865 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6866
6867 if (mCblk) {
6868 new(mCblk) effect_param_cblk_t();
6869 mBuffer = (uint8_t *)mCblk + bufOffset;
6870 }
6871 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006872 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873 return;
6874 }
6875}
6876
6877AudioFlinger::EffectHandle::~EffectHandle()
6878{
Steve Block3856b092011-10-20 11:56:00 +01006879 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006880 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006881 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882}
6883
6884status_t AudioFlinger::EffectHandle::enable()
6885{
Steve Block3856b092011-10-20 11:56:00 +01006886 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 if (!mHasControl) return INVALID_OPERATION;
6888 if (mEffect == 0) return DEAD_OBJECT;
6889
Eric Laurentdb7c0792011-08-10 10:37:50 -07006890 if (mEnabled) {
6891 return NO_ERROR;
6892 }
6893
Eric Laurent59255e42011-07-27 19:49:51 -07006894 mEnabled = true;
6895
6896 sp<ThreadBase> thread = mEffect->thread().promote();
6897 if (thread != 0) {
6898 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6899 }
6900
6901 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6902 if (mEffect->suspended()) {
6903 return NO_ERROR;
6904 }
6905
Eric Laurentdb7c0792011-08-10 10:37:50 -07006906 status_t status = mEffect->setEnabled(true);
6907 if (status != NO_ERROR) {
6908 if (thread != 0) {
6909 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6910 }
6911 mEnabled = false;
6912 }
6913 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914}
6915
6916status_t AudioFlinger::EffectHandle::disable()
6917{
Steve Block3856b092011-10-20 11:56:00 +01006918 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006920 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921
Eric Laurentdb7c0792011-08-10 10:37:50 -07006922 if (!mEnabled) {
6923 return NO_ERROR;
6924 }
Eric Laurent59255e42011-07-27 19:49:51 -07006925 mEnabled = false;
6926
6927 if (mEffect->suspended()) {
6928 return NO_ERROR;
6929 }
6930
6931 status_t status = mEffect->setEnabled(false);
6932
6933 sp<ThreadBase> thread = mEffect->thread().promote();
6934 if (thread != 0) {
6935 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6936 }
6937
6938 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006939}
6940
6941void AudioFlinger::EffectHandle::disconnect()
6942{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006943 disconnect(true);
6944}
6945
6946void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6947{
Steve Block3856b092011-10-20 11:56:00 +01006948 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949 if (mEffect == 0) {
6950 return;
6951 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006952 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006953
Eric Laurenta85a74a2011-10-19 11:44:54 -07006954 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006955 sp<ThreadBase> thread = mEffect->thread().promote();
6956 if (thread != 0) {
6957 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6958 }
Eric Laurent59255e42011-07-27 19:49:51 -07006959 }
6960
Mathias Agopian65ab4712010-07-14 17:59:35 -07006961 // release sp on module => module destructor can be called now
6962 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006964 if (mCblk) {
6965 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6966 }
6967 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006968 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6969 mClient.clear();
6970 }
6971}
6972
Eric Laurent25f43952010-07-28 05:40:18 -07006973status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6974 uint32_t cmdSize,
6975 void *pCmdData,
6976 uint32_t *replySize,
6977 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978{
Steve Block3856b092011-10-20 11:56:00 +01006979// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006980// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981
6982 // only get parameter command is permitted for applications not controlling the effect
6983 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6984 return INVALID_OPERATION;
6985 }
6986 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006987 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988
6989 // handle commands that are not forwarded transparently to effect engine
6990 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6991 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6992 // no risk to block the whole media server process or mixer threads is we are stuck here
6993 Mutex::Autolock _l(mCblk->lock);
6994 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6995 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6996 mCblk->serverIndex = 0;
6997 mCblk->clientIndex = 0;
6998 return BAD_VALUE;
6999 }
7000 status_t status = NO_ERROR;
7001 while (mCblk->serverIndex < mCblk->clientIndex) {
7002 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007003 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004 int *p = (int *)(mBuffer + mCblk->serverIndex);
7005 int size = *p++;
7006 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007007 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008 break;
7009 }
7010 effect_param_t *param = (effect_param_t *)p;
7011 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007012 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 mCblk->serverIndex += size;
7014 continue;
7015 }
Eric Laurent25f43952010-07-28 05:40:18 -07007016 uint32_t psize = sizeof(effect_param_t) +
7017 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7018 param->vsize;
7019 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7020 psize,
7021 p,
7022 &rsize,
7023 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007024 // stop at first error encountered
7025 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007027 *(int *)pReplyData = reply;
7028 break;
7029 } else if (reply != NO_ERROR) {
7030 *(int *)pReplyData = reply;
7031 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 }
7033 mCblk->serverIndex += size;
7034 }
7035 mCblk->serverIndex = 0;
7036 mCblk->clientIndex = 0;
7037 return status;
7038 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007039 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 return enable();
7041 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007042 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007043 return disable();
7044 }
7045
7046 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7047}
7048
7049sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7050 return mCblkMemory;
7051}
7052
Eric Laurent59255e42011-07-27 19:49:51 -07007053void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054{
Steve Block3856b092011-10-20 11:56:00 +01007055 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056
7057 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007058 mEnabled = enabled;
7059
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060 if (signal && mEffectClient != 0) {
7061 mEffectClient->controlStatusChanged(hasControl);
7062 }
7063}
7064
Eric Laurent25f43952010-07-28 05:40:18 -07007065void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7066 uint32_t cmdSize,
7067 void *pCmdData,
7068 uint32_t replySize,
7069 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070{
7071 if (mEffectClient != 0) {
7072 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7073 }
7074}
7075
7076
7077
7078void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7079{
7080 if (mEffectClient != 0) {
7081 mEffectClient->enableStatusChanged(enabled);
7082 }
7083}
7084
7085status_t AudioFlinger::EffectHandle::onTransact(
7086 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7087{
7088 return BnEffect::onTransact(code, data, reply, flags);
7089}
7090
7091
7092void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7093{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007094 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095
7096 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7097 (mClient == NULL) ? getpid() : mClient->pid(),
7098 mPriority,
7099 mHasControl,
7100 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007101 mCblk ? mCblk->clientIndex : 0,
7102 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103 );
7104
7105 if (locked) {
7106 mCblk->lock.unlock();
7107 }
7108}
7109
7110#undef LOG_TAG
7111#define LOG_TAG "AudioFlinger::EffectChain"
7112
7113AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7114 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007115 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007116 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7117 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007118{
Dima Zavinfce7a472011-04-19 22:30:36 -07007119 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007120 sp<ThreadBase> thread = mThread.promote();
7121 if (thread == 0) {
7122 return;
7123 }
7124 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7125 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007126}
7127
7128AudioFlinger::EffectChain::~EffectChain()
7129{
7130 if (mOwnInBuffer) {
7131 delete mInBuffer;
7132 }
7133
7134}
7135
Eric Laurent59255e42011-07-27 19:49:51 -07007136// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007137sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138{
7139 sp<EffectModule> effect;
7140 size_t size = mEffects.size();
7141
7142 for (size_t i = 0; i < size; i++) {
7143 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7144 effect = mEffects[i];
7145 break;
7146 }
7147 }
7148 return effect;
7149}
7150
Eric Laurent59255e42011-07-27 19:49:51 -07007151// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007152sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153{
7154 sp<EffectModule> effect;
7155 size_t size = mEffects.size();
7156
7157 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007158 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7159 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 effect = mEffects[i];
7161 break;
7162 }
7163 }
7164 return effect;
7165}
7166
Eric Laurent59255e42011-07-27 19:49:51 -07007167// getEffectFromType_l() must be called with ThreadBase::mLock held
7168sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7169 const effect_uuid_t *type)
7170{
7171 sp<EffectModule> effect;
7172 size_t size = mEffects.size();
7173
7174 for (size_t i = 0; i < size; i++) {
7175 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7176 effect = mEffects[i];
7177 break;
7178 }
7179 }
7180 return effect;
7181}
7182
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183// Must be called with EffectChain::mLock locked
7184void AudioFlinger::EffectChain::process_l()
7185{
Eric Laurentdac69112010-09-28 14:09:57 -07007186 sp<ThreadBase> thread = mThread.promote();
7187 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007188 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007189 return;
7190 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007191 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7192 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007193 // always process effects unless no more tracks are on the session and the effect tail
7194 // has been rendered
7195 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007196 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007197 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007198
Eric Laurent544fe9b2011-11-11 15:42:52 -08007199 if (!tracksOnSession && mTailBufferCount == 0) {
7200 doProcess = false;
7201 }
7202
7203 if (activeTrackCnt() == 0) {
7204 // if no track is active and the effect tail has not been rendered,
7205 // the input buffer must be cleared here as the mixer process will not do it
7206 if (tracksOnSession || mTailBufferCount > 0) {
7207 size_t numSamples = thread->frameCount() * thread->channelCount();
7208 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7209 if (mTailBufferCount > 0) {
7210 mTailBufferCount--;
7211 }
7212 }
7213 }
Eric Laurentdac69112010-09-28 14:09:57 -07007214 }
7215
Mathias Agopian65ab4712010-07-14 17:59:35 -07007216 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007217 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007218 for (size_t i = 0; i < size; i++) {
7219 mEffects[i]->process();
7220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 }
7222 for (size_t i = 0; i < size; i++) {
7223 mEffects[i]->updateState();
7224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007225}
7226
Eric Laurentcab11242010-07-15 12:50:15 -07007227// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007228status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007229{
7230 effect_descriptor_t desc = effect->desc();
7231 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7232
7233 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007234 effect->setChain(this);
7235 sp<ThreadBase> thread = mThread.promote();
7236 if (thread == 0) {
7237 return NO_INIT;
7238 }
7239 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007240
7241 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7242 // Auxiliary effects are inserted at the beginning of mEffects vector as
7243 // they are processed first and accumulated in chain input buffer
7244 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007245
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246 // the input buffer for auxiliary effect contains mono samples in
7247 // 32 bit format. This is to avoid saturation in AudoMixer
7248 // accumulation stage. Saturation is done in EffectModule::process() before
7249 // calling the process in effect engine
7250 size_t numSamples = thread->frameCount();
7251 int32_t *buffer = new int32_t[numSamples];
7252 memset(buffer, 0, numSamples * sizeof(int32_t));
7253 effect->setInBuffer((int16_t *)buffer);
7254 // auxiliary effects output samples to chain input buffer for further processing
7255 // by insert effects
7256 effect->setOutBuffer(mInBuffer);
7257 } else {
7258 // Insert effects are inserted at the end of mEffects vector as they are processed
7259 // after track and auxiliary effects.
7260 // Insert effect order as a function of indicated preference:
7261 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7262 // another effect is present
7263 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7264 // last effect claiming first position
7265 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7266 // first effect claiming last position
7267 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7268 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7269 // already present
7270
7271 int size = (int)mEffects.size();
7272 int idx_insert = size;
7273 int idx_insert_first = -1;
7274 int idx_insert_last = -1;
7275
7276 for (int i = 0; i < size; i++) {
7277 effect_descriptor_t d = mEffects[i]->desc();
7278 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7279 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7280 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7281 // check invalid effect chaining combinations
7282 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7283 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007284 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 return INVALID_OPERATION;
7286 }
7287 // remember position of first insert effect and by default
7288 // select this as insert position for new effect
7289 if (idx_insert == size) {
7290 idx_insert = i;
7291 }
7292 // remember position of last insert effect claiming
7293 // first position
7294 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7295 idx_insert_first = i;
7296 }
7297 // remember position of first insert effect claiming
7298 // last position
7299 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7300 idx_insert_last == -1) {
7301 idx_insert_last = i;
7302 }
7303 }
7304 }
7305
7306 // modify idx_insert from first position if needed
7307 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7308 if (idx_insert_last != -1) {
7309 idx_insert = idx_insert_last;
7310 } else {
7311 idx_insert = size;
7312 }
7313 } else {
7314 if (idx_insert_first != -1) {
7315 idx_insert = idx_insert_first + 1;
7316 }
7317 }
7318
7319 // always read samples from chain input buffer
7320 effect->setInBuffer(mInBuffer);
7321
7322 // if last effect in the chain, output samples to chain
7323 // output buffer, otherwise to chain input buffer
7324 if (idx_insert == size) {
7325 if (idx_insert != 0) {
7326 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7327 mEffects[idx_insert-1]->configure();
7328 }
7329 effect->setOutBuffer(mOutBuffer);
7330 } else {
7331 effect->setOutBuffer(mInBuffer);
7332 }
7333 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334
Steve Block3856b092011-10-20 11:56:00 +01007335 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336 }
7337 effect->configure();
7338 return NO_ERROR;
7339}
7340
Eric Laurentcab11242010-07-15 12:50:15 -07007341// removeEffect_l() must be called with PlaybackThread::mLock held
7342size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343{
7344 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 int size = (int)mEffects.size();
7346 int i;
7347 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7348
7349 for (i = 0; i < size; i++) {
7350 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007351 // calling stop here will remove pre-processing effect from the audio HAL.
7352 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7353 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007354 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7355 mEffects[i]->state() == EffectModule::STOPPING) {
7356 mEffects[i]->stop();
7357 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7359 delete[] effect->inBuffer();
7360 } else {
7361 if (i == size - 1 && i != 0) {
7362 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7363 mEffects[i - 1]->configure();
7364 }
7365 }
7366 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007367 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 break;
7369 }
7370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007371
7372 return mEffects.size();
7373}
7374
Eric Laurentcab11242010-07-15 12:50:15 -07007375// setDevice_l() must be called with PlaybackThread::mLock held
7376void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377{
7378 size_t size = mEffects.size();
7379 for (size_t i = 0; i < size; i++) {
7380 mEffects[i]->setDevice(device);
7381 }
7382}
7383
Eric Laurentcab11242010-07-15 12:50:15 -07007384// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007385void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386{
7387 size_t size = mEffects.size();
7388 for (size_t i = 0; i < size; i++) {
7389 mEffects[i]->setMode(mode);
7390 }
7391}
7392
Eric Laurentcab11242010-07-15 12:50:15 -07007393// setVolume_l() must be called with PlaybackThread::mLock held
7394bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395{
7396 uint32_t newLeft = *left;
7397 uint32_t newRight = *right;
7398 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007399 int ctrlIdx = -1;
7400 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401
Eric Laurentcab11242010-07-15 12:50:15 -07007402 // first update volume controller
7403 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007404 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007405 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7406 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007407 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007408 break;
7409 }
7410 }
7411
7412 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007413 if (hasControl) {
7414 *left = mNewLeftVolume;
7415 *right = mNewRightVolume;
7416 }
7417 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007418 }
7419
7420 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007421 mLeftVolume = newLeft;
7422 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007423
7424 // second get volume update from volume controller
7425 if (ctrlIdx >= 0) {
7426 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007427 mNewLeftVolume = newLeft;
7428 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 }
7430 // then indicate volume to all other effects in chain.
7431 // Pass altered volume to effects before volume controller
7432 // and requested volume to effects after controller
7433 uint32_t lVol = newLeft;
7434 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007435
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007437 if ((int)i == ctrlIdx) continue;
7438 // this also works for ctrlIdx == -1 when there is no volume controller
7439 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007440 lVol = *left;
7441 rVol = *right;
7442 }
7443 mEffects[i]->setVolume(&lVol, &rVol, false);
7444 }
7445 *left = newLeft;
7446 *right = newRight;
7447
7448 return hasControl;
7449}
7450
Mathias Agopian65ab4712010-07-14 17:59:35 -07007451status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7452{
7453 const size_t SIZE = 256;
7454 char buffer[SIZE];
7455 String8 result;
7456
7457 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7458 result.append(buffer);
7459
7460 bool locked = tryLock(mLock);
7461 // failed to lock - AudioFlinger is probably deadlocked
7462 if (!locked) {
7463 result.append("\tCould not lock mutex:\n");
7464 }
7465
Eric Laurentcab11242010-07-15 12:50:15 -07007466 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7467 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007468 mEffects.size(),
7469 (uint32_t)mInBuffer,
7470 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007471 mActiveTrackCnt);
7472 result.append(buffer);
7473 write(fd, result.string(), result.size());
7474
7475 for (size_t i = 0; i < mEffects.size(); ++i) {
7476 sp<EffectModule> effect = mEffects[i];
7477 if (effect != 0) {
7478 effect->dump(fd, args);
7479 }
7480 }
7481
7482 if (locked) {
7483 mLock.unlock();
7484 }
7485
7486 return NO_ERROR;
7487}
7488
Eric Laurent59255e42011-07-27 19:49:51 -07007489// must be called with ThreadBase::mLock held
7490void AudioFlinger::EffectChain::setEffectSuspended_l(
7491 const effect_uuid_t *type, bool suspend)
7492{
7493 sp<SuspendedEffectDesc> desc;
7494 // use effect type UUID timelow as key as there is no real risk of identical
7495 // timeLow fields among effect type UUIDs.
7496 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7497 if (suspend) {
7498 if (index >= 0) {
7499 desc = mSuspendedEffects.valueAt(index);
7500 } else {
7501 desc = new SuspendedEffectDesc();
7502 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7503 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007504 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007505 }
7506 if (desc->mRefCount++ == 0) {
7507 sp<EffectModule> effect = getEffectIfEnabled(type);
7508 if (effect != 0) {
7509 desc->mEffect = effect;
7510 effect->setSuspended(true);
7511 effect->setEnabled(false);
7512 }
7513 }
7514 } else {
7515 if (index < 0) {
7516 return;
7517 }
7518 desc = mSuspendedEffects.valueAt(index);
7519 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007520 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007521 desc->mRefCount = 1;
7522 }
7523 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007524 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007525 if (desc->mEffect != 0) {
7526 sp<EffectModule> effect = desc->mEffect.promote();
7527 if (effect != 0) {
7528 effect->setSuspended(false);
7529 sp<EffectHandle> handle = effect->controlHandle();
7530 if (handle != 0) {
7531 effect->setEnabled(handle->enabled());
7532 }
7533 }
7534 desc->mEffect.clear();
7535 }
7536 mSuspendedEffects.removeItemsAt(index);
7537 }
7538 }
7539}
7540
7541// must be called with ThreadBase::mLock held
7542void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7543{
7544 sp<SuspendedEffectDesc> desc;
7545
7546 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7547 if (suspend) {
7548 if (index >= 0) {
7549 desc = mSuspendedEffects.valueAt(index);
7550 } else {
7551 desc = new SuspendedEffectDesc();
7552 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007553 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007554 }
7555 if (desc->mRefCount++ == 0) {
7556 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7557 for (size_t i = 0; i < effects.size(); i++) {
7558 setEffectSuspended_l(&effects[i]->desc().type, true);
7559 }
7560 }
7561 } else {
7562 if (index < 0) {
7563 return;
7564 }
7565 desc = mSuspendedEffects.valueAt(index);
7566 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007567 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007568 desc->mRefCount = 1;
7569 }
7570 if (--desc->mRefCount == 0) {
7571 Vector<const effect_uuid_t *> types;
7572 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7573 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7574 continue;
7575 }
7576 types.add(&mSuspendedEffects.valueAt(i)->mType);
7577 }
7578 for (size_t i = 0; i < types.size(); i++) {
7579 setEffectSuspended_l(types[i], false);
7580 }
Steve Block3856b092011-10-20 11:56:00 +01007581 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007582 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7583 }
7584 }
7585}
7586
Eric Laurent6bffdb82011-09-23 08:40:41 -07007587
7588// The volume effect is used for automated tests only
7589#ifndef OPENSL_ES_H_
7590static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7591 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7592const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7593#endif //OPENSL_ES_H_
7594
Eric Laurentdb7c0792011-08-10 10:37:50 -07007595bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7596{
7597 // auxiliary effects and visualizer are never suspended on output mix
7598 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7599 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007600 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7601 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007602 return false;
7603 }
7604 return true;
7605}
7606
Eric Laurent59255e42011-07-27 19:49:51 -07007607Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7608{
7609 Vector< sp<EffectModule> > effects;
7610 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007611 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007612 continue;
7613 }
7614 effects.add(mEffects[i]);
7615 }
7616 return effects;
7617}
7618
7619sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7620 const effect_uuid_t *type)
7621{
7622 sp<EffectModule> effect;
7623 effect = getEffectFromType_l(type);
7624 if (effect != 0 && !effect->isEnabled()) {
7625 effect.clear();
7626 }
7627 return effect;
7628}
7629
7630void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7631 bool enabled)
7632{
7633 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7634 if (enabled) {
7635 if (index < 0) {
7636 // if the effect is not suspend check if all effects are suspended
7637 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7638 if (index < 0) {
7639 return;
7640 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007641 if (!isEffectEligibleForSuspend(effect->desc())) {
7642 return;
7643 }
Eric Laurent59255e42011-07-27 19:49:51 -07007644 setEffectSuspended_l(&effect->desc().type, enabled);
7645 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007646 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007647 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007648 return;
7649 }
Eric Laurent59255e42011-07-27 19:49:51 -07007650 }
Steve Block3856b092011-10-20 11:56:00 +01007651 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007652 effect->desc().type.timeLow);
7653 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7654 // if effect is requested to suspended but was not yet enabled, supend it now.
7655 if (desc->mEffect == 0) {
7656 desc->mEffect = effect;
7657 effect->setEnabled(false);
7658 effect->setSuspended(true);
7659 }
7660 } else {
7661 if (index < 0) {
7662 return;
7663 }
Steve Block3856b092011-10-20 11:56:00 +01007664 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007665 effect->desc().type.timeLow);
7666 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7667 desc->mEffect.clear();
7668 effect->setSuspended(false);
7669 }
7670}
7671
Mathias Agopian65ab4712010-07-14 17:59:35 -07007672#undef LOG_TAG
7673#define LOG_TAG "AudioFlinger"
7674
7675// ----------------------------------------------------------------------------
7676
7677status_t AudioFlinger::onTransact(
7678 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7679{
7680 return BnAudioFlinger::onTransact(code, data, reply, flags);
7681}
7682
Mathias Agopian65ab4712010-07-14 17:59:35 -07007683}; // namespace android