blob: fdf15701a8bd7d032ab3f3dffdfcf0d3ea463d21 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Dima Zavin799a70e2011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261
262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800270 sp<Client> client = mClients.valueAt(i).promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700274 }
275 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700276
277 result.append("Global session refs:\n");
278 result.append(" session pid cnt\n");
279 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
280 AudioSessionRef *r = mAudioSessionRefs[i];
281 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
282 result.append(buffer);
283 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700284 write(fd, result.string(), result.size());
285 return NO_ERROR;
286}
287
288
289status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
290{
291 const size_t SIZE = 256;
292 char buffer[SIZE];
293 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800294 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700295
296 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
297 result.append(buffer);
298 write(fd, result.string(), result.size());
299 return NO_ERROR;
300}
301
302status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
303{
304 const size_t SIZE = 256;
305 char buffer[SIZE];
306 String8 result;
307 snprintf(buffer, SIZE, "Permission Denial: "
308 "can't dump AudioFlinger from pid=%d, uid=%d\n",
309 IPCThreadState::self()->getCallingPid(),
310 IPCThreadState::self()->getCallingUid());
311 result.append(buffer);
312 write(fd, result.string(), result.size());
313 return NO_ERROR;
314}
315
316static bool tryLock(Mutex& mutex)
317{
318 bool locked = false;
319 for (int i = 0; i < kDumpLockRetries; ++i) {
320 if (mutex.tryLock() == NO_ERROR) {
321 locked = true;
322 break;
323 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800324 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700325 }
326 return locked;
327}
328
329status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
330{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800331 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700332 dumpPermissionDenial(fd, args);
333 } else {
334 // get state of hardware lock
335 bool hardwareLocked = tryLock(mHardwareLock);
336 if (!hardwareLocked) {
337 String8 result(kHardwareLockedString);
338 write(fd, result.string(), result.size());
339 } else {
340 mHardwareLock.unlock();
341 }
342
343 bool locked = tryLock(mLock);
344
345 // failed to lock - AudioFlinger is probably deadlocked
346 if (!locked) {
347 String8 result(kDeadlockedString);
348 write(fd, result.string(), result.size());
349 }
350
351 dumpClients(fd, args);
352 dumpInternals(fd, args);
353
354 // dump playback threads
355 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
356 mPlaybackThreads.valueAt(i)->dump(fd, args);
357 }
358
359 // dump record threads
360 for (size_t i = 0; i < mRecordThreads.size(); i++) {
361 mRecordThreads.valueAt(i)->dump(fd, args);
362 }
363
Dima Zavin799a70e2011-04-18 16:57:27 -0700364 // dump all hardware devs
365 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
366 audio_hw_device_t *dev = mAudioHwDevs[i];
367 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700368 }
369 if (locked) mLock.unlock();
370 }
371 return NO_ERROR;
372}
373
374
375// IAudioFlinger interface
376
377
378sp<IAudioTrack> AudioFlinger::createTrack(
379 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800380 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700381 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800382 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700383 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384 int frameCount,
385 uint32_t flags,
386 const sp<IMemory>& sharedBuffer,
387 int output,
388 int *sessionId,
389 status_t *status)
390{
391 sp<PlaybackThread::Track> track;
392 sp<TrackHandle> trackHandle;
393 sp<Client> client;
394 wp<Client> wclient;
395 status_t lStatus;
396 int lSessionId;
397
Glenn Kasten263709e2012-01-06 08:40:01 -0800398 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
399 // but if someone uses binder directly they could bypass that and cause us to crash
400 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000401 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 lStatus = BAD_VALUE;
403 goto Exit;
404 }
405
406 {
407 Mutex::Autolock _l(mLock);
408 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700409 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700410 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000411 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 lStatus = BAD_VALUE;
413 goto Exit;
414 }
415
416 wclient = mClients.valueFor(pid);
417
418 if (wclient != NULL) {
419 client = wclient.promote();
420 } else {
421 client = new Client(this, pid);
422 mClients.add(pid, client);
423 }
424
Steve Block3856b092011-10-20 11:56:00 +0100425 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700426 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700427 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700428 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
429 if (mPlaybackThreads.keyAt(i) != output) {
430 // prevent same audio session on different output threads
431 uint32_t sessions = t->hasAudioSession(*sessionId);
432 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000433 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700434 lStatus = BAD_VALUE;
435 goto Exit;
436 }
437 // check if an effect with same session ID is waiting for a track to be created
438 if (sessions & PlaybackThread::EFFECT_SESSION) {
439 effectThread = t.get();
440 }
Eric Laurentde070132010-07-13 04:45:46 -0700441 }
442 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 lSessionId = *sessionId;
444 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700445 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700446 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 if (sessionId != NULL) {
448 *sessionId = lSessionId;
449 }
450 }
Steve Block3856b092011-10-20 11:56:00 +0100451 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700452
453 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700454 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700455
456 // move effect chain to this output thread if an effect on same session was waiting
457 // for a track to be created
458 if (lStatus == NO_ERROR && effectThread != NULL) {
459 Mutex::Autolock _dl(thread->mLock);
460 Mutex::Autolock _sl(effectThread->mLock);
461 moveEffectChain_l(lSessionId, effectThread, thread, true);
462 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700463 }
464 if (lStatus == NO_ERROR) {
465 trackHandle = new TrackHandle(track);
466 } else {
467 // remove local strong reference to Client before deleting the Track so that the Client
468 // destructor is called by the TrackBase destructor with mLock held
469 client.clear();
470 track.clear();
471 }
472
473Exit:
474 if(status) {
475 *status = lStatus;
476 }
477 return trackHandle;
478}
479
480uint32_t AudioFlinger::sampleRate(int output) const
481{
482 Mutex::Autolock _l(mLock);
483 PlaybackThread *thread = checkPlaybackThread_l(output);
484 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000485 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700486 return 0;
487 }
488 return thread->sampleRate();
489}
490
491int AudioFlinger::channelCount(int output) const
492{
493 Mutex::Autolock _l(mLock);
494 PlaybackThread *thread = checkPlaybackThread_l(output);
495 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000496 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700497 return 0;
498 }
499 return thread->channelCount();
500}
501
Glenn Kasten58f30212012-01-12 12:27:51 -0800502audio_format_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503{
504 Mutex::Autolock _l(mLock);
505 PlaybackThread *thread = checkPlaybackThread_l(output);
506 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000507 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800508 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509 }
510 return thread->format();
511}
512
513size_t AudioFlinger::frameCount(int output) const
514{
515 Mutex::Autolock _l(mLock);
516 PlaybackThread *thread = checkPlaybackThread_l(output);
517 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000518 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700519 return 0;
520 }
521 return thread->frameCount();
522}
523
524uint32_t AudioFlinger::latency(int output) const
525{
526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000529 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 return 0;
531 }
532 return thread->latency();
533}
534
535status_t AudioFlinger::setMasterVolume(float value)
536{
Eric Laurenta1884f92011-08-23 08:25:03 -0700537 status_t ret = initCheck();
538 if (ret != NO_ERROR) {
539 return ret;
540 }
541
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 // check calling permissions
543 if (!settingsAllowed()) {
544 return PERMISSION_DENIED;
545 }
546
547 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800548 { // scope for the lock
549 AutoMutex lock(mHardwareLock);
550 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700551 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800552 value = 1.0f;
553 }
554 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556
Eric Laurent93575202011-01-18 18:39:02 -0800557 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 mMasterVolume = value;
559 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
560 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
561
562 return NO_ERROR;
563}
564
Glenn Kastenf78aee72012-01-04 11:00:47 -0800565status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700566{
Eric Laurenta1884f92011-08-23 08:25:03 -0700567 status_t ret = initCheck();
568 if (ret != NO_ERROR) {
569 return ret;
570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700571
572 // check calling permissions
573 if (!settingsAllowed()) {
574 return PERMISSION_DENIED;
575 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800576 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000577 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 return BAD_VALUE;
579 }
580
581 { // scope for the lock
582 AutoMutex lock(mHardwareLock);
583 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700584 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 mHardwareStatus = AUDIO_HW_IDLE;
586 }
587
588 if (NO_ERROR == ret) {
589 Mutex::Autolock _l(mLock);
590 mMode = mode;
591 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
592 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700593 }
594
595 return ret;
596}
597
598status_t AudioFlinger::setMicMute(bool state)
599{
Eric Laurenta1884f92011-08-23 08:25:03 -0700600 status_t ret = initCheck();
601 if (ret != NO_ERROR) {
602 return ret;
603 }
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 // check calling permissions
606 if (!settingsAllowed()) {
607 return PERMISSION_DENIED;
608 }
609
610 AutoMutex lock(mHardwareLock);
611 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700612 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613 mHardwareStatus = AUDIO_HW_IDLE;
614 return ret;
615}
616
617bool AudioFlinger::getMicMute() const
618{
Eric Laurenta1884f92011-08-23 08:25:03 -0700619 status_t ret = initCheck();
620 if (ret != NO_ERROR) {
621 return false;
622 }
623
Dima Zavinfce7a472011-04-19 22:30:36 -0700624 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700626 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 mHardwareStatus = AUDIO_HW_IDLE;
628 return state;
629}
630
631status_t AudioFlinger::setMasterMute(bool muted)
632{
633 // check calling permissions
634 if (!settingsAllowed()) {
635 return PERMISSION_DENIED;
636 }
637
Eric Laurent93575202011-01-18 18:39:02 -0800638 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700639 mMasterMute = muted;
640 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
641 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
642
643 return NO_ERROR;
644}
645
646float AudioFlinger::masterVolume() const
647{
Glenn Kasten98067102011-12-13 11:47:54 -0800648 Mutex::Autolock _l(mLock);
649 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700650}
651
652bool AudioFlinger::masterMute() const
653{
Glenn Kasten98067102011-12-13 11:47:54 -0800654 Mutex::Autolock _l(mLock);
655 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656}
657
Glenn Kastenfff6d712012-01-12 16:38:12 -0800658status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659{
660 // check calling permissions
661 if (!settingsAllowed()) {
662 return PERMISSION_DENIED;
663 }
664
Glenn Kasten263709e2012-01-06 08:40:01 -0800665 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000666 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 return BAD_VALUE;
668 }
669
670 AutoMutex lock(mLock);
671 PlaybackThread *thread = NULL;
672 if (output) {
673 thread = checkPlaybackThread_l(output);
674 if (thread == NULL) {
675 return BAD_VALUE;
676 }
677 }
678
679 mStreamTypes[stream].volume = value;
680
681 if (thread == NULL) {
682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
683 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
684 }
685 } else {
686 thread->setStreamVolume(stream, value);
687 }
688
689 return NO_ERROR;
690}
691
Glenn Kastenfff6d712012-01-12 16:38:12 -0800692status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Glenn Kasten263709e2012-01-06 08:40:01 -0800699 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000701 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return BAD_VALUE;
703 }
704
Eric Laurent93575202011-01-18 18:39:02 -0800705 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 mStreamTypes[stream].mute = muted;
707 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
708 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
709
710 return NO_ERROR;
711}
712
Glenn Kastenfff6d712012-01-12 16:38:12 -0800713float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700714{
Glenn Kasten263709e2012-01-06 08:40:01 -0800715 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 return 0.0f;
717 }
718
719 AutoMutex lock(mLock);
720 float volume;
721 if (output) {
722 PlaybackThread *thread = checkPlaybackThread_l(output);
723 if (thread == NULL) {
724 return 0.0f;
725 }
726 volume = thread->streamVolume(stream);
727 } else {
728 volume = mStreamTypes[stream].volume;
729 }
730
731 return volume;
732}
733
Glenn Kastenfff6d712012-01-12 16:38:12 -0800734bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735{
Glenn Kasten263709e2012-01-06 08:40:01 -0800736 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 return true;
738 }
739
740 return mStreamTypes[stream].mute;
741}
742
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
744{
745 status_t result;
746
Steve Block3856b092011-10-20 11:56:00 +0100747 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
752 }
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 // ioHandle == 0 means the parameters are global to the audio hardware interface
755 if (ioHandle == 0) {
756 AutoMutex lock(mHardwareLock);
757 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700758 status_t final_result = NO_ERROR;
759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 result = dev->set_parameters(dev, keyValuePairs.string());
762 final_result = result ?: final_result;
763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
766 AudioParameter param = AudioParameter(keyValuePairs);
767 String8 value;
768 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
769 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700770 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
771 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 sp<RecordThread> thread = mRecordThreads.valueAt(i);
774 RecordThread::RecordTrack *track = thread->track();
775 if (track != NULL) {
776 audio_devices_t device = (audio_devices_t)(
777 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700778 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700779 thread->setEffectSuspended(FX_IID_AEC,
780 suspend,
781 track->sessionId());
782 thread->setEffectSuspended(FX_IID_NS,
783 suspend,
784 track->sessionId());
785 }
786 }
Eric Laurentbee53372011-08-29 12:42:48 -0700787 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700788 }
789 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700790 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 }
792
793 // hold a strong ref on thread in case closeOutput() or closeInput() is called
794 // and the thread is exited once the lock is released
795 sp<ThreadBase> thread;
796 {
797 Mutex::Autolock _l(mLock);
798 thread = checkPlaybackThread_l(ioHandle);
799 if (thread == NULL) {
800 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800801 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700802 // indicate output device change to all input threads for pre processing
803 AudioParameter param = AudioParameter(keyValuePairs);
804 int value;
805 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
807 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
808 }
809 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811 }
812 if (thread != NULL) {
813 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return result;
815 }
816 return BAD_VALUE;
817}
818
819String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
820{
Steve Block3856b092011-10-20 11:56:00 +0100821// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
823
824 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700825 String8 out_s8;
826
Dima Zavin799a70e2011-04-18 16:57:27 -0700827 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
828 audio_hw_device_t *dev = mAudioHwDevs[i];
829 char *s = dev->get_parameters(dev, keys.string());
830 out_s8 += String8(s);
831 free(s);
832 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700833 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 }
835
836 Mutex::Autolock _l(mLock);
837
838 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
839 if (playbackThread != NULL) {
840 return playbackThread->getParameters(keys);
841 }
842 RecordThread *recordThread = checkRecordThread_l(ioHandle);
843 if (recordThread != NULL) {
844 return recordThread->getParameters(keys);
845 }
846 return String8("");
847}
848
Glenn Kasten58f30212012-01-12 12:27:51 -0800849size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700850{
Eric Laurenta1884f92011-08-23 08:25:03 -0700851 status_t ret = initCheck();
852 if (ret != NO_ERROR) {
853 return 0;
854 }
855
Dima Zavin799a70e2011-04-18 16:57:27 -0700856 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857}
858
859unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
860{
861 if (ioHandle == 0) {
862 return 0;
863 }
864
865 Mutex::Autolock _l(mLock);
866
867 RecordThread *recordThread = checkRecordThread_l(ioHandle);
868 if (recordThread != NULL) {
869 return recordThread->getInputFramesLost();
870 }
871 return 0;
872}
873
874status_t AudioFlinger::setVoiceVolume(float value)
875{
Eric Laurenta1884f92011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
886 AutoMutex lock(mHardwareLock);
887 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700888 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 mHardwareStatus = AUDIO_HW_IDLE;
890
891 return ret;
892}
893
894status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
895{
896 status_t status;
897
898 Mutex::Autolock _l(mLock);
899
900 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
901 if (playbackThread != NULL) {
902 return playbackThread->getRenderPosition(halFrames, dspFrames);
903 }
904
905 return BAD_VALUE;
906}
907
908void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
909{
910
911 Mutex::Autolock _l(mLock);
912
913 int pid = IPCThreadState::self()->getCallingPid();
914 if (mNotificationClients.indexOfKey(pid) < 0) {
915 sp<NotificationClient> notificationClient = new NotificationClient(this,
916 client,
917 pid);
Steve Block3856b092011-10-20 11:56:00 +0100918 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919
920 mNotificationClients.add(pid, notificationClient);
921
922 sp<IBinder> binder = client->asBinder();
923 binder->linkToDeath(notificationClient);
924
925 // the config change is always sent from playback or record threads to avoid deadlock
926 // with AudioSystem::gLock
927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
929 }
930
931 for (size_t i = 0; i < mRecordThreads.size(); i++) {
932 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
933 }
934 }
935}
936
937void AudioFlinger::removeNotificationClient(pid_t pid)
938{
939 Mutex::Autolock _l(mLock);
940
941 int index = mNotificationClients.indexOfKey(pid);
942 if (index >= 0) {
943 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100944 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 mNotificationClients.removeItem(pid);
946 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700947
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700949 int num = mAudioSessionRefs.size();
950 bool removed = false;
951 for (int i = 0; i< num; i++) {
952 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100955 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700956 mAudioSessionRefs.removeAt(i);
957 delete ref;
958 removed = true;
959 i--;
960 num--;
961 }
962 }
963 if (removed) {
964 purgeStaleEffects_l();
965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966}
967
968// audioConfigChanged_l() must be called with AudioFlinger::mLock held
969void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
970{
971 size_t size = mNotificationClients.size();
972 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800973 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
974 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 }
976}
977
978// removeClient_l() must be called with AudioFlinger::mLock held
979void AudioFlinger::removeClient_l(pid_t pid)
980{
Steve Block3856b092011-10-20 11:56:00 +0100981 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 mClients.removeItem(pid);
983}
984
985
986// ----------------------------------------------------------------------------
987
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800988AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
989 type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800991 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800992 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
993 // mChannelMask
994 mChannelCount(0),
995 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
996 mParamStatus(NO_ERROR),
997 mStandby(false), mId(id), mExiting(false),
998 mDevice(device),
999 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000{
1001}
1002
1003AudioFlinger::ThreadBase::~ThreadBase()
1004{
1005 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001006 // do not lock the mutex in destructor
1007 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001008 if (mPowerManager != 0) {
1009 sp<IBinder> binder = mPowerManager->asBinder();
1010 binder->unlinkToDeath(mDeathRecipient);
1011 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001012}
1013
1014void AudioFlinger::ThreadBase::exit()
1015{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001016 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 // destroyed in the middle of requestExitAndWait()
1018 sp <ThreadBase> strongMe = this;
1019
Steve Block3856b092011-10-20 11:56:00 +01001020 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001022 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 mExiting = true;
1024 requestExit();
1025 mWaitWorkCV.signal();
1026 }
1027 requestExitAndWait();
1028}
1029
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
1032 status_t status;
1033
Steve Block3856b092011-10-20 11:56:00 +01001034 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035 Mutex::Autolock _l(mLock);
1036
1037 mNewParameters.add(keyValuePairs);
1038 mWaitWorkCV.signal();
1039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
1047 return status;
1048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
1053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001059 ConfigEvent configEvent;
1060 configEvent.mEvent = event;
1061 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001063 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001072 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 mConfigEvents.removeAt(0);
1074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
1076 mLock.unlock();
1077 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001078 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001079 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 mLock.lock();
1081 }
1082 mLock.unlock();
1083}
1084
1085status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1086{
1087 const size_t SIZE = 256;
1088 char buffer[SIZE];
1089 String8 result;
1090
1091 bool locked = tryLock(mLock);
1092 if (!locked) {
1093 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1094 write(fd, buffer, strlen(buffer));
1095 }
1096
1097 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1098 result.append(buffer);
1099 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1100 result.append(buffer);
1101 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1102 result.append(buffer);
1103 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1104 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001105 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1106 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001107 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1108 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001109 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001110 result.append(buffer);
1111
1112 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1113 result.append(buffer);
1114 result.append(" Index Command");
1115 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1116 snprintf(buffer, SIZE, "\n %02d ", i);
1117 result.append(buffer);
1118 result.append(mNewParameters[i]);
1119 }
1120
1121 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1122 result.append(buffer);
1123 snprintf(buffer, SIZE, " Index event param\n");
1124 result.append(buffer);
1125 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001126 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001127 result.append(buffer);
1128 }
1129 result.append("\n");
1130
1131 write(fd, result.string(), result.size());
1132
1133 if (locked) {
1134 mLock.unlock();
1135 }
1136 return NO_ERROR;
1137}
1138
Eric Laurent1d2bff02011-07-24 17:49:51 -07001139status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1140{
1141 const size_t SIZE = 256;
1142 char buffer[SIZE];
1143 String8 result;
1144
1145 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1146 write(fd, buffer, strlen(buffer));
1147
1148 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1149 sp<EffectChain> chain = mEffectChains[i];
1150 if (chain != 0) {
1151 chain->dump(fd, args);
1152 }
1153 }
1154 return NO_ERROR;
1155}
1156
Eric Laurentfeb0db62011-07-22 09:04:31 -07001157void AudioFlinger::ThreadBase::acquireWakeLock()
1158{
1159 Mutex::Autolock _l(mLock);
1160 acquireWakeLock_l();
1161}
1162
1163void AudioFlinger::ThreadBase::acquireWakeLock_l()
1164{
1165 if (mPowerManager == 0) {
1166 // use checkService() to avoid blocking if power service is not up yet
1167 sp<IBinder> binder =
1168 defaultServiceManager()->checkService(String16("power"));
1169 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001170 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001171 } else {
1172 mPowerManager = interface_cast<IPowerManager>(binder);
1173 binder->linkToDeath(mDeathRecipient);
1174 }
1175 }
1176 if (mPowerManager != 0) {
1177 sp<IBinder> binder = new BBinder();
1178 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1179 binder,
1180 String16(mName));
1181 if (status == NO_ERROR) {
1182 mWakeLockToken = binder;
1183 }
Steve Block3856b092011-10-20 11:56:00 +01001184 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001185 }
1186}
1187
1188void AudioFlinger::ThreadBase::releaseWakeLock()
1189{
1190 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001191 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001192}
1193
1194void AudioFlinger::ThreadBase::releaseWakeLock_l()
1195{
1196 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001198 if (mPowerManager != 0) {
1199 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1200 }
1201 mWakeLockToken.clear();
1202 }
1203}
1204
1205void AudioFlinger::ThreadBase::clearPowerManager()
1206{
1207 Mutex::Autolock _l(mLock);
1208 releaseWakeLock_l();
1209 mPowerManager.clear();
1210}
1211
1212void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1213{
1214 sp<ThreadBase> thread = mThread.promote();
1215 if (thread != 0) {
1216 thread->clearPowerManager();
1217 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001218 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001219}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001220
Eric Laurent59255e42011-07-27 19:49:51 -07001221void AudioFlinger::ThreadBase::setEffectSuspended(
1222 const effect_uuid_t *type, bool suspend, int sessionId)
1223{
1224 Mutex::Autolock _l(mLock);
1225 setEffectSuspended_l(type, suspend, sessionId);
1226}
1227
1228void AudioFlinger::ThreadBase::setEffectSuspended_l(
1229 const effect_uuid_t *type, bool suspend, int sessionId)
1230{
1231 sp<EffectChain> chain;
1232 chain = getEffectChain_l(sessionId);
1233 if (chain != 0) {
1234 if (type != NULL) {
1235 chain->setEffectSuspended_l(type, suspend);
1236 } else {
1237 chain->setEffectSuspendedAll_l(suspend);
1238 }
1239 }
1240
1241 updateSuspendedSessions_l(type, suspend, sessionId);
1242}
1243
1244void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1245{
1246 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1247 if (index < 0) {
1248 return;
1249 }
1250
1251 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1252 mSuspendedSessions.editValueAt(index);
1253
1254 for (size_t i = 0; i < sessionEffects.size(); i++) {
1255 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1256 for (int j = 0; j < desc->mRefCount; j++) {
1257 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1258 chain->setEffectSuspendedAll_l(true);
1259 } else {
Steve Block3856b092011-10-20 11:56:00 +01001260 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001261 desc->mType.timeLow);
1262 chain->setEffectSuspended_l(&desc->mType, true);
1263 }
1264 }
1265 }
1266}
1267
Eric Laurent59255e42011-07-27 19:49:51 -07001268void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1269 bool suspend,
1270 int sessionId)
1271{
1272 int index = mSuspendedSessions.indexOfKey(sessionId);
1273
1274 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1275
1276 if (suspend) {
1277 if (index >= 0) {
1278 sessionEffects = mSuspendedSessions.editValueAt(index);
1279 } else {
1280 mSuspendedSessions.add(sessionId, sessionEffects);
1281 }
1282 } else {
1283 if (index < 0) {
1284 return;
1285 }
1286 sessionEffects = mSuspendedSessions.editValueAt(index);
1287 }
1288
1289
1290 int key = EffectChain::kKeyForSuspendAll;
1291 if (type != NULL) {
1292 key = type->timeLow;
1293 }
1294 index = sessionEffects.indexOfKey(key);
1295
1296 sp <SuspendedSessionDesc> desc;
1297 if (suspend) {
1298 if (index >= 0) {
1299 desc = sessionEffects.valueAt(index);
1300 } else {
1301 desc = new SuspendedSessionDesc();
1302 if (type != NULL) {
1303 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1304 }
1305 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001306 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001307 }
1308 desc->mRefCount++;
1309 } else {
1310 if (index < 0) {
1311 return;
1312 }
1313 desc = sessionEffects.valueAt(index);
1314 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001316 sessionEffects.removeItemsAt(index);
1317 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001319 sessionId);
1320 mSuspendedSessions.removeItem(sessionId);
1321 }
1322 }
1323 }
1324 if (!sessionEffects.isEmpty()) {
1325 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1326 }
1327}
1328
1329void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1330 bool enabled,
1331 int sessionId)
1332{
1333 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001334 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1335}
Eric Laurent59255e42011-07-27 19:49:51 -07001336
Eric Laurenta85a74a2011-10-19 11:44:54 -07001337void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1338 bool enabled,
1339 int sessionId)
1340{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001341 if (mType != RECORD) {
1342 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1343 // another session. This gives the priority to well behaved effect control panels
1344 // and applications not using global effects.
1345 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1346 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1347 }
1348 }
Eric Laurent59255e42011-07-27 19:49:51 -07001349
1350 sp<EffectChain> chain = getEffectChain_l(sessionId);
1351 if (chain != 0) {
1352 chain->checkSuspendOnEffectEnabled(effect, enabled);
1353 }
1354}
1355
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356// ----------------------------------------------------------------------------
1357
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001358AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1359 AudioStreamOut* output,
1360 int id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001361 uint32_t device,
1362 type_t type)
1363 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001364 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1365 // Assumes constructor is called by AudioFlinger with it's mLock held,
1366 // but it would be safer to explicitly pass initial masterMute as parameter
1367 mMasterMute(audioFlinger->masterMute_l()),
1368 // mStreamTypes[] initialized in constructor body
1369 mOutput(output),
1370 // Assumes constructor is called by AudioFlinger with it's mLock held,
1371 // but it would be safer to explicitly pass initial masterVolume as parameter
1372 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001373 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001375 snprintf(mName, kNameLength, "AudioOut_%d", id);
1376
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 readOutputParameters();
1378
Glenn Kasten263709e2012-01-06 08:40:01 -08001379 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001380 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1381 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1382 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1384 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001385 // initialized by stream_type_t default constructor
1386 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 }
1388}
1389
1390AudioFlinger::PlaybackThread::~PlaybackThread()
1391{
1392 delete [] mMixBuffer;
1393}
1394
1395status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1396{
1397 dumpInternals(fd, args);
1398 dumpTracks(fd, args);
1399 dumpEffectChains(fd, args);
1400 return NO_ERROR;
1401}
1402
1403status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1404{
1405 const size_t SIZE = 256;
1406 char buffer[SIZE];
1407 String8 result;
1408
1409 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1410 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001411 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 -07001412 for (size_t i = 0; i < mTracks.size(); ++i) {
1413 sp<Track> track = mTracks[i];
1414 if (track != 0) {
1415 track->dump(buffer, SIZE);
1416 result.append(buffer);
1417 }
1418 }
1419
1420 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1421 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001422 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 -07001423 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001424 sp<Track> track = mActiveTracks[i].promote();
1425 if (track != 0) {
1426 track->dump(buffer, SIZE);
1427 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001428 }
1429 }
1430 write(fd, result.string(), result.size());
1431 return NO_ERROR;
1432}
1433
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1435{
1436 const size_t SIZE = 256;
1437 char buffer[SIZE];
1438 String8 result;
1439
1440 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1441 result.append(buffer);
1442 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1453 result.append(buffer);
1454 write(fd, result.string(), result.size());
1455
1456 dumpBase(fd, args);
1457
1458 return NO_ERROR;
1459}
1460
1461// Thread virtuals
1462status_t AudioFlinger::PlaybackThread::readyToRun()
1463{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001464 status_t status = initCheck();
1465 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001466 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001467 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001468 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001470 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
1473void AudioFlinger::PlaybackThread::onFirstRef()
1474{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001475 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1479sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1480 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001481 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001483 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001484 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 int frameCount,
1486 const sp<IMemory>& sharedBuffer,
1487 int sessionId,
1488 status_t *status)
1489{
1490 sp<Track> track;
1491 status_t lStatus;
1492
1493 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001494 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1495 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001496 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001497 "for output %p with format %d",
1498 sampleRate, format, channelMask, mOutput, mFormat);
1499 lStatus = BAD_VALUE;
1500 goto Exit;
1501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 }
1503 } else {
1504 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1505 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001506 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 lStatus = BAD_VALUE;
1508 goto Exit;
1509 }
1510 }
1511
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001512 lStatus = initCheck();
1513 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001514 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 goto Exit;
1516 }
1517
1518 { // scope for mLock
1519 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001520
1521 // all tracks in same audio session must share the same routing strategy otherwise
1522 // conflicts will happen when tracks are moved from one output to another by audio policy
1523 // manager
1524 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001525 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001526 for (size_t i = 0; i < mTracks.size(); ++i) {
1527 sp<Track> t = mTracks[i];
1528 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001529 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1530 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001531 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001532 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536 }
1537 }
1538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001540 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 if (track->getCblk() == NULL || track->name() < 0) {
1542 lStatus = NO_MEMORY;
1543 goto Exit;
1544 }
1545 mTracks.add(track);
1546
1547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001549 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001551 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001552 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001554
1555 // invalidate track immediately if the stream type was moved to another thread since
1556 // createTrack() was called by the client process.
1557 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001558 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001559 this, streamType);
1560 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1561 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 }
1563 lStatus = NO_ERROR;
1564
1565Exit:
1566 if(status) {
1567 *status = lStatus;
1568 }
1569 return track;
1570}
1571
1572uint32_t AudioFlinger::PlaybackThread::latency() const
1573{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001574 Mutex::Autolock _l(mLock);
1575 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001576 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001577 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 return 0;
1579 }
1580}
1581
1582status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1583{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 mMasterVolume = value;
1585 return NO_ERROR;
1586}
1587
1588status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 mMasterMute = muted;
1591 return NO_ERROR;
1592}
1593
Glenn Kastenfff6d712012-01-12 16:38:12 -08001594status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 mStreamTypes[stream].volume = value;
1597 return NO_ERROR;
1598}
1599
Glenn Kastenfff6d712012-01-12 16:38:12 -08001600status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 mStreamTypes[stream].mute = muted;
1603 return NO_ERROR;
1604}
1605
Glenn Kastenfff6d712012-01-12 16:38:12 -08001606float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607{
1608 return mStreamTypes[stream].volume;
1609}
1610
Glenn Kastenfff6d712012-01-12 16:38:12 -08001611bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612{
1613 return mStreamTypes[stream].mute;
1614}
1615
Mathias Agopian65ab4712010-07-14 17:59:35 -07001616// addTrack_l() must be called with ThreadBase::mLock held
1617status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1618{
1619 status_t status = ALREADY_EXISTS;
1620
1621 // set retry count for buffer fill
1622 track->mRetryCount = kMaxTrackStartupRetries;
1623 if (mActiveTracks.indexOf(track) < 0) {
1624 // the track is newly added, make sure it fills up all its
1625 // buffers before playing. This is to ensure the client will
1626 // effectively get the latency it requested.
1627 track->mFillingUpStatus = Track::FS_FILLING;
1628 track->mResetDone = false;
1629 mActiveTracks.add(track);
1630 if (track->mainBuffer() != mMixBuffer) {
1631 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1632 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001633 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001634 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001635 }
1636 }
1637
1638 status = NO_ERROR;
1639 }
1640
Steve Block3856b092011-10-20 11:56:00 +01001641 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 mWaitWorkCV.broadcast();
1643
1644 return status;
1645}
1646
1647// destroyTrack_l() must be called with ThreadBase::mLock held
1648void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1649{
1650 track->mState = TrackBase::TERMINATED;
1651 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001652 removeTrack_l(track);
1653 }
1654}
1655
1656void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1657{
1658 mTracks.remove(track);
1659 deleteTrackName_l(track->name());
1660 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1661 if (chain != 0) {
1662 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 }
1664}
1665
1666String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1667{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001668 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001669 char *s;
1670
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001671 Mutex::Autolock _l(mLock);
1672 if (initCheck() != NO_ERROR) {
1673 return out_s8;
1674 }
1675
Dima Zavin799a70e2011-04-18 16:57:27 -07001676 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001677 out_s8 = String8(s);
1678 free(s);
1679 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680}
1681
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001682// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1684 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001685 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686
Steve Block3856b092011-10-20 11:56:00 +01001687 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688
1689 switch (event) {
1690 case AudioSystem::OUTPUT_OPENED:
1691 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001692 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 desc.samplingRate = mSampleRate;
1694 desc.format = mFormat;
1695 desc.frameCount = mFrameCount;
1696 desc.latency = latency();
1697 param2 = &desc;
1698 break;
1699
1700 case AudioSystem::STREAM_CONFIG_CHANGED:
1701 param2 = &param;
1702 case AudioSystem::OUTPUT_CLOSED:
1703 default:
1704 break;
1705 }
1706 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1707}
1708
1709void AudioFlinger::PlaybackThread::readOutputParameters()
1710{
Dima Zavin799a70e2011-04-18 16:57:27 -07001711 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001712 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1713 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001714 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001715 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001716 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717
1718 // FIXME - Current mixer implementation only supports stereo output: Always
1719 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001720 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 mMixBuffer = new int16_t[mFrameCount * 2];
1722 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1723
Eric Laurentde070132010-07-13 04:45:46 -07001724 // force reconfiguration of effect chains and engines to take new buffer size and audio
1725 // parameters into account
1726 // Note that mLock is not held when readOutputParameters() is called from the constructor
1727 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1728 // matter.
1729 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1730 Vector< sp<EffectChain> > effectChains = mEffectChains;
1731 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001732 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001733 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001734}
1735
1736status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1737{
Glenn Kastena0d68332012-01-27 16:47:15 -08001738 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739 return BAD_VALUE;
1740 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001741 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001742 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743 return INVALID_OPERATION;
1744 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001745 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746
Dima Zavin799a70e2011-04-18 16:57:27 -07001747 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748}
1749
Eric Laurent39e94f82010-07-28 01:32:47 -07001750uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751{
1752 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001753 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001755 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 }
1757
1758 for (size_t i = 0; i < mTracks.size(); ++i) {
1759 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001760 if (sessionId == track->sessionId() &&
1761 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001762 result |= TRACK_SESSION;
1763 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 }
1765 }
1766
Eric Laurent39e94f82010-07-28 01:32:47 -07001767 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768}
1769
Eric Laurentde070132010-07-13 04:45:46 -07001770uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1771{
Dima Zavinfce7a472011-04-19 22:30:36 -07001772 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001773 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001774 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1775 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001776 }
1777 for (size_t i = 0; i < mTracks.size(); i++) {
1778 sp<Track> track = mTracks[i];
1779 if (sessionId == track->sessionId() &&
1780 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001781 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001782 }
1783 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001784 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001785}
1786
Mathias Agopian65ab4712010-07-14 17:59:35 -07001787
Glenn Kastenaed850d2012-01-26 09:46:34 -08001788AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001789{
1790 Mutex::Autolock _l(mLock);
1791 return mOutput;
1792}
1793
1794AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1795{
1796 Mutex::Autolock _l(mLock);
1797 AudioStreamOut *output = mOutput;
1798 mOutput = NULL;
1799 return output;
1800}
1801
1802// this method must always be called either with ThreadBase mLock held or inside the thread loop
1803audio_stream_t* AudioFlinger::PlaybackThread::stream()
1804{
1805 if (mOutput == NULL) {
1806 return NULL;
1807 }
1808 return &mOutput->stream->common;
1809}
1810
Eric Laurent162b40b2011-12-05 09:47:19 -08001811uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1812{
1813 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1814 // decoding and transfer time. So sleeping for half of the latency would likely cause
1815 // underruns
1816 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1817 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1818 } else {
1819 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1820 }
1821}
1822
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823// ----------------------------------------------------------------------------
1824
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001825AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1826 int id, uint32_t device, type_t type)
1827 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001828 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1829 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831 // FIXME - Current mixer implementation only supports stereo output
1832 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001833 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 }
1835}
1836
1837AudioFlinger::MixerThread::~MixerThread()
1838{
1839 delete mAudioMixer;
1840}
1841
1842bool AudioFlinger::MixerThread::threadLoop()
1843{
1844 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001845 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 nsecs_t standbyTime = systemTime();
1847 size_t mixBufferSize = mFrameCount * mFrameSize;
1848 // FIXME: Relaxed timing because of a certain device that can't meet latency
1849 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001850 // increase threshold again due to low power audio mode. The way this warning threshold is
1851 // calculated and its usefulness should be reconsidered anyway.
1852 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 nsecs_t lastWarning = 0;
1854 bool longStandbyExit = false;
1855 uint32_t activeSleepTime = activeSleepTimeUs();
1856 uint32_t idleSleepTime = idleSleepTimeUs();
1857 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001858 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001860#ifdef DEBUG_CPU_USAGE
1861 ThreadCpuUsage cpu;
1862 const CentralTendencyStatistics& stats = cpu.statistics();
1863#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864
Eric Laurentfeb0db62011-07-22 09:04:31 -07001865 acquireWakeLock();
1866
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 while (!exitPending())
1868 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001869#ifdef DEBUG_CPU_USAGE
1870 cpu.sampleAndEnable();
1871 unsigned n = stats.n();
1872 // cpu.elapsed() is expensive, so don't call it every loop
1873 if ((n & 127) == 1) {
1874 long long elapsed = cpu.elapsed();
1875 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1876 double perLoop = elapsed / (double) n;
1877 double perLoop100 = perLoop * 0.01;
1878 double mean = stats.mean();
1879 double stddev = stats.stddev();
1880 double minimum = stats.minimum();
1881 double maximum = stats.maximum();
1882 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001883 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 -07001884 elapsed * .000000001, n, perLoop * .000001,
1885 mean * .001,
1886 stddev * .001,
1887 minimum * .001,
1888 maximum * .001,
1889 mean / perLoop100,
1890 stddev / perLoop100,
1891 minimum / perLoop100,
1892 maximum / perLoop100);
1893 }
1894 }
1895#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896 processConfigEvents();
1897
1898 mixerStatus = MIXER_IDLE;
1899 { // scope for mLock
1900
1901 Mutex::Autolock _l(mLock);
1902
1903 if (checkForNewParameters_l()) {
1904 mixBufferSize = mFrameCount * mFrameSize;
1905 // FIXME: Relaxed timing because of a certain device that can't meet latency
1906 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001907 // increase threshold again due to low power audio mode. The way this warning
1908 // threshold is calculated and its usefulness should be reconsidered anyway.
1909 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910 activeSleepTime = activeSleepTimeUs();
1911 idleSleepTime = idleSleepTimeUs();
1912 }
1913
1914 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1915
1916 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001917 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1918 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001920 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001921 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 mStandby = true;
1923 mBytesWritten = 0;
1924 }
1925
1926 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1927 // we're about to wait, flush the binder command buffer
1928 IPCThreadState::self()->flushCommands();
1929
1930 if (exitPending()) break;
1931
Eric Laurentfeb0db62011-07-22 09:04:31 -07001932 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001934 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001936 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001937 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938
Eric Laurent27741442012-01-17 19:20:12 -08001939 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001940 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 char value[PROPERTY_VALUE_MAX];
1942 property_get("ro.audio.silent", value, "0");
1943 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001944 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 setMasterMute(true);
1946 }
1947 }
1948
1949 standbyTime = systemTime() + kStandbyTimeInNsecs;
1950 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001951 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 continue;
1953 }
1954 }
1955
1956 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1957
1958 // prevent any changes in effect chain list and in each effect chain
1959 // during mixing and effect process as the audio buffers could be deleted
1960 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001961 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001962 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001963
Glenn Kastenf6b16782011-12-15 09:51:17 -08001964 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 // mix buffers...
1966 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001967 // increase sleep time progressively when application underrun condition clears.
1968 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1969 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1970 // such that we would underrun the audio HAL.
1971 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001972 sleepTimeShift--;
1973 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001974 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 standbyTime = systemTime() + kStandbyTimeInNsecs;
1976 //TODO: delay standby when effects have a tail
1977 } else {
1978 // If no tracks are ready, sleep once for the duration of an output
1979 // buffer size, then write 0s to the output
1980 if (sleepTime == 0) {
1981 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001982 sleepTime = activeSleepTime >> sleepTimeShift;
1983 if (sleepTime < kMinThreadSleepTimeUs) {
1984 sleepTime = kMinThreadSleepTimeUs;
1985 }
1986 // reduce sleep time in case of consecutive application underruns to avoid
1987 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1988 // duration we would end up writing less data than needed by the audio HAL if
1989 // the condition persists.
1990 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1991 sleepTimeShift++;
1992 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 } else {
1994 sleepTime = idleSleepTime;
1995 }
1996 } else if (mBytesWritten != 0 ||
1997 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1998 memset (mMixBuffer, 0, mixBufferSize);
1999 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002000 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 }
2002 // TODO add standby time extension fct of effect tail
2003 }
2004
2005 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002006 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002007 }
2008 // sleepTime == 0 means we must write to audio hardware
2009 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002010 for (size_t i = 0; i < effectChains.size(); i ++) {
2011 effectChains[i]->process_l();
2012 }
2013 // enable changes in effect chain
2014 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 mLastWriteTime = systemTime();
2016 mInWrite = true;
2017 mBytesWritten += mixBufferSize;
2018
Dima Zavin799a70e2011-04-18 16:57:27 -07002019 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2021 mNumWrites++;
2022 mInWrite = false;
2023 nsecs_t now = systemTime();
2024 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002025 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002027 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002028 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 ns2ms(delta), mNumDelayedWrites, this);
2030 lastWarning = now;
2031 }
2032 if (mStandby) {
2033 longStandbyExit = true;
2034 }
2035 }
2036 mStandby = false;
2037 } else {
2038 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002039 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 usleep(sleepTime);
2041 }
2042
2043 // finally let go of all our tracks, without the lock held
2044 // since we can't guarantee the destructors won't acquire that
2045 // same lock.
2046 tracksToRemove.clear();
2047
2048 // Effect chains will be actually deleted here if they were removed from
2049 // mEffectChains list during mixing or effects processing
2050 effectChains.clear();
2051 }
2052
2053 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002054 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 }
2056
Eric Laurentfeb0db62011-07-22 09:04:31 -07002057 releaseWakeLock();
2058
Steve Block3856b092011-10-20 11:56:00 +01002059 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 return false;
2061}
2062
2063// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002064AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2065 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066{
2067
Glenn Kasten29c23c32012-01-26 13:37:52 -08002068 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 // find out which tracks need to be processed
2070 size_t count = activeTracks.size();
2071 size_t mixedTracks = 0;
2072 size_t tracksWithEffect = 0;
2073
2074 float masterVolume = mMasterVolume;
2075 bool masterMute = mMasterMute;
2076
Eric Laurent571d49c2010-08-11 05:20:11 -07002077 if (masterMute) {
2078 masterVolume = 0;
2079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002081 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002083 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002084 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 masterVolume = (float)((v + (1 << 23)) >> 24);
2086 chain.clear();
2087 }
2088
2089 for (size_t i=0 ; i<count ; i++) {
2090 sp<Track> t = activeTracks[i].promote();
2091 if (t == 0) continue;
2092
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002093 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 Track* const track = t.get();
2095 audio_track_cblk_t* cblk = track->cblk();
2096
2097 // The first time a track is added we wait
2098 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002099 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002100 // make sure that we have enough frames to mix one full buffer.
2101 // enforce this condition only once to enable draining the buffer in case the client
2102 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002103 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002104 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002105 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002106 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002107 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002108 if (t->sampleRate() == (int)mSampleRate) {
2109 minFrames = mFrameCount;
2110 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002111 // +1 for rounding and +1 for additional sample needed for interpolation
2112 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2113 // add frames already consumed but not yet released by the resampler
2114 // because cblk->framesReady() will include these frames
2115 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2116 // the minimum track buffer size is normally twice the number of frames necessary
2117 // to fill one buffer and the resampler should not leave more than one buffer worth
2118 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002119 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002120 }
2121 }
2122 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 !track->isPaused() && !track->isTerminated())
2124 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002125 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126
2127 mixedTracks++;
2128
2129 // track->mainBuffer() != mMixBuffer means there is an effect chain
2130 // connected to the track
2131 chain.clear();
2132 if (track->mainBuffer() != mMixBuffer) {
2133 chain = getEffectChain_l(track->sessionId());
2134 // Delegate volume control to effect in track effect chain if needed
2135 if (chain != 0) {
2136 tracksWithEffect++;
2137 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002138 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002139 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 }
2141 }
2142
2143
2144 int param = AudioMixer::VOLUME;
2145 if (track->mFillingUpStatus == Track::FS_FILLED) {
2146 // no ramp for the first volume setting
2147 track->mFillingUpStatus = Track::FS_ACTIVE;
2148 if (track->mState == TrackBase::RESUMING) {
2149 track->mState = TrackBase::ACTIVE;
2150 param = AudioMixer::RAMP_VOLUME;
2151 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002152 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 } else if (cblk->server != 0) {
2154 // If the track is stopped before the first frame was mixed,
2155 // do not apply ramp
2156 param = AudioMixer::RAMP_VOLUME;
2157 }
2158
2159 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002160 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002161 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002162 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002163 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 if (track->isPausing()) {
2165 track->setPaused();
2166 }
2167 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002168
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 // read original volumes with volume control
2170 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002172 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002173 vl = vlr & 0xFFFF;
2174 vr = vlr >> 16;
2175 // track volumes come from shared memory, so can't be trusted and must be clamped
2176 if (vl > MAX_GAIN_INT) {
2177 ALOGV("Track left volume out of range: %04X", vl);
2178 vl = MAX_GAIN_INT;
2179 }
2180 if (vr > MAX_GAIN_INT) {
2181 ALOGV("Track right volume out of range: %04X", vr);
2182 vr = MAX_GAIN_INT;
2183 }
2184 // now apply the master volume and stream type volume
2185 vl = (uint32_t)(v * vl) << 12;
2186 vr = (uint32_t)(v * vr) << 12;
2187 // assuming master volume and stream type volume each go up to 1.0,
2188 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189
Glenn Kasten05632a52012-01-03 14:22:33 -08002190 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2191 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002192 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002193 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002194 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002195 }
2196 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002198 // Delegate volume control to effect in track effect chain if needed
2199 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2200 // Do not ramp volume if volume is controlled by effect
2201 param = AudioMixer::VOLUME;
2202 track->mHasVolumeController = true;
2203 } else {
2204 // force no volume ramp when volume controller was just disabled or removed
2205 // from effect chain to avoid volume spike
2206 if (track->mHasVolumeController) {
2207 param = AudioMixer::VOLUME;
2208 }
2209 track->mHasVolumeController = false;
2210 }
2211
2212 // Convert volumes from 8.24 to 4.12 format
2213 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002214 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002215 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2216 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2217 left = int16_t(v_clamped);
2218 v_clamped = (vr + (1 << 11)) >> 12;
2219 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2220 right = int16_t(v_clamped);
2221
2222 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2223 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002224
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002226 mAudioMixer->setBufferProvider(name, track);
2227 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002229 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2230 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2231 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002233 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 AudioMixer::TRACK,
2235 AudioMixer::FORMAT, (void *)track->format());
2236 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002237 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002239 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002241 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 AudioMixer::RESAMPLE,
2243 AudioMixer::SAMPLE_RATE,
2244 (void *)(cblk->sampleRate));
2245 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002246 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 AudioMixer::TRACK,
2248 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2249 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002250 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002251 AudioMixer::TRACK,
2252 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2253
2254 // reset retry count
2255 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002256 // If one track is ready, set the mixer ready if:
2257 // - the mixer was not ready during previous round OR
2258 // - no other track is not ready
2259 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2260 mixerStatus != MIXER_TRACKS_ENABLED) {
2261 mixerStatus = MIXER_TRACKS_READY;
2262 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002264 //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 -07002265 if (track->isStopped()) {
2266 track->reset();
2267 }
2268 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2269 // We have consumed all the buffers of this track.
2270 // Remove it from the list of active tracks.
2271 tracksToRemove->add(track);
2272 } else {
2273 // No buffers for this track. Give it a few chances to
2274 // fill a buffer, then remove it from active list.
2275 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002276 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002278 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002279 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002280 // If one track is not ready, mark the mixer also not ready if:
2281 // - the mixer was ready during previous round OR
2282 // - no other track is ready
2283 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2284 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285 mixerStatus = MIXER_TRACKS_ENABLED;
2286 }
2287 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002288 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 }
2290 }
2291
2292 // remove all the tracks that need to be...
2293 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002294 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 for (size_t i=0 ; i<count ; i++) {
2296 const sp<Track>& track = tracksToRemove->itemAt(i);
2297 mActiveTracks.remove(track);
2298 if (track->mainBuffer() != mMixBuffer) {
2299 chain = getEffectChain_l(track->sessionId());
2300 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002301 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002302 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 }
2304 }
2305 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002306 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 }
2308 }
2309 }
2310
2311 // mix buffer must be cleared if all tracks are connected to an
2312 // effect chain as in this case the mixer will not write to
2313 // mix buffer and track effects will accumulate into it
2314 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2315 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2316 }
2317
Eric Laurent27741442012-01-17 19:20:12 -08002318 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 return mixerStatus;
2320}
2321
Glenn Kastenfff6d712012-01-12 16:38:12 -08002322void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323{
Steve Block3856b092011-10-20 11:56:00 +01002324 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002325 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002327
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 size_t size = mTracks.size();
2329 for (size_t i = 0; i < size; i++) {
2330 sp<Track> t = mTracks[i];
2331 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002332 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 }
2335 }
2336}
2337
Glenn Kastenfff6d712012-01-12 16:38:12 -08002338void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002339{
Steve Block3856b092011-10-20 11:56:00 +01002340 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002341 this, streamType, valid);
2342 Mutex::Autolock _l(mLock);
2343
2344 mStreamTypes[streamType].valid = valid;
2345}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346
2347// getTrackName_l() must be called with ThreadBase::mLock held
2348int AudioFlinger::MixerThread::getTrackName_l()
2349{
2350 return mAudioMixer->getTrackName();
2351}
2352
2353// deleteTrackName_l() must be called with ThreadBase::mLock held
2354void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2355{
Steve Block3856b092011-10-20 11:56:00 +01002356 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 mAudioMixer->deleteTrackName(name);
2358}
2359
2360// checkForNewParameters_l() must be called with ThreadBase::mLock held
2361bool AudioFlinger::MixerThread::checkForNewParameters_l()
2362{
2363 bool reconfig = false;
2364
2365 while (!mNewParameters.isEmpty()) {
2366 status_t status = NO_ERROR;
2367 String8 keyValuePair = mNewParameters[0];
2368 AudioParameter param = AudioParameter(keyValuePair);
2369 int value;
2370
2371 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2372 reconfig = true;
2373 }
2374 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002375 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002376 status = BAD_VALUE;
2377 } else {
2378 reconfig = true;
2379 }
2380 }
2381 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002382 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383 status = BAD_VALUE;
2384 } else {
2385 reconfig = true;
2386 }
2387 }
2388 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2389 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002390 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 // if frame count is changed after track creation
2392 if (!mTracks.isEmpty()) {
2393 status = INVALID_OPERATION;
2394 } else {
2395 reconfig = true;
2396 }
2397 }
2398 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002399 // when changing the audio output device, call addBatteryData to notify
2400 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002401 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002402 uint32_t params = 0;
2403 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002404 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002405 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2406 }
2407
2408 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002409 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002410 // check if any other device (except speaker) is on
2411 if (value & deviceWithoutSpeaker ) {
2412 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2413 }
2414
2415 if (params != 0) {
2416 addBatteryData(params);
2417 }
2418 }
2419
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 // forward device change to effects that have requested to be
2421 // aware of attached audio device.
2422 mDevice = (uint32_t)value;
2423 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002424 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 }
2426 }
2427
2428 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002429 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002430 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002432 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 mStandby = true;
2434 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002435 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002436 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 }
2438 if (status == NO_ERROR && reconfig) {
2439 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002440 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2441 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442 readOutputParameters();
2443 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2444 for (size_t i = 0; i < mTracks.size() ; i++) {
2445 int name = getTrackName_l();
2446 if (name < 0) break;
2447 mTracks[i]->mName = name;
2448 // limit track sample rate to 2 x new output sample rate
2449 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2450 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2451 }
2452 }
2453 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2454 }
2455 }
2456
2457 mNewParameters.removeAt(0);
2458
2459 mParamStatus = status;
2460 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002461 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2462 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002463 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002464 }
2465 return reconfig;
2466}
2467
2468status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2469{
2470 const size_t SIZE = 256;
2471 char buffer[SIZE];
2472 String8 result;
2473
2474 PlaybackThread::dumpInternals(fd, args);
2475
2476 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2477 result.append(buffer);
2478 write(fd, result.string(), result.size());
2479 return NO_ERROR;
2480}
2481
Mathias Agopian65ab4712010-07-14 17:59:35 -07002482uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2483{
Eric Laurent60e18242010-07-29 06:50:24 -07002484 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485}
2486
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002487uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2488{
2489 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2490}
2491
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002493AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002494 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002495 // mLeftVolFloat, mRightVolFloat
2496 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002497{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498}
2499
2500AudioFlinger::DirectOutputThread::~DirectOutputThread()
2501{
2502}
2503
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504static inline
2505int32_t mul(int16_t in, int16_t v)
2506{
2507#if defined(__arm__) && !defined(__thumb__)
2508 int32_t out;
2509 asm( "smulbb %[out], %[in], %[v] \n"
2510 : [out]"=r"(out)
2511 : [in]"%r"(in), [v]"r"(v)
2512 : );
2513 return out;
2514#else
2515 return in * int32_t(v);
2516#endif
2517}
2518
2519void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2520{
2521 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002522 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 return;
2524 }
2525
2526 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002527 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002528 size_t count = mFrameCount * mChannelCount;
2529 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2530 int16_t *dst = mMixBuffer + count-1;
2531 while(count--) {
2532 *dst-- = (int16_t)(*src--^0x80) << 8;
2533 }
2534 }
2535
2536 size_t frameCount = mFrameCount;
2537 int16_t *out = mMixBuffer;
2538 if (ramp) {
2539 if (mChannelCount == 1) {
2540 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2541 int32_t vlInc = d / (int32_t)frameCount;
2542 int32_t vl = ((int32_t)mLeftVolShort << 16);
2543 do {
2544 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2545 out++;
2546 vl += vlInc;
2547 } while (--frameCount);
2548
2549 } else {
2550 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2551 int32_t vlInc = d / (int32_t)frameCount;
2552 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2553 int32_t vrInc = d / (int32_t)frameCount;
2554 int32_t vl = ((int32_t)mLeftVolShort << 16);
2555 int32_t vr = ((int32_t)mRightVolShort << 16);
2556 do {
2557 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2558 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2559 out += 2;
2560 vl += vlInc;
2561 vr += vrInc;
2562 } while (--frameCount);
2563 }
2564 } else {
2565 if (mChannelCount == 1) {
2566 do {
2567 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2568 out++;
2569 } while (--frameCount);
2570 } else {
2571 do {
2572 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2573 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2574 out += 2;
2575 } while (--frameCount);
2576 }
2577 }
2578
2579 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002580 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002581 size_t count = mFrameCount * mChannelCount;
2582 int16_t *src = mMixBuffer;
2583 uint8_t *dst = (uint8_t *)mMixBuffer;
2584 while(count--) {
2585 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2586 }
2587 }
2588
2589 mLeftVolShort = leftVol;
2590 mRightVolShort = rightVol;
2591}
2592
2593bool AudioFlinger::DirectOutputThread::threadLoop()
2594{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002595 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 sp<Track> trackToRemove;
2597 sp<Track> activeTrack;
2598 nsecs_t standbyTime = systemTime();
2599 int8_t *curBuf;
2600 size_t mixBufferSize = mFrameCount*mFrameSize;
2601 uint32_t activeSleepTime = activeSleepTimeUs();
2602 uint32_t idleSleepTime = idleSleepTimeUs();
2603 uint32_t sleepTime = idleSleepTime;
2604 // use shorter standby delay as on normal output to release
2605 // hardware resources as soon as possible
2606 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2607
Eric Laurentfeb0db62011-07-22 09:04:31 -07002608 acquireWakeLock();
2609
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 while (!exitPending())
2611 {
2612 bool rampVolume;
2613 uint16_t leftVol;
2614 uint16_t rightVol;
2615 Vector< sp<EffectChain> > effectChains;
2616
2617 processConfigEvents();
2618
2619 mixerStatus = MIXER_IDLE;
2620
2621 { // scope for the mLock
2622
2623 Mutex::Autolock _l(mLock);
2624
2625 if (checkForNewParameters_l()) {
2626 mixBufferSize = mFrameCount*mFrameSize;
2627 activeSleepTime = activeSleepTimeUs();
2628 idleSleepTime = idleSleepTimeUs();
2629 standbyDelay = microseconds(activeSleepTime*2);
2630 }
2631
2632 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002633 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2634 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 // wait until we have something to do...
2636 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002637 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002638 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 mStandby = true;
2640 mBytesWritten = 0;
2641 }
2642
2643 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2644 // we're about to wait, flush the binder command buffer
2645 IPCThreadState::self()->flushCommands();
2646
2647 if (exitPending()) break;
2648
Eric Laurentfeb0db62011-07-22 09:04:31 -07002649 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002650 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002652 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002653 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654
Glenn Kastenf1d45922012-01-13 15:54:24 -08002655 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656 char value[PROPERTY_VALUE_MAX];
2657 property_get("ro.audio.silent", value, "0");
2658 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002659 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 setMasterMute(true);
2661 }
2662 }
2663
2664 standbyTime = systemTime() + standbyDelay;
2665 sleepTime = idleSleepTime;
2666 continue;
2667 }
2668 }
2669
2670 effectChains = mEffectChains;
2671
2672 // find out which tracks need to be processed
2673 if (mActiveTracks.size() != 0) {
2674 sp<Track> t = mActiveTracks[0].promote();
2675 if (t == 0) continue;
2676
2677 Track* const track = t.get();
2678 audio_track_cblk_t* cblk = track->cblk();
2679
2680 // The first time a track is added we wait
2681 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002682 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683 !track->isPaused() && !track->isTerminated())
2684 {
Steve Block3856b092011-10-20 11:56:00 +01002685 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686
2687 if (track->mFillingUpStatus == Track::FS_FILLED) {
2688 track->mFillingUpStatus = Track::FS_ACTIVE;
2689 mLeftVolFloat = mRightVolFloat = 0;
2690 mLeftVolShort = mRightVolShort = 0;
2691 if (track->mState == TrackBase::RESUMING) {
2692 track->mState = TrackBase::ACTIVE;
2693 rampVolume = true;
2694 }
2695 } else if (cblk->server != 0) {
2696 // If the track is stopped before the first frame was mixed,
2697 // do not apply ramp
2698 rampVolume = true;
2699 }
2700 // compute volume for this track
2701 float left, right;
2702 if (track->isMuted() || mMasterMute || track->isPausing() ||
2703 mStreamTypes[track->type()].mute) {
2704 left = right = 0;
2705 if (track->isPausing()) {
2706 track->setPaused();
2707 }
2708 } else {
2709 float typeVolume = mStreamTypes[track->type()].volume;
2710 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002711 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002712 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2714 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002715 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2717 right = v_clamped/MAX_GAIN;
2718 }
2719
2720 if (left != mLeftVolFloat || right != mRightVolFloat) {
2721 mLeftVolFloat = left;
2722 mRightVolFloat = right;
2723
2724 // If audio HAL implements volume control,
2725 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002726 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 left = 1.0f;
2728 right = 1.0f;
2729 }
2730
2731 // Convert volumes from float to 8.24
2732 uint32_t vl = (uint32_t)(left * (1 << 24));
2733 uint32_t vr = (uint32_t)(right * (1 << 24));
2734
2735 // Delegate volume control to effect in track effect chain if needed
2736 // only one effect chain can be present on DirectOutputThread, so if
2737 // there is one, the track is connected to it
2738 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002739 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002740 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002741 rampVolume = false;
2742 }
2743 }
2744
2745 // Convert volumes from 8.24 to 4.12 format
2746 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2747 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2748 leftVol = (uint16_t)v_clamped;
2749 v_clamped = (vr + (1 << 11)) >> 12;
2750 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2751 rightVol = (uint16_t)v_clamped;
2752 } else {
2753 leftVol = mLeftVolShort;
2754 rightVol = mRightVolShort;
2755 rampVolume = false;
2756 }
2757
2758 // reset retry count
2759 track->mRetryCount = kMaxTrackRetriesDirect;
2760 activeTrack = t;
2761 mixerStatus = MIXER_TRACKS_READY;
2762 } else {
Steve Block3856b092011-10-20 11:56:00 +01002763 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764 if (track->isStopped()) {
2765 track->reset();
2766 }
2767 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2768 // We have consumed all the buffers of this track.
2769 // Remove it from the list of active tracks.
2770 trackToRemove = track;
2771 } else {
2772 // No buffers for this track. Give it a few chances to
2773 // fill a buffer, then remove it from active list.
2774 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002775 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776 trackToRemove = track;
2777 } else {
2778 mixerStatus = MIXER_TRACKS_ENABLED;
2779 }
2780 }
2781 }
2782 }
2783
2784 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002785 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786 mActiveTracks.remove(trackToRemove);
2787 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002788 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002789 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002790 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 }
2792 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002793 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 }
2795 }
2796
Eric Laurentde070132010-07-13 04:45:46 -07002797 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 }
2799
Glenn Kastenf6b16782011-12-15 09:51:17 -08002800 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 AudioBufferProvider::Buffer buffer;
2802 size_t frameCount = mFrameCount;
2803 curBuf = (int8_t *)mMixBuffer;
2804 // output audio to hardware
2805 while (frameCount) {
2806 buffer.frameCount = frameCount;
2807 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002808 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 memset(curBuf, 0, frameCount * mFrameSize);
2810 break;
2811 }
2812 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2813 frameCount -= buffer.frameCount;
2814 curBuf += buffer.frameCount * mFrameSize;
2815 activeTrack->releaseBuffer(&buffer);
2816 }
2817 sleepTime = 0;
2818 standbyTime = systemTime() + standbyDelay;
2819 } else {
2820 if (sleepTime == 0) {
2821 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2822 sleepTime = activeSleepTime;
2823 } else {
2824 sleepTime = idleSleepTime;
2825 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002826 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2828 sleepTime = 0;
2829 }
2830 }
2831
2832 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002833 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835 // sleepTime == 0 means we must write to audio hardware
2836 if (sleepTime == 0) {
2837 if (mixerStatus == MIXER_TRACKS_READY) {
2838 applyVolume(leftVol, rightVol, rampVolume);
2839 }
2840 for (size_t i = 0; i < effectChains.size(); i ++) {
2841 effectChains[i]->process_l();
2842 }
Eric Laurentde070132010-07-13 04:45:46 -07002843 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844
2845 mLastWriteTime = systemTime();
2846 mInWrite = true;
2847 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002848 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2850 mNumWrites++;
2851 mInWrite = false;
2852 mStandby = false;
2853 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002854 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 usleep(sleepTime);
2856 }
2857
2858 // finally let go of removed track, without the lock held
2859 // since we can't guarantee the destructors won't acquire that
2860 // same lock.
2861 trackToRemove.clear();
2862 activeTrack.clear();
2863
2864 // Effect chains will be actually deleted here if they were removed from
2865 // mEffectChains list during mixing or effects processing
2866 effectChains.clear();
2867 }
2868
2869 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002870 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 }
2872
Eric Laurentfeb0db62011-07-22 09:04:31 -07002873 releaseWakeLock();
2874
Steve Block3856b092011-10-20 11:56:00 +01002875 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876 return false;
2877}
2878
2879// getTrackName_l() must be called with ThreadBase::mLock held
2880int AudioFlinger::DirectOutputThread::getTrackName_l()
2881{
2882 return 0;
2883}
2884
2885// deleteTrackName_l() must be called with ThreadBase::mLock held
2886void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2887{
2888}
2889
2890// checkForNewParameters_l() must be called with ThreadBase::mLock held
2891bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2892{
2893 bool reconfig = false;
2894
2895 while (!mNewParameters.isEmpty()) {
2896 status_t status = NO_ERROR;
2897 String8 keyValuePair = mNewParameters[0];
2898 AudioParameter param = AudioParameter(keyValuePair);
2899 int value;
2900
2901 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2902 // do not accept frame count changes if tracks are open as the track buffer
2903 // size depends on frame count and correct behavior would not be garantied
2904 // if frame count is changed after track creation
2905 if (!mTracks.isEmpty()) {
2906 status = INVALID_OPERATION;
2907 } else {
2908 reconfig = true;
2909 }
2910 }
2911 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002912 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002913 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002915 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916 mStandby = true;
2917 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002918 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002919 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 }
2921 if (status == NO_ERROR && reconfig) {
2922 readOutputParameters();
2923 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2924 }
2925 }
2926
2927 mNewParameters.removeAt(0);
2928
2929 mParamStatus = status;
2930 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002931 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2932 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002933 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 }
2935 return reconfig;
2936}
2937
2938uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2939{
2940 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002941 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002942 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 } else {
2944 time = 10000;
2945 }
2946 return time;
2947}
2948
2949uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2950{
2951 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002952 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002953 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 } else {
2955 time = 10000;
2956 }
2957 return time;
2958}
2959
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002960uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2961{
2962 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002963 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002964 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2965 } else {
2966 time = 10000;
2967 }
2968 return time;
2969}
2970
2971
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972// ----------------------------------------------------------------------------
2973
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002974AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
2975 AudioFlinger::MixerThread* mainThread, int id)
2976 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2977 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002978{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 addOutputTrack(mainThread);
2980}
2981
2982AudioFlinger::DuplicatingThread::~DuplicatingThread()
2983{
2984 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2985 mOutputTracks[i]->destroy();
2986 }
2987 mOutputTracks.clear();
2988}
2989
2990bool AudioFlinger::DuplicatingThread::threadLoop()
2991{
2992 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002993 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 nsecs_t standbyTime = systemTime();
2995 size_t mixBufferSize = mFrameCount*mFrameSize;
2996 SortedVector< sp<OutputTrack> > outputTracks;
2997 uint32_t writeFrames = 0;
2998 uint32_t activeSleepTime = activeSleepTimeUs();
2999 uint32_t idleSleepTime = idleSleepTimeUs();
3000 uint32_t sleepTime = idleSleepTime;
3001 Vector< sp<EffectChain> > effectChains;
3002
Eric Laurentfeb0db62011-07-22 09:04:31 -07003003 acquireWakeLock();
3004
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 while (!exitPending())
3006 {
3007 processConfigEvents();
3008
3009 mixerStatus = MIXER_IDLE;
3010 { // scope for the mLock
3011
3012 Mutex::Autolock _l(mLock);
3013
3014 if (checkForNewParameters_l()) {
3015 mixBufferSize = mFrameCount*mFrameSize;
3016 updateWaitTime();
3017 activeSleepTime = activeSleepTimeUs();
3018 idleSleepTime = idleSleepTimeUs();
3019 }
3020
3021 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3022
3023 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3024 outputTracks.add(mOutputTracks[i]);
3025 }
3026
3027 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003028 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3029 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 if (!mStandby) {
3031 for (size_t i = 0; i < outputTracks.size(); i++) {
3032 outputTracks[i]->stop();
3033 }
3034 mStandby = true;
3035 mBytesWritten = 0;
3036 }
3037
3038 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3039 // we're about to wait, flush the binder command buffer
3040 IPCThreadState::self()->flushCommands();
3041 outputTracks.clear();
3042
3043 if (exitPending()) break;
3044
Eric Laurentfeb0db62011-07-22 09:04:31 -07003045 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003046 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003048 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003049 acquireWakeLock_l();
3050
Eric Laurent27741442012-01-17 19:20:12 -08003051 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003052 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 char value[PROPERTY_VALUE_MAX];
3054 property_get("ro.audio.silent", value, "0");
3055 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003056 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 setMasterMute(true);
3058 }
3059 }
3060
3061 standbyTime = systemTime() + kStandbyTimeInNsecs;
3062 sleepTime = idleSleepTime;
3063 continue;
3064 }
3065 }
3066
3067 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3068
3069 // prevent any changes in effect chain list and in each effect chain
3070 // during mixing and effect process as the audio buffers could be deleted
3071 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003072 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 }
3074
Glenn Kastenf6b16782011-12-15 09:51:17 -08003075 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 // mix buffers...
3077 if (outputsReady(outputTracks)) {
3078 mAudioMixer->process();
3079 } else {
3080 memset(mMixBuffer, 0, mixBufferSize);
3081 }
3082 sleepTime = 0;
3083 writeFrames = mFrameCount;
3084 } else {
3085 if (sleepTime == 0) {
3086 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3087 sleepTime = activeSleepTime;
3088 } else {
3089 sleepTime = idleSleepTime;
3090 }
3091 } else if (mBytesWritten != 0) {
3092 // flush remaining overflow buffers in output tracks
3093 for (size_t i = 0; i < outputTracks.size(); i++) {
3094 if (outputTracks[i]->isActive()) {
3095 sleepTime = 0;
3096 writeFrames = 0;
3097 memset(mMixBuffer, 0, mixBufferSize);
3098 break;
3099 }
3100 }
3101 }
3102 }
3103
3104 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003105 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003106 }
3107 // sleepTime == 0 means we must write to audio hardware
3108 if (sleepTime == 0) {
3109 for (size_t i = 0; i < effectChains.size(); i ++) {
3110 effectChains[i]->process_l();
3111 }
3112 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003113 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114
3115 standbyTime = systemTime() + kStandbyTimeInNsecs;
3116 for (size_t i = 0; i < outputTracks.size(); i++) {
3117 outputTracks[i]->write(mMixBuffer, writeFrames);
3118 }
3119 mStandby = false;
3120 mBytesWritten += mixBufferSize;
3121 } else {
3122 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003123 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003124 usleep(sleepTime);
3125 }
3126
3127 // finally let go of all our tracks, without the lock held
3128 // since we can't guarantee the destructors won't acquire that
3129 // same lock.
3130 tracksToRemove.clear();
3131 outputTracks.clear();
3132
3133 // Effect chains will be actually deleted here if they were removed from
3134 // mEffectChains list during mixing or effects processing
3135 effectChains.clear();
3136 }
3137
Eric Laurentfeb0db62011-07-22 09:04:31 -07003138 releaseWakeLock();
3139
Mathias Agopian65ab4712010-07-14 17:59:35 -07003140 return false;
3141}
3142
3143void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3144{
3145 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3146 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3147 this,
3148 mSampleRate,
3149 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003150 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 frameCount);
3152 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003153 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003155 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 updateWaitTime();
3157 }
3158}
3159
3160void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3161{
3162 Mutex::Autolock _l(mLock);
3163 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3164 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3165 mOutputTracks[i]->destroy();
3166 mOutputTracks.removeAt(i);
3167 updateWaitTime();
3168 return;
3169 }
3170 }
Steve Block3856b092011-10-20 11:56:00 +01003171 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003172}
3173
3174void AudioFlinger::DuplicatingThread::updateWaitTime()
3175{
3176 mWaitTimeMs = UINT_MAX;
3177 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3178 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3179 if (strong != NULL) {
3180 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3181 if (waitTimeMs < mWaitTimeMs) {
3182 mWaitTimeMs = waitTimeMs;
3183 }
3184 }
3185 }
3186}
3187
3188
3189bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3190{
3191 for (size_t i = 0; i < outputTracks.size(); i++) {
3192 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3193 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003194 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195 return false;
3196 }
3197 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3198 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003199 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 return false;
3201 }
3202 }
3203 return true;
3204}
3205
3206uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3207{
3208 return (mWaitTimeMs * 1000) / 2;
3209}
3210
3211// ----------------------------------------------------------------------------
3212
3213// TrackBase constructor must be called with AudioFlinger::mLock held
3214AudioFlinger::ThreadBase::TrackBase::TrackBase(
3215 const wp<ThreadBase>& thread,
3216 const sp<Client>& client,
3217 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003218 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003219 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 int frameCount,
3221 uint32_t flags,
3222 const sp<IMemory>& sharedBuffer,
3223 int sessionId)
3224 : RefBase(),
3225 mThread(thread),
3226 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003227 mCblk(NULL),
3228 // mBuffer
3229 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 mFrameCount(0),
3231 mState(IDLE),
3232 mClientTid(-1),
3233 mFormat(format),
3234 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3235 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003236 // mChannelCount
3237 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238{
Steve Block3856b092011-10-20 11:56:00 +01003239 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240
Steve Blockb8a80522011-12-20 16:23:08 +00003241 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003243 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3245 if (sharedBuffer == 0) {
3246 size += bufferSize;
3247 }
3248
3249 if (client != NULL) {
3250 mCblkMemory = client->heap()->allocate(size);
3251 if (mCblkMemory != 0) {
3252 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003253 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 new(mCblk) audio_track_cblk_t();
3255 // clear all buffers
3256 mCblk->frameCount = frameCount;
3257 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003258 mChannelCount = channelCount;
3259 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003260 if (sharedBuffer == 0) {
3261 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3262 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3263 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003264 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 mCblk->flags = CBLK_UNDERRUN_ON;
3266 } else {
3267 mBuffer = sharedBuffer->pointer();
3268 }
3269 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3270 }
3271 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003272 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 client->heap()->dump("AudioTrack");
3274 return;
3275 }
3276 } else {
3277 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003278 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 new(mCblk) audio_track_cblk_t();
3280 // clear all buffers
3281 mCblk->frameCount = frameCount;
3282 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003283 mChannelCount = channelCount;
3284 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3286 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3287 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003288 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 mCblk->flags = CBLK_UNDERRUN_ON;
3290 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 }
3292}
3293
3294AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3295{
Glenn Kastena0d68332012-01-27 16:47:15 -08003296 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003297 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3298 if (mClient == NULL) {
3299 delete mCblk;
3300 }
3301 }
3302 mCblkMemory.clear(); // and free the shared memory
3303 if (mClient != NULL) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003304 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3306 mClient.clear();
3307 }
3308}
3309
3310void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3311{
Glenn Kastene0feee32011-12-13 11:53:26 -08003312 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 mFrameCount = buffer->frameCount;
3314 step();
3315 buffer->frameCount = 0;
3316}
3317
3318bool AudioFlinger::ThreadBase::TrackBase::step() {
3319 bool result;
3320 audio_track_cblk_t* cblk = this->cblk();
3321
3322 result = cblk->stepServer(mFrameCount);
3323 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003324 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 mFlags |= STEPSERVER_FAILED;
3326 }
3327 return result;
3328}
3329
3330void AudioFlinger::ThreadBase::TrackBase::reset() {
3331 audio_track_cblk_t* cblk = this->cblk();
3332
3333 cblk->user = 0;
3334 cblk->server = 0;
3335 cblk->userBase = 0;
3336 cblk->serverBase = 0;
3337 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003338 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339}
3340
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3342 return (int)mCblk->sampleRate;
3343}
3344
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3346 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003347 size_t frameSize = cblk->frameSize;
3348 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3349 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350
3351 // Check validity of returned pointer in case the track control block would have been corrupted.
3352 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003353 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003354 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 -07003355 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003357 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003358 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 }
3360
3361 return bufferStart;
3362}
3363
3364// ----------------------------------------------------------------------------
3365
3366// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3367AudioFlinger::PlaybackThread::Track::Track(
3368 const wp<ThreadBase>& thread,
3369 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003370 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003372 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003373 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 int frameCount,
3375 const sp<IMemory>& sharedBuffer,
3376 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003377 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003378 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3379 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380{
3381 if (mCblk != NULL) {
3382 sp<ThreadBase> baseThread = thread.promote();
3383 if (baseThread != 0) {
3384 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3385 mName = playbackThread->getTrackName_l();
3386 mMainBuffer = playbackThread->mixBuffer();
3387 }
Steve Block3856b092011-10-20 11:56:00 +01003388 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003389 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003390 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003391 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 mStreamType = streamType;
3393 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3394 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003395 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 }
3397}
3398
3399AudioFlinger::PlaybackThread::Track::~Track()
3400{
Steve Block3856b092011-10-20 11:56:00 +01003401 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 sp<ThreadBase> thread = mThread.promote();
3403 if (thread != 0) {
3404 Mutex::Autolock _l(thread->mLock);
3405 mState = TERMINATED;
3406 }
3407}
3408
3409void AudioFlinger::PlaybackThread::Track::destroy()
3410{
3411 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3412 // by removing it from mTracks vector, so there is a risk that this Tracks's
3413 // desctructor is called. As the destructor needs to lock mLock,
3414 // we must acquire a strong reference on this Track before locking mLock
3415 // here so that the destructor is called only when exiting this function.
3416 // On the other hand, as long as Track::destroy() is only called by
3417 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3418 // this Track with its member mTrack.
3419 sp<Track> keep(this);
3420 { // scope for mLock
3421 sp<ThreadBase> thread = mThread.promote();
3422 if (thread != 0) {
3423 if (!isOutputTrack()) {
3424 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003425 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003426 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003427 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003428
3429 // to track the speaker usage
3430 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 }
3432 AudioSystem::releaseOutput(thread->id());
3433 }
3434 Mutex::Autolock _l(thread->mLock);
3435 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3436 playbackThread->destroyTrack_l(this);
3437 }
3438 }
3439}
3440
3441void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3442{
Glenn Kasten83d86532012-01-17 14:39:34 -08003443 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003444 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 -07003445 mName - AudioMixer::TRACK0,
3446 (mClient == NULL) ? getpid() : mClient->pid(),
3447 mStreamType,
3448 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003449 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 mSessionId,
3451 mFrameCount,
3452 mState,
3453 mMute,
3454 mFillingUpStatus,
3455 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003456 vlr & 0xFFFF,
3457 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 mCblk->server,
3459 mCblk->user,
3460 (int)mMainBuffer,
3461 (int)mAuxBuffer);
3462}
3463
3464status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3465{
3466 audio_track_cblk_t* cblk = this->cblk();
3467 uint32_t framesReady;
3468 uint32_t framesReq = buffer->frameCount;
3469
3470 // Check if last stepServer failed, try to step now
3471 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3472 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003473 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3475 }
3476
3477 framesReady = cblk->framesReady();
3478
Glenn Kastenf6b16782011-12-15 09:51:17 -08003479 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 uint32_t s = cblk->server;
3481 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3482
3483 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3484 if (framesReq > framesReady) {
3485 framesReq = framesReady;
3486 }
3487 if (s + framesReq > bufferEnd) {
3488 framesReq = bufferEnd - s;
3489 }
3490
3491 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003492 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493
3494 buffer->frameCount = framesReq;
3495 return NO_ERROR;
3496 }
3497
3498getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003499 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003501 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 return NOT_ENOUGH_DATA;
3503}
3504
3505bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003506 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507
3508 if (mCblk->framesReady() >= mCblk->frameCount ||
3509 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3510 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003511 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512 return true;
3513 }
3514 return false;
3515}
3516
3517status_t AudioFlinger::PlaybackThread::Track::start()
3518{
3519 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003520 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003521 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 sp<ThreadBase> thread = mThread.promote();
3523 if (thread != 0) {
3524 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003525 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526 // here the track could be either new, or restarted
3527 // in both cases "unstop" the track
3528 if (mState == PAUSED) {
3529 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003530 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 } else {
3532 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003533 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 }
3535
3536 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3537 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003538 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003539 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003540 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003542
3543 // to track the speaker usage
3544 if (status == NO_ERROR) {
3545 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 }
3548 if (status == NO_ERROR) {
3549 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3550 playbackThread->addTrack_l(this);
3551 } else {
3552 mState = state;
3553 }
3554 } else {
3555 status = BAD_VALUE;
3556 }
3557 return status;
3558}
3559
3560void AudioFlinger::PlaybackThread::Track::stop()
3561{
Steve Block3856b092011-10-20 11:56:00 +01003562 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003563 sp<ThreadBase> thread = mThread.promote();
3564 if (thread != 0) {
3565 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003566 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 if (mState > STOPPED) {
3568 mState = STOPPED;
3569 // If the track is not active (PAUSED and buffers full), flush buffers
3570 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3571 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3572 reset();
3573 }
Steve Block3856b092011-10-20 11:56:00 +01003574 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 }
3576 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3577 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003578 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003579 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003580 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003582
3583 // to track the speaker usage
3584 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 }
3586 }
3587}
3588
3589void AudioFlinger::PlaybackThread::Track::pause()
3590{
Steve Block3856b092011-10-20 11:56:00 +01003591 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592 sp<ThreadBase> thread = mThread.promote();
3593 if (thread != 0) {
3594 Mutex::Autolock _l(thread->mLock);
3595 if (mState == ACTIVE || mState == RESUMING) {
3596 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003597 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 if (!isOutputTrack()) {
3599 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003600 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003601 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003602 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003604
3605 // to track the speaker usage
3606 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003607 }
3608 }
3609 }
3610}
3611
3612void AudioFlinger::PlaybackThread::Track::flush()
3613{
Steve Block3856b092011-10-20 11:56:00 +01003614 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003615 sp<ThreadBase> thread = mThread.promote();
3616 if (thread != 0) {
3617 Mutex::Autolock _l(thread->mLock);
3618 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3619 return;
3620 }
3621 // No point remaining in PAUSED state after a flush => go to
3622 // STOPPED state
3623 mState = STOPPED;
3624
Eric Laurent38ccae22011-03-28 18:37:07 -07003625 // do not reset the track if it is still in the process of being stopped or paused.
3626 // this will be done by prepareTracks_l() when the track is stopped.
3627 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3628 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3629 reset();
3630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003631 }
3632}
3633
3634void AudioFlinger::PlaybackThread::Track::reset()
3635{
3636 // Do not reset twice to avoid discarding data written just after a flush and before
3637 // the audioflinger thread detects the track is stopped.
3638 if (!mResetDone) {
3639 TrackBase::reset();
3640 // Force underrun condition to avoid false underrun callback until first data is
3641 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003642 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3643 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644 mFillingUpStatus = FS_FILLING;
3645 mResetDone = true;
3646 }
3647}
3648
3649void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3650{
3651 mMute = muted;
3652}
3653
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3655{
3656 status_t status = DEAD_OBJECT;
3657 sp<ThreadBase> thread = mThread.promote();
3658 if (thread != 0) {
3659 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3660 status = playbackThread->attachAuxEffect(this, EffectId);
3661 }
3662 return status;
3663}
3664
3665void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3666{
3667 mAuxEffectId = EffectId;
3668 mAuxBuffer = buffer;
3669}
3670
3671// ----------------------------------------------------------------------------
3672
3673// RecordTrack constructor must be called with AudioFlinger::mLock held
3674AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3675 const wp<ThreadBase>& thread,
3676 const sp<Client>& client,
3677 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003678 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003679 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680 int frameCount,
3681 uint32_t flags,
3682 int sessionId)
3683 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003684 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 mOverflow(false)
3686{
3687 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003688 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003689 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003690 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003691 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003692 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 } else {
3694 mCblk->frameSize = sizeof(int8_t);
3695 }
3696 }
3697}
3698
3699AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3700{
3701 sp<ThreadBase> thread = mThread.promote();
3702 if (thread != 0) {
3703 AudioSystem::releaseInput(thread->id());
3704 }
3705}
3706
3707status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3708{
3709 audio_track_cblk_t* cblk = this->cblk();
3710 uint32_t framesAvail;
3711 uint32_t framesReq = buffer->frameCount;
3712
3713 // Check if last stepServer failed, try to step now
3714 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3715 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003716 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003717 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3718 }
3719
3720 framesAvail = cblk->framesAvailable_l();
3721
Glenn Kastenf6b16782011-12-15 09:51:17 -08003722 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723 uint32_t s = cblk->server;
3724 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3725
3726 if (framesReq > framesAvail) {
3727 framesReq = framesAvail;
3728 }
3729 if (s + framesReq > bufferEnd) {
3730 framesReq = bufferEnd - s;
3731 }
3732
3733 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003734 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735
3736 buffer->frameCount = framesReq;
3737 return NO_ERROR;
3738 }
3739
3740getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003741 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003742 buffer->frameCount = 0;
3743 return NOT_ENOUGH_DATA;
3744}
3745
3746status_t AudioFlinger::RecordThread::RecordTrack::start()
3747{
3748 sp<ThreadBase> thread = mThread.promote();
3749 if (thread != 0) {
3750 RecordThread *recordThread = (RecordThread *)thread.get();
3751 return recordThread->start(this);
3752 } else {
3753 return BAD_VALUE;
3754 }
3755}
3756
3757void AudioFlinger::RecordThread::RecordTrack::stop()
3758{
3759 sp<ThreadBase> thread = mThread.promote();
3760 if (thread != 0) {
3761 RecordThread *recordThread = (RecordThread *)thread.get();
3762 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003763 TrackBase::reset();
3764 // Force overerrun condition to avoid false overrun callback until first data is
3765 // read from buffer
3766 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 }
3768}
3769
3770void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3771{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003772 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773 (mClient == NULL) ? getpid() : mClient->pid(),
3774 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003775 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 mSessionId,
3777 mFrameCount,
3778 mState,
3779 mCblk->sampleRate,
3780 mCblk->server,
3781 mCblk->user);
3782}
3783
3784
3785// ----------------------------------------------------------------------------
3786
3787AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3788 const wp<ThreadBase>& thread,
3789 DuplicatingThread *sourceThread,
3790 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003791 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003792 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003794 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 mActive(false), mSourceThread(sourceThread)
3796{
3797
3798 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3799 if (mCblk != NULL) {
3800 mCblk->flags |= CBLK_DIRECTION_OUT;
3801 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003802 mOutBuffer.frameCount = 0;
3803 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003804 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003805 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3806 mCblk, mBuffer, mCblk->buffers,
3807 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003809 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003810 }
3811}
3812
3813AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3814{
3815 clearBufferQueue();
3816}
3817
3818status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3819{
3820 status_t status = Track::start();
3821 if (status != NO_ERROR) {
3822 return status;
3823 }
3824
3825 mActive = true;
3826 mRetryCount = 127;
3827 return status;
3828}
3829
3830void AudioFlinger::PlaybackThread::OutputTrack::stop()
3831{
3832 Track::stop();
3833 clearBufferQueue();
3834 mOutBuffer.frameCount = 0;
3835 mActive = false;
3836}
3837
3838bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3839{
3840 Buffer *pInBuffer;
3841 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003842 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 bool outputBufferFull = false;
3844 inBuffer.frameCount = frames;
3845 inBuffer.i16 = data;
3846
3847 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3848
3849 if (!mActive && frames != 0) {
3850 start();
3851 sp<ThreadBase> thread = mThread.promote();
3852 if (thread != 0) {
3853 MixerThread *mixerThread = (MixerThread *)thread.get();
3854 if (mCblk->frameCount > frames){
3855 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3856 uint32_t startFrames = (mCblk->frameCount - frames);
3857 pInBuffer = new Buffer;
3858 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3859 pInBuffer->frameCount = startFrames;
3860 pInBuffer->i16 = pInBuffer->mBuffer;
3861 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3862 mBufferQueue.add(pInBuffer);
3863 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003864 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 }
3866 }
3867 }
3868 }
3869
3870 while (waitTimeLeftMs) {
3871 // First write pending buffers, then new data
3872 if (mBufferQueue.size()) {
3873 pInBuffer = mBufferQueue.itemAt(0);
3874 } else {
3875 pInBuffer = &inBuffer;
3876 }
3877
3878 if (pInBuffer->frameCount == 0) {
3879 break;
3880 }
3881
3882 if (mOutBuffer.frameCount == 0) {
3883 mOutBuffer.frameCount = pInBuffer->frameCount;
3884 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003885 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003886 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 outputBufferFull = true;
3888 break;
3889 }
3890 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3891 if (waitTimeLeftMs >= waitTimeMs) {
3892 waitTimeLeftMs -= waitTimeMs;
3893 } else {
3894 waitTimeLeftMs = 0;
3895 }
3896 }
3897
3898 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3899 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3900 mCblk->stepUser(outFrames);
3901 pInBuffer->frameCount -= outFrames;
3902 pInBuffer->i16 += outFrames * channelCount;
3903 mOutBuffer.frameCount -= outFrames;
3904 mOutBuffer.i16 += outFrames * channelCount;
3905
3906 if (pInBuffer->frameCount == 0) {
3907 if (mBufferQueue.size()) {
3908 mBufferQueue.removeAt(0);
3909 delete [] pInBuffer->mBuffer;
3910 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003911 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912 } else {
3913 break;
3914 }
3915 }
3916 }
3917
3918 // If we could not write all frames, allocate a buffer and queue it for next time.
3919 if (inBuffer.frameCount) {
3920 sp<ThreadBase> thread = mThread.promote();
3921 if (thread != 0 && !thread->standby()) {
3922 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3923 pInBuffer = new Buffer;
3924 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3925 pInBuffer->frameCount = inBuffer.frameCount;
3926 pInBuffer->i16 = pInBuffer->mBuffer;
3927 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3928 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003929 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003931 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 }
3933 }
3934 }
3935
3936 // Calling write() with a 0 length buffer, means that no more data will be written:
3937 // If no more buffers are pending, fill output track buffer to make sure it is started
3938 // by output mixer.
3939 if (frames == 0 && mBufferQueue.size() == 0) {
3940 if (mCblk->user < mCblk->frameCount) {
3941 frames = mCblk->frameCount - mCblk->user;
3942 pInBuffer = new Buffer;
3943 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3944 pInBuffer->frameCount = frames;
3945 pInBuffer->i16 = pInBuffer->mBuffer;
3946 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3947 mBufferQueue.add(pInBuffer);
3948 } else if (mActive) {
3949 stop();
3950 }
3951 }
3952
3953 return outputBufferFull;
3954}
3955
3956status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3957{
3958 int active;
3959 status_t result;
3960 audio_track_cblk_t* cblk = mCblk;
3961 uint32_t framesReq = buffer->frameCount;
3962
Steve Block3856b092011-10-20 11:56:00 +01003963// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964 buffer->frameCount = 0;
3965
3966 uint32_t framesAvail = cblk->framesAvailable();
3967
3968
3969 if (framesAvail == 0) {
3970 Mutex::Autolock _l(cblk->lock);
3971 goto start_loop_here;
3972 while (framesAvail == 0) {
3973 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003974 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003975 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003976 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 }
3978 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3979 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003980 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003981 }
3982 // read the server count again
3983 start_loop_here:
3984 framesAvail = cblk->framesAvailable_l();
3985 }
3986 }
3987
3988// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003989// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990// }
3991
3992 if (framesReq > framesAvail) {
3993 framesReq = framesAvail;
3994 }
3995
3996 uint32_t u = cblk->user;
3997 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3998
3999 if (u + framesReq > bufferEnd) {
4000 framesReq = bufferEnd - u;
4001 }
4002
4003 buffer->frameCount = framesReq;
4004 buffer->raw = (void *)cblk->buffer(u);
4005 return NO_ERROR;
4006}
4007
4008
4009void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4010{
4011 size_t size = mBufferQueue.size();
4012 Buffer *pBuffer;
4013
4014 for (size_t i = 0; i < size; i++) {
4015 pBuffer = mBufferQueue.itemAt(i);
4016 delete [] pBuffer->mBuffer;
4017 delete pBuffer;
4018 }
4019 mBufferQueue.clear();
4020}
4021
4022// ----------------------------------------------------------------------------
4023
4024AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4025 : RefBase(),
4026 mAudioFlinger(audioFlinger),
4027 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4028 mPid(pid)
4029{
4030 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4031}
4032
4033// Client destructor must be called with AudioFlinger::mLock held
4034AudioFlinger::Client::~Client()
4035{
4036 mAudioFlinger->removeClient_l(mPid);
4037}
4038
Glenn Kasten435dbe62012-01-30 10:15:48 -08004039sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040{
4041 return mMemoryDealer;
4042}
4043
4044// ----------------------------------------------------------------------------
4045
4046AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4047 const sp<IAudioFlingerClient>& client,
4048 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004049 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050{
4051}
4052
4053AudioFlinger::NotificationClient::~NotificationClient()
4054{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055}
4056
4057void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4058{
4059 sp<NotificationClient> keep(this);
4060 {
4061 mAudioFlinger->removeNotificationClient(mPid);
4062 }
4063}
4064
4065// ----------------------------------------------------------------------------
4066
4067AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4068 : BnAudioTrack(),
4069 mTrack(track)
4070{
4071}
4072
4073AudioFlinger::TrackHandle::~TrackHandle() {
4074 // just stop the track on deletion, associated resources
4075 // will be freed from the main thread once all pending buffers have
4076 // been played. Unless it's not in the active track list, in which
4077 // case we free everything now...
4078 mTrack->destroy();
4079}
4080
Glenn Kasten90716c52012-01-26 13:40:12 -08004081sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4082 return mTrack->getCblk();
4083}
4084
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085status_t AudioFlinger::TrackHandle::start() {
4086 return mTrack->start();
4087}
4088
4089void AudioFlinger::TrackHandle::stop() {
4090 mTrack->stop();
4091}
4092
4093void AudioFlinger::TrackHandle::flush() {
4094 mTrack->flush();
4095}
4096
4097void AudioFlinger::TrackHandle::mute(bool e) {
4098 mTrack->mute(e);
4099}
4100
4101void AudioFlinger::TrackHandle::pause() {
4102 mTrack->pause();
4103}
4104
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4106{
4107 return mTrack->attachAuxEffect(EffectId);
4108}
4109
4110status_t AudioFlinger::TrackHandle::onTransact(
4111 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4112{
4113 return BnAudioTrack::onTransact(code, data, reply, flags);
4114}
4115
4116// ----------------------------------------------------------------------------
4117
4118sp<IAudioRecord> AudioFlinger::openRecord(
4119 pid_t pid,
4120 int input,
4121 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004122 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004123 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004124 int frameCount,
4125 uint32_t flags,
4126 int *sessionId,
4127 status_t *status)
4128{
4129 sp<RecordThread::RecordTrack> recordTrack;
4130 sp<RecordHandle> recordHandle;
4131 sp<Client> client;
4132 wp<Client> wclient;
4133 status_t lStatus;
4134 RecordThread *thread;
4135 size_t inFrameCount;
4136 int lSessionId;
4137
4138 // check calling permissions
4139 if (!recordingAllowed()) {
4140 lStatus = PERMISSION_DENIED;
4141 goto Exit;
4142 }
4143
4144 // add client to list
4145 { // scope for mLock
4146 Mutex::Autolock _l(mLock);
4147 thread = checkRecordThread_l(input);
4148 if (thread == NULL) {
4149 lStatus = BAD_VALUE;
4150 goto Exit;
4151 }
4152
4153 wclient = mClients.valueFor(pid);
4154 if (wclient != NULL) {
4155 client = wclient.promote();
4156 } else {
4157 client = new Client(this, pid);
4158 mClients.add(pid, client);
4159 }
4160
4161 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004162 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 lSessionId = *sessionId;
4164 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004165 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 if (sessionId != NULL) {
4167 *sessionId = lSessionId;
4168 }
4169 }
4170 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004171 recordTrack = thread->createRecordTrack_l(client,
4172 sampleRate,
4173 format,
4174 channelMask,
4175 frameCount,
4176 flags,
4177 lSessionId,
4178 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004180 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4182 // destructor is called by the TrackBase destructor with mLock held
4183 client.clear();
4184 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185 goto Exit;
4186 }
4187
4188 // return to handle to client
4189 recordHandle = new RecordHandle(recordTrack);
4190 lStatus = NO_ERROR;
4191
4192Exit:
4193 if (status) {
4194 *status = lStatus;
4195 }
4196 return recordHandle;
4197}
4198
4199// ----------------------------------------------------------------------------
4200
4201AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4202 : BnAudioRecord(),
4203 mRecordTrack(recordTrack)
4204{
4205}
4206
4207AudioFlinger::RecordHandle::~RecordHandle() {
4208 stop();
4209}
4210
Glenn Kasten90716c52012-01-26 13:40:12 -08004211sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4212 return mRecordTrack->getCblk();
4213}
4214
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004216 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 return mRecordTrack->start();
4218}
4219
4220void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004221 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 mRecordTrack->stop();
4223}
4224
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225status_t AudioFlinger::RecordHandle::onTransact(
4226 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4227{
4228 return BnAudioRecord::onTransact(code, data, reply, flags);
4229}
4230
4231// ----------------------------------------------------------------------------
4232
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004233AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4234 AudioStreamIn *input,
4235 uint32_t sampleRate,
4236 uint32_t channels,
4237 int id,
4238 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004239 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004240 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4241 // mRsmpInIndex and mInputBytes set by readInputParameters()
4242 mReqChannelCount(popcount(channels)),
4243 mReqSampleRate(sampleRate)
4244 // mBytesRead is only meaningful while active, and so is cleared in start()
4245 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004247 snprintf(mName, kNameLength, "AudioIn_%d", id);
4248
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 readInputParameters();
4250}
4251
4252
4253AudioFlinger::RecordThread::~RecordThread()
4254{
4255 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004256 delete mResampler;
4257 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258}
4259
4260void AudioFlinger::RecordThread::onFirstRef()
4261{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004262 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263}
4264
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004265status_t AudioFlinger::RecordThread::readyToRun()
4266{
4267 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004268 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004269 return status;
4270}
4271
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272bool AudioFlinger::RecordThread::threadLoop()
4273{
4274 AudioBufferProvider::Buffer buffer;
4275 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004276 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277
Eric Laurent44d98482010-09-30 16:12:31 -07004278 nsecs_t lastWarning = 0;
4279
Eric Laurentfeb0db62011-07-22 09:04:31 -07004280 acquireWakeLock();
4281
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282 // start recording
4283 while (!exitPending()) {
4284
4285 processConfigEvents();
4286
4287 { // scope for mLock
4288 Mutex::Autolock _l(mLock);
4289 checkForNewParameters_l();
4290 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4291 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004292 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 mStandby = true;
4294 }
4295
4296 if (exitPending()) break;
4297
Eric Laurentfeb0db62011-07-22 09:04:31 -07004298 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004299 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 // go to sleep
4301 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004302 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004303 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004304 continue;
4305 }
4306 if (mActiveTrack != 0) {
4307 if (mActiveTrack->mState == TrackBase::PAUSING) {
4308 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004309 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 mStandby = true;
4311 }
4312 mActiveTrack.clear();
4313 mStartStopCond.broadcast();
4314 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4315 if (mReqChannelCount != mActiveTrack->channelCount()) {
4316 mActiveTrack.clear();
4317 mStartStopCond.broadcast();
4318 } else if (mBytesRead != 0) {
4319 // record start succeeds only if first read from audio input
4320 // succeeds
4321 if (mBytesRead > 0) {
4322 mActiveTrack->mState = TrackBase::ACTIVE;
4323 } else {
4324 mActiveTrack.clear();
4325 }
4326 mStartStopCond.broadcast();
4327 }
4328 mStandby = false;
4329 }
4330 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004331 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004332 }
4333
4334 if (mActiveTrack != 0) {
4335 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4336 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004337 unlockEffectChains(effectChains);
4338 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339 continue;
4340 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004341 for (size_t i = 0; i < effectChains.size(); i ++) {
4342 effectChains[i]->process_l();
4343 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004344
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004346 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004348 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 // no resampling
4350 while (framesOut) {
4351 size_t framesIn = mFrameCount - mRsmpInIndex;
4352 if (framesIn) {
4353 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4354 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4355 if (framesIn > framesOut)
4356 framesIn = framesOut;
4357 mRsmpInIndex += framesIn;
4358 framesOut -= framesIn;
4359 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004360 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361 memcpy(dst, src, framesIn * mFrameSize);
4362 } else {
4363 int16_t *src16 = (int16_t *)src;
4364 int16_t *dst16 = (int16_t *)dst;
4365 if (mChannelCount == 1) {
4366 while (framesIn--) {
4367 *dst16++ = *src16;
4368 *dst16++ = *src16++;
4369 }
4370 } else {
4371 while (framesIn--) {
4372 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4373 src16 += 2;
4374 }
4375 }
4376 }
4377 }
4378 if (framesOut && mFrameCount == mRsmpInIndex) {
4379 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004380 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004381 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 framesOut = 0;
4383 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004384 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004385 mRsmpInIndex = 0;
4386 }
4387 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004388 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4390 // Force input into standby so that it tries to
4391 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004392 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004393 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394 }
4395 mRsmpInIndex = mFrameCount;
4396 framesOut = 0;
4397 buffer.frameCount = 0;
4398 }
4399 }
4400 }
4401 } else {
4402 // resampling
4403
4404 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4405 // alter output frame count as if we were expecting stereo samples
4406 if (mChannelCount == 1 && mReqChannelCount == 1) {
4407 framesOut >>= 1;
4408 }
4409 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4410 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4411 // are 32 bit aligned which should be always true.
4412 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004413 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004414 // the resampler always outputs stereo samples: do post stereo to mono conversion
4415 int16_t *src = (int16_t *)mRsmpOutBuffer;
4416 int16_t *dst = buffer.i16;
4417 while (framesOut--) {
4418 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4419 src += 2;
4420 }
4421 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004422 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424
4425 }
4426 mActiveTrack->releaseBuffer(&buffer);
4427 mActiveTrack->overflow();
4428 }
4429 // client isn't retrieving buffers fast enough
4430 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004431 if (!mActiveTrack->setOverflow()) {
4432 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004433 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004434 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004435 lastWarning = now;
4436 }
4437 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438 // Release the processor for a while before asking for a new buffer.
4439 // This will give the application more chance to read from the buffer and
4440 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004441 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442 }
4443 }
Eric Laurentec437d82011-07-26 20:54:46 -07004444 // enable changes in effect chain
4445 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004446 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 }
4448
4449 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004450 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004451 }
4452 mActiveTrack.clear();
4453
4454 mStartStopCond.broadcast();
4455
Eric Laurentfeb0db62011-07-22 09:04:31 -07004456 releaseWakeLock();
4457
Steve Block3856b092011-10-20 11:56:00 +01004458 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 return false;
4460}
4461
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004462
4463sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4464 const sp<AudioFlinger::Client>& client,
4465 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004466 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004467 int channelMask,
4468 int frameCount,
4469 uint32_t flags,
4470 int sessionId,
4471 status_t *status)
4472{
4473 sp<RecordTrack> track;
4474 status_t lStatus;
4475
4476 lStatus = initCheck();
4477 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004478 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004479 goto Exit;
4480 }
4481
4482 { // scope for mLock
4483 Mutex::Autolock _l(mLock);
4484
4485 track = new RecordTrack(this, client, sampleRate,
4486 format, channelMask, frameCount, flags, sessionId);
4487
4488 if (track->getCblk() == NULL) {
4489 lStatus = NO_MEMORY;
4490 goto Exit;
4491 }
4492
4493 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004494 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4495 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004496 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004497 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4498 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004499 }
4500 lStatus = NO_ERROR;
4501
4502Exit:
4503 if (status) {
4504 *status = lStatus;
4505 }
4506 return track;
4507}
4508
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4510{
Steve Block3856b092011-10-20 11:56:00 +01004511 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 sp <ThreadBase> strongMe = this;
4513 status_t status = NO_ERROR;
4514 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004515 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 if (mActiveTrack != 0) {
4517 if (recordTrack != mActiveTrack.get()) {
4518 status = -EBUSY;
4519 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4520 mActiveTrack->mState = TrackBase::ACTIVE;
4521 }
4522 return status;
4523 }
4524
4525 recordTrack->mState = TrackBase::IDLE;
4526 mActiveTrack = recordTrack;
4527 mLock.unlock();
4528 status_t status = AudioSystem::startInput(mId);
4529 mLock.lock();
4530 if (status != NO_ERROR) {
4531 mActiveTrack.clear();
4532 return status;
4533 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004534 mRsmpInIndex = mFrameCount;
4535 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004536 if (mResampler != NULL) {
4537 mResampler->reset();
4538 }
4539 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004541 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 mWaitWorkCV.signal();
4543 // do not wait for mStartStopCond if exiting
4544 if (mExiting) {
4545 mActiveTrack.clear();
4546 status = INVALID_OPERATION;
4547 goto startError;
4548 }
4549 mStartStopCond.wait(mLock);
4550 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004551 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 status = BAD_VALUE;
4553 goto startError;
4554 }
Steve Block3856b092011-10-20 11:56:00 +01004555 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 return status;
4557 }
4558startError:
4559 AudioSystem::stopInput(mId);
4560 return status;
4561}
4562
4563void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004564 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 sp <ThreadBase> strongMe = this;
4566 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004567 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4569 mActiveTrack->mState = TrackBase::PAUSING;
4570 // do not wait for mStartStopCond if exiting
4571 if (mExiting) {
4572 return;
4573 }
4574 mStartStopCond.wait(mLock);
4575 // if we have been restarted, recordTrack == mActiveTrack.get() here
4576 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4577 mLock.unlock();
4578 AudioSystem::stopInput(mId);
4579 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004580 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581 }
4582 }
4583 }
4584}
4585
4586status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4587{
4588 const size_t SIZE = 256;
4589 char buffer[SIZE];
4590 String8 result;
4591 pid_t pid = 0;
4592
4593 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4594 result.append(buffer);
4595
4596 if (mActiveTrack != 0) {
4597 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004598 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 mActiveTrack->dump(buffer, SIZE);
4600 result.append(buffer);
4601
4602 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4603 result.append(buffer);
4604 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4605 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004606 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607 result.append(buffer);
4608 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4609 result.append(buffer);
4610 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4611 result.append(buffer);
4612
4613
4614 } else {
4615 result.append("No record client\n");
4616 }
4617 write(fd, result.string(), result.size());
4618
4619 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004620 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621
4622 return NO_ERROR;
4623}
4624
4625status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4626{
4627 size_t framesReq = buffer->frameCount;
4628 size_t framesReady = mFrameCount - mRsmpInIndex;
4629 int channelCount;
4630
4631 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004632 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004634 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4636 // Force input into standby so that it tries to
4637 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004638 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004639 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004641 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 buffer->frameCount = 0;
4643 return NOT_ENOUGH_DATA;
4644 }
4645 mRsmpInIndex = 0;
4646 framesReady = mFrameCount;
4647 }
4648
4649 if (framesReq > framesReady) {
4650 framesReq = framesReady;
4651 }
4652
4653 if (mChannelCount == 1 && mReqChannelCount == 2) {
4654 channelCount = 1;
4655 } else {
4656 channelCount = 2;
4657 }
4658 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4659 buffer->frameCount = framesReq;
4660 return NO_ERROR;
4661}
4662
4663void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4664{
4665 mRsmpInIndex += buffer->frameCount;
4666 buffer->frameCount = 0;
4667}
4668
4669bool AudioFlinger::RecordThread::checkForNewParameters_l()
4670{
4671 bool reconfig = false;
4672
4673 while (!mNewParameters.isEmpty()) {
4674 status_t status = NO_ERROR;
4675 String8 keyValuePair = mNewParameters[0];
4676 AudioParameter param = AudioParameter(keyValuePair);
4677 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004678 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004679 int reqSamplingRate = mReqSampleRate;
4680 int reqChannelCount = mReqChannelCount;
4681
4682 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4683 reqSamplingRate = value;
4684 reconfig = true;
4685 }
4686 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004687 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688 reconfig = true;
4689 }
4690 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004691 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 reconfig = true;
4693 }
4694 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4695 // do not accept frame count changes if tracks are open as the track buffer
4696 // size depends on frame count and correct behavior would not be garantied
4697 // if frame count is changed after track creation
4698 if (mActiveTrack != 0) {
4699 status = INVALID_OPERATION;
4700 } else {
4701 reconfig = true;
4702 }
4703 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004704 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4705 // forward device change to effects that have requested to be
4706 // aware of attached audio device.
4707 for (size_t i = 0; i < mEffectChains.size(); i++) {
4708 mEffectChains[i]->setDevice_l(value);
4709 }
4710 // store input device and output device but do not forward output device to audio HAL.
4711 // Note that status is ignored by the caller for output device
4712 // (see AudioFlinger::setParameters()
4713 if (value & AUDIO_DEVICE_OUT_ALL) {
4714 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4715 status = BAD_VALUE;
4716 } else {
4717 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004718 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4719 if (mTrack != NULL) {
4720 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004721 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004722 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4723 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4724 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004725 }
4726 mDevice |= (uint32_t)value;
4727 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004729 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004731 mInput->stream->common.standby(&mInput->stream->common);
4732 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004733 }
4734 if (reconfig) {
4735 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004736 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004737 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004738 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4739 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004740 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741 status = NO_ERROR;
4742 }
4743 if (status == NO_ERROR) {
4744 readInputParameters();
4745 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4746 }
4747 }
4748 }
4749
4750 mNewParameters.removeAt(0);
4751
4752 mParamStatus = status;
4753 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004754 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4755 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004756 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004757 }
4758 return reconfig;
4759}
4760
4761String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4762{
Dima Zavinfce7a472011-04-19 22:30:36 -07004763 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004764 String8 out_s8 = String8();
4765
4766 Mutex::Autolock _l(mLock);
4767 if (initCheck() != NO_ERROR) {
4768 return out_s8;
4769 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004770
Dima Zavin799a70e2011-04-18 16:57:27 -07004771 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004772 out_s8 = String8(s);
4773 free(s);
4774 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004775}
4776
4777void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4778 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004779 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004780
4781 switch (event) {
4782 case AudioSystem::INPUT_OPENED:
4783 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004784 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004785 desc.samplingRate = mSampleRate;
4786 desc.format = mFormat;
4787 desc.frameCount = mFrameCount;
4788 desc.latency = 0;
4789 param2 = &desc;
4790 break;
4791
4792 case AudioSystem::INPUT_CLOSED:
4793 default:
4794 break;
4795 }
4796 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4797}
4798
4799void AudioFlinger::RecordThread::readInputParameters()
4800{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004801 delete mRsmpInBuffer;
4802 // mRsmpInBuffer is always assigned a new[] below
4803 delete mRsmpOutBuffer;
4804 mRsmpOutBuffer = NULL;
4805 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004806 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807
Dima Zavin799a70e2011-04-18 16:57:27 -07004808 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004809 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4810 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004811 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004812 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004813 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 mFrameCount = mInputBytes / mFrameSize;
4815 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4816
4817 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4818 {
4819 int channelCount;
4820 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4821 // stereo to mono post process as the resampler always outputs stereo.
4822 if (mChannelCount == 1 && mReqChannelCount == 2) {
4823 channelCount = 1;
4824 } else {
4825 channelCount = 2;
4826 }
4827 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4828 mResampler->setSampleRate(mSampleRate);
4829 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4830 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4831
4832 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4833 if (mChannelCount == 1 && mReqChannelCount == 1) {
4834 mFrameCount >>= 1;
4835 }
4836
4837 }
4838 mRsmpInIndex = mFrameCount;
4839}
4840
4841unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4842{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004843 Mutex::Autolock _l(mLock);
4844 if (initCheck() != NO_ERROR) {
4845 return 0;
4846 }
4847
Dima Zavin799a70e2011-04-18 16:57:27 -07004848 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849}
4850
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004851uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4852{
4853 Mutex::Autolock _l(mLock);
4854 uint32_t result = 0;
4855 if (getEffectChain_l(sessionId) != 0) {
4856 result = EFFECT_SESSION;
4857 }
4858
4859 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4860 result |= TRACK_SESSION;
4861 }
4862
4863 return result;
4864}
4865
Eric Laurent59bd0da2011-08-01 09:52:20 -07004866AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4867{
4868 Mutex::Autolock _l(mLock);
4869 return mTrack;
4870}
4871
Glenn Kastenaed850d2012-01-26 09:46:34 -08004872AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004873{
4874 Mutex::Autolock _l(mLock);
4875 return mInput;
4876}
4877
4878AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4879{
4880 Mutex::Autolock _l(mLock);
4881 AudioStreamIn *input = mInput;
4882 mInput = NULL;
4883 return input;
4884}
4885
4886// this method must always be called either with ThreadBase mLock held or inside the thread loop
4887audio_stream_t* AudioFlinger::RecordThread::stream()
4888{
4889 if (mInput == NULL) {
4890 return NULL;
4891 }
4892 return &mInput->stream->common;
4893}
4894
4895
Mathias Agopian65ab4712010-07-14 17:59:35 -07004896// ----------------------------------------------------------------------------
4897
4898int AudioFlinger::openOutput(uint32_t *pDevices,
4899 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004900 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004901 uint32_t *pChannels,
4902 uint32_t *pLatencyMs,
4903 uint32_t flags)
4904{
4905 status_t status;
4906 PlaybackThread *thread = NULL;
4907 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4908 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004909 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910 uint32_t channels = pChannels ? *pChannels : 0;
4911 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004912 audio_stream_out_t *outStream;
4913 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914
Steve Block3856b092011-10-20 11:56:00 +01004915 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004916 pDevices ? *pDevices : 0,
4917 samplingRate,
4918 format,
4919 channels,
4920 flags);
4921
4922 if (pDevices == NULL || *pDevices == 0) {
4923 return 0;
4924 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004925
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 Mutex::Autolock _l(mLock);
4927
Dima Zavin799a70e2011-04-18 16:57:27 -07004928 outHwDev = findSuitableHwDev_l(*pDevices);
4929 if (outHwDev == NULL)
4930 return 0;
4931
Glenn Kasten58f30212012-01-12 12:27:51 -08004932 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004933 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004934 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004935 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 samplingRate,
4937 format,
4938 channels,
4939 status);
4940
4941 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004942 if (outStream != NULL) {
4943 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004944 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004945
Dima Zavinfce7a472011-04-19 22:30:36 -07004946 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4947 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4948 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004950 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 } else {
4952 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004953 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954 }
4955 mPlaybackThreads.add(id, thread);
4956
Glenn Kastena0d68332012-01-27 16:47:15 -08004957 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4958 if (pFormat != NULL) *pFormat = format;
4959 if (pChannels != NULL) *pChannels = channels;
4960 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961
4962 // notify client processes of the new output creation
4963 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4964 return id;
4965 }
4966
4967 return 0;
4968}
4969
4970int AudioFlinger::openDuplicateOutput(int output1, int output2)
4971{
4972 Mutex::Autolock _l(mLock);
4973 MixerThread *thread1 = checkMixerThread_l(output1);
4974 MixerThread *thread2 = checkMixerThread_l(output2);
4975
4976 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004977 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004978 return 0;
4979 }
4980
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004981 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4983 thread->addOutputTrack(thread2);
4984 mPlaybackThreads.add(id, thread);
4985 // notify client processes of the new output creation
4986 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4987 return id;
4988}
4989
4990status_t AudioFlinger::closeOutput(int output)
4991{
4992 // keep strong reference on the playback thread so that
4993 // it is not destroyed while exit() is executed
4994 sp <PlaybackThread> thread;
4995 {
4996 Mutex::Autolock _l(mLock);
4997 thread = checkPlaybackThread_l(output);
4998 if (thread == NULL) {
4999 return BAD_VALUE;
5000 }
5001
Steve Block3856b092011-10-20 11:56:00 +01005002 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005004 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005006 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5008 dupThread->removeOutputTrack((MixerThread *)thread.get());
5009 }
5010 }
5011 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005012 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5014 mPlaybackThreads.removeItem(output);
5015 }
5016 thread->exit();
5017
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005019 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005020 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005021 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005022 out->hwDev->close_output_stream(out->hwDev, out->stream);
5023 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005024 }
5025 return NO_ERROR;
5026}
5027
5028status_t AudioFlinger::suspendOutput(int output)
5029{
5030 Mutex::Autolock _l(mLock);
5031 PlaybackThread *thread = checkPlaybackThread_l(output);
5032
5033 if (thread == NULL) {
5034 return BAD_VALUE;
5035 }
5036
Steve Block3856b092011-10-20 11:56:00 +01005037 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 thread->suspend();
5039
5040 return NO_ERROR;
5041}
5042
5043status_t AudioFlinger::restoreOutput(int output)
5044{
5045 Mutex::Autolock _l(mLock);
5046 PlaybackThread *thread = checkPlaybackThread_l(output);
5047
5048 if (thread == NULL) {
5049 return BAD_VALUE;
5050 }
5051
Steve Block3856b092011-10-20 11:56:00 +01005052 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005053
5054 thread->restore();
5055
5056 return NO_ERROR;
5057}
5058
5059int AudioFlinger::openInput(uint32_t *pDevices,
5060 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005061 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005063 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064{
5065 status_t status;
5066 RecordThread *thread = NULL;
5067 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005068 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 uint32_t channels = pChannels ? *pChannels : 0;
5070 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005071 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005073 audio_stream_in_t *inStream;
5074 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075
5076 if (pDevices == NULL || *pDevices == 0) {
5077 return 0;
5078 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005079
Mathias Agopian65ab4712010-07-14 17:59:35 -07005080 Mutex::Autolock _l(mLock);
5081
Dima Zavin799a70e2011-04-18 16:57:27 -07005082 inHwDev = findSuitableHwDev_l(*pDevices);
5083 if (inHwDev == NULL)
5084 return 0;
5085
Glenn Kasten58f30212012-01-12 12:27:51 -08005086 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005087 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005088 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005090 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005091 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005092 samplingRate,
5093 format,
5094 channels,
5095 acoustics,
5096 status);
5097
5098 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5099 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5100 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005101 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005102 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005104 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005105 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005106 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005107 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005108 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005109 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110 }
5111
Dima Zavin799a70e2011-04-18 16:57:27 -07005112 if (inStream != NULL) {
5113 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5114
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005115 int id = nextUniqueId();
5116 // Start record thread
5117 // RecorThread require both input and output device indication to forward to audio
5118 // pre processing modules
5119 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5120 thread = new RecordThread(this,
5121 input,
5122 reqSamplingRate,
5123 reqChannels,
5124 id,
5125 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005126 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005127 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005128 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5129 if (pFormat != NULL) *pFormat = format;
5130 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131
Dima Zavin799a70e2011-04-18 16:57:27 -07005132 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133
5134 // notify client processes of the new input creation
5135 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5136 return id;
5137 }
5138
5139 return 0;
5140}
5141
5142status_t AudioFlinger::closeInput(int input)
5143{
5144 // keep strong reference on the record thread so that
5145 // it is not destroyed while exit() is executed
5146 sp <RecordThread> thread;
5147 {
5148 Mutex::Autolock _l(mLock);
5149 thread = checkRecordThread_l(input);
5150 if (thread == NULL) {
5151 return BAD_VALUE;
5152 }
5153
Steve Block3856b092011-10-20 11:56:00 +01005154 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005155 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005156 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5157 mRecordThreads.removeItem(input);
5158 }
5159 thread->exit();
5160
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005161 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005162 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005163 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005164 in->hwDev->close_input_stream(in->hwDev, in->stream);
5165 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166
5167 return NO_ERROR;
5168}
5169
Glenn Kastenfff6d712012-01-12 16:38:12 -08005170status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171{
5172 Mutex::Autolock _l(mLock);
5173 MixerThread *dstThread = checkMixerThread_l(output);
5174 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005175 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176 return BAD_VALUE;
5177 }
5178
Steve Block3856b092011-10-20 11:56:00 +01005179 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5181
Eric Laurent9f6530f2011-08-30 10:18:54 -07005182 dstThread->setStreamValid(stream, true);
5183
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5185 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5186 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005187 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005189 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191 }
Eric Laurentde070132010-07-13 04:45:46 -07005192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005193
5194 return NO_ERROR;
5195}
5196
5197
5198int AudioFlinger::newAudioSessionId()
5199{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005200 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201}
5202
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005203void AudioFlinger::acquireAudioSessionId(int audioSession)
5204{
5205 Mutex::Autolock _l(mLock);
5206 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005207 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005208 int num = mAudioSessionRefs.size();
5209 for (int i = 0; i< num; i++) {
5210 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5211 if (ref->sessionid == audioSession && ref->pid == caller) {
5212 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005213 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005214 return;
5215 }
5216 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005217 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5218 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005219}
5220
5221void AudioFlinger::releaseAudioSessionId(int audioSession)
5222{
5223 Mutex::Autolock _l(mLock);
5224 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005225 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005226 int num = mAudioSessionRefs.size();
5227 for (int i = 0; i< num; i++) {
5228 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5229 if (ref->sessionid == audioSession && ref->pid == caller) {
5230 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005231 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005232 if (ref->cnt == 0) {
5233 mAudioSessionRefs.removeAt(i);
5234 delete ref;
5235 purgeStaleEffects_l();
5236 }
5237 return;
5238 }
5239 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005240 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005241}
5242
5243void AudioFlinger::purgeStaleEffects_l() {
5244
Steve Block3856b092011-10-20 11:56:00 +01005245 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005246
5247 Vector< sp<EffectChain> > chains;
5248
5249 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5250 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5251 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5252 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005253 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5254 chains.push(ec);
5255 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005256 }
5257 }
5258 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5259 sp<RecordThread> t = mRecordThreads.valueAt(i);
5260 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5261 sp<EffectChain> ec = t->mEffectChains[j];
5262 chains.push(ec);
5263 }
5264 }
5265
5266 for (size_t i = 0; i < chains.size(); i++) {
5267 sp<EffectChain> ec = chains[i];
5268 int sessionid = ec->sessionId();
5269 sp<ThreadBase> t = ec->mThread.promote();
5270 if (t == 0) {
5271 continue;
5272 }
5273 size_t numsessionrefs = mAudioSessionRefs.size();
5274 bool found = false;
5275 for (size_t k = 0; k < numsessionrefs; k++) {
5276 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5277 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005278 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005279 sessionid, ref->pid, ref->cnt);
5280 found = true;
5281 break;
5282 }
5283 }
5284 if (!found) {
5285 // remove all effects from the chain
5286 while (ec->mEffects.size()) {
5287 sp<EffectModule> effect = ec->mEffects[0];
5288 effect->unPin();
5289 Mutex::Autolock _l (t->mLock);
5290 t->removeEffect_l(effect);
5291 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5292 sp<EffectHandle> handle = effect->mHandles[j].promote();
5293 if (handle != 0) {
5294 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005295 if (handle->mHasControl && handle->mEnabled) {
5296 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5297 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005298 }
5299 }
5300 AudioSystem::unregisterEffect(effect->id());
5301 }
5302 }
5303 }
5304 return;
5305}
5306
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5308AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5309{
5310 PlaybackThread *thread = NULL;
5311 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5312 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5313 }
5314 return thread;
5315}
5316
5317// checkMixerThread_l() must be called with AudioFlinger::mLock held
5318AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5319{
5320 PlaybackThread *thread = checkPlaybackThread_l(output);
5321 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005322 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323 thread = NULL;
5324 }
5325 }
5326 return (MixerThread *)thread;
5327}
5328
5329// checkRecordThread_l() must be called with AudioFlinger::mLock held
5330AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5331{
5332 RecordThread *thread = NULL;
5333 if (mRecordThreads.indexOfKey(input) >= 0) {
5334 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5335 }
5336 return thread;
5337}
5338
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005339uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005341 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342}
5343
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005344AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5345{
5346 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5347 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005348 AudioStreamOut *output = thread->getOutput();
5349 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005350 return thread;
5351 }
5352 }
5353 return NULL;
5354}
5355
5356uint32_t AudioFlinger::primaryOutputDevice_l()
5357{
5358 PlaybackThread *thread = primaryPlaybackThread_l();
5359
5360 if (thread == NULL) {
5361 return 0;
5362 }
5363
5364 return thread->device();
5365}
5366
5367
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368// ----------------------------------------------------------------------------
5369// Effect management
5370// ----------------------------------------------------------------------------
5371
5372
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5374{
5375 Mutex::Autolock _l(mLock);
5376 return EffectQueryNumberEffects(numEffects);
5377}
5378
5379status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5380{
5381 Mutex::Autolock _l(mLock);
5382 return EffectQueryEffect(index, descriptor);
5383}
5384
5385status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5386{
5387 Mutex::Autolock _l(mLock);
5388 return EffectGetDescriptor(pUuid, descriptor);
5389}
5390
5391
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5393 effect_descriptor_t *pDesc,
5394 const sp<IEffectClient>& effectClient,
5395 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005396 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397 int sessionId,
5398 status_t *status,
5399 int *id,
5400 int *enabled)
5401{
5402 status_t lStatus = NO_ERROR;
5403 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 effect_descriptor_t desc;
5405 sp<Client> client;
5406 wp<Client> wclient;
5407
Steve Block3856b092011-10-20 11:56:00 +01005408 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005409 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410
5411 if (pDesc == NULL) {
5412 lStatus = BAD_VALUE;
5413 goto Exit;
5414 }
5415
Eric Laurent84e9a102010-09-23 16:10:16 -07005416 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005417 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005418 lStatus = PERMISSION_DENIED;
5419 goto Exit;
5420 }
5421
Dima Zavinfce7a472011-04-19 22:30:36 -07005422 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005423 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005424 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005425 lStatus = PERMISSION_DENIED;
5426 goto Exit;
5427 }
5428
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005429 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005430 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005431 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005432 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005433 lStatus = BAD_VALUE;
5434 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005435 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005436 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005437 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005438 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005439 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005440 }
5441 }
5442
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 {
5444 Mutex::Autolock _l(mLock);
5445
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446
5447 if (!EffectIsNullUuid(&pDesc->uuid)) {
5448 // if uuid is specified, request effect descriptor
5449 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5450 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005451 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005452 goto Exit;
5453 }
5454 } else {
5455 // if uuid is not specified, look for an available implementation
5456 // of the required type in effect factory
5457 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005458 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 lStatus = BAD_VALUE;
5460 goto Exit;
5461 }
5462 uint32_t numEffects = 0;
5463 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005464 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 bool found = false;
5466
5467 lStatus = EffectQueryNumberEffects(&numEffects);
5468 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005469 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470 goto Exit;
5471 }
5472 for (uint32_t i = 0; i < numEffects; i++) {
5473 lStatus = EffectQueryEffect(i, &desc);
5474 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005475 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005476 continue;
5477 }
5478 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5479 // If matching type found save effect descriptor. If the session is
5480 // 0 and the effect is not auxiliary, continue enumeration in case
5481 // an auxiliary version of this effect type is available
5482 found = true;
5483 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005484 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005485 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5486 break;
5487 }
5488 }
5489 }
5490 if (!found) {
5491 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005492 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 goto Exit;
5494 }
5495 // For same effect type, chose auxiliary version over insert version if
5496 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005497 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5499 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5500 }
5501 }
5502
5503 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005504 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5506 lStatus = INVALID_OPERATION;
5507 goto Exit;
5508 }
5509
Eric Laurent59255e42011-07-27 19:49:51 -07005510 // check recording permission for visualizer
5511 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5512 !recordingAllowed()) {
5513 lStatus = PERMISSION_DENIED;
5514 goto Exit;
5515 }
5516
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517 // return effect descriptor
5518 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5519
5520 // If output is not specified try to find a matching audio session ID in one of the
5521 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005522 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5523 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005524 // Note: io is never 0 when creating an effect on an input
5525 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005526 // look for the thread where the specified audio session is present
5527 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5528 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005529 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005530 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005531 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005533 if (io == 0) {
5534 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5535 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5536 io = mRecordThreads.keyAt(i);
5537 break;
5538 }
5539 }
5540 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005541 // If no output thread contains the requested session ID, default to
5542 // first output. The effect chain will be moved to the correct output
5543 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005544 if (io == 0 && mPlaybackThreads.size()) {
5545 io = mPlaybackThreads.keyAt(0);
5546 }
Steve Block3856b092011-10-20 11:56:00 +01005547 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005548 }
5549 ThreadBase *thread = checkRecordThread_l(io);
5550 if (thread == NULL) {
5551 thread = checkPlaybackThread_l(io);
5552 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005553 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005554 lStatus = BAD_VALUE;
5555 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005556 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005558
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 wclient = mClients.valueFor(pid);
5560
5561 if (wclient != NULL) {
5562 client = wclient.promote();
5563 } else {
5564 client = new Client(this, pid);
5565 mClients.add(pid, client);
5566 }
5567
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005568 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005569 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5570 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 if (handle != 0 && id != NULL) {
5572 *id = handle->id();
5573 }
5574 }
5575
5576Exit:
5577 if(status) {
5578 *status = lStatus;
5579 }
5580 return handle;
5581}
5582
Eric Laurent59255e42011-07-27 19:49:51 -07005583status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005584{
Steve Block3856b092011-10-20 11:56:00 +01005585 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005586 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005587 Mutex::Autolock _l(mLock);
5588 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005589 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005590 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 }
Eric Laurentde070132010-07-13 04:45:46 -07005592 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5593 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005594 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005595 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005596 }
Eric Laurentde070132010-07-13 04:45:46 -07005597 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5598 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005599 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005600 return BAD_VALUE;
5601 }
5602
5603 Mutex::Autolock _dl(dstThread->mLock);
5604 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005605 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005606
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607 return NO_ERROR;
5608}
5609
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005610// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005611status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005612 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005613 AudioFlinger::PlaybackThread *dstThread,
5614 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005615{
Steve Block3856b092011-10-20 11:56:00 +01005616 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005617 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005618
Eric Laurent59255e42011-07-27 19:49:51 -07005619 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005620 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005621 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005622 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005623 return INVALID_OPERATION;
5624 }
5625
Eric Laurent39e94f82010-07-28 01:32:47 -07005626 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005627 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005628 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005629 // removed.
5630 srcThread->removeEffectChain_l(chain);
5631
5632 // transfer all effects one by one so that new effect chain is created on new thread with
5633 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005634 int dstOutput = dstThread->id();
5635 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005636 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005637 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5638 while (effect != 0) {
5639 srcThread->removeEffect_l(effect);
5640 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005641 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5642 if (effect->state() == EffectModule::ACTIVE ||
5643 effect->state() == EffectModule::STOPPING) {
5644 effect->start();
5645 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005646 // if the move request is not received from audio policy manager, the effect must be
5647 // re-registered with the new strategy and output
5648 if (dstChain == 0) {
5649 dstChain = effect->chain().promote();
5650 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005651 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005652 srcThread->addEffect_l(effect);
5653 return NO_INIT;
5654 }
5655 strategy = dstChain->strategy();
5656 }
5657 if (reRegister) {
5658 AudioSystem::unregisterEffect(effect->id());
5659 AudioSystem::registerEffect(&effect->desc(),
5660 dstOutput,
5661 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005662 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005663 effect->id());
5664 }
Eric Laurentde070132010-07-13 04:45:46 -07005665 effect = chain->getEffectFromId_l(0);
5666 }
5667
5668 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669}
5670
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005671
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005673sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 const sp<AudioFlinger::Client>& client,
5675 const sp<IEffectClient>& effectClient,
5676 int32_t priority,
5677 int sessionId,
5678 effect_descriptor_t *desc,
5679 int *enabled,
5680 status_t *status
5681 )
5682{
5683 sp<EffectModule> effect;
5684 sp<EffectHandle> handle;
5685 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005687 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 bool effectCreated = false;
5689 bool effectRegistered = false;
5690
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005691 lStatus = initCheck();
5692 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005693 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 goto Exit;
5695 }
5696
5697 // Do not allow effects with session ID 0 on direct output or duplicating threads
5698 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005699 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005700 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005701 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702 lStatus = BAD_VALUE;
5703 goto Exit;
5704 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005705 // Only Pre processor effects are allowed on input threads and only on input threads
5706 if ((mType == RECORD &&
5707 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5708 (mType != RECORD &&
5709 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005710 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005711 desc->name, desc->flags, mType);
5712 lStatus = BAD_VALUE;
5713 goto Exit;
5714 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715
Steve Block3856b092011-10-20 11:56:00 +01005716 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717
5718 { // scope for mLock
5719 Mutex::Autolock _l(mLock);
5720
5721 // check for existing effect chain with the requested audio session
5722 chain = getEffectChain_l(sessionId);
5723 if (chain == 0) {
5724 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005725 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 chain = new EffectChain(this, sessionId);
5727 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005728 chain->setStrategy(getStrategyForSession_l(sessionId));
5729 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005731 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 }
5733
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005734 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735
5736 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005737 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005739 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 if (lStatus != NO_ERROR) {
5741 goto Exit;
5742 }
5743 effectRegistered = true;
5744 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005745 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 lStatus = effect->status();
5747 if (lStatus != NO_ERROR) {
5748 goto Exit;
5749 }
Eric Laurentcab11242010-07-15 12:50:15 -07005750 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751 if (lStatus != NO_ERROR) {
5752 goto Exit;
5753 }
5754 effectCreated = true;
5755
5756 effect->setDevice(mDevice);
5757 effect->setMode(mAudioFlinger->getMode());
5758 }
5759 // create effect handle and connect it to effect module
5760 handle = new EffectHandle(effect, client, effectClient, priority);
5761 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005762 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763 *enabled = (int)effect->isEnabled();
5764 }
5765 }
5766
5767Exit:
5768 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005769 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005771 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772 }
5773 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005774 AudioSystem::unregisterEffect(effect->id());
5775 }
5776 if (chainCreated) {
5777 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778 }
5779 handle.clear();
5780 }
5781
5782 if(status) {
5783 *status = lStatus;
5784 }
5785 return handle;
5786}
5787
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005788sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5789{
5790 sp<EffectModule> effect;
5791
5792 sp<EffectChain> chain = getEffectChain_l(sessionId);
5793 if (chain != 0) {
5794 effect = chain->getEffectFromId_l(effectId);
5795 }
5796 return effect;
5797}
5798
Eric Laurentde070132010-07-13 04:45:46 -07005799// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5800// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005801status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005802{
5803 // check for existing effect chain with the requested audio session
5804 int sessionId = effect->sessionId();
5805 sp<EffectChain> chain = getEffectChain_l(sessionId);
5806 bool chainCreated = false;
5807
5808 if (chain == 0) {
5809 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005810 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005811 chain = new EffectChain(this, sessionId);
5812 addEffectChain_l(chain);
5813 chain->setStrategy(getStrategyForSession_l(sessionId));
5814 chainCreated = true;
5815 }
Steve Block3856b092011-10-20 11:56:00 +01005816 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005817
5818 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005819 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005820 this, effect->desc().name, chain.get());
5821 return BAD_VALUE;
5822 }
5823
5824 status_t status = chain->addEffect_l(effect);
5825 if (status != NO_ERROR) {
5826 if (chainCreated) {
5827 removeEffectChain_l(chain);
5828 }
5829 return status;
5830 }
5831
5832 effect->setDevice(mDevice);
5833 effect->setMode(mAudioFlinger->getMode());
5834 return NO_ERROR;
5835}
5836
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005837void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005838
Steve Block3856b092011-10-20 11:56:00 +01005839 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005841 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5842 detachAuxEffect_l(effect->id());
5843 }
5844
5845 sp<EffectChain> chain = effect->chain().promote();
5846 if (chain != 0) {
5847 // remove effect chain if removing last effect
5848 if (chain->removeEffect_l(effect) == 0) {
5849 removeEffectChain_l(chain);
5850 }
5851 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005852 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005853 }
5854}
5855
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005856void AudioFlinger::ThreadBase::lockEffectChains_l(
5857 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5858{
5859 effectChains = mEffectChains;
5860 for (size_t i = 0; i < mEffectChains.size(); i++) {
5861 mEffectChains[i]->lock();
5862 }
5863}
5864
5865void AudioFlinger::ThreadBase::unlockEffectChains(
5866 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5867{
5868 for (size_t i = 0; i < effectChains.size(); i++) {
5869 effectChains[i]->unlock();
5870 }
5871}
5872
5873sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5874{
5875 Mutex::Autolock _l(mLock);
5876 return getEffectChain_l(sessionId);
5877}
5878
5879sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5880{
5881 sp<EffectChain> chain;
5882
5883 size_t size = mEffectChains.size();
5884 for (size_t i = 0; i < size; i++) {
5885 if (mEffectChains[i]->sessionId() == sessionId) {
5886 chain = mEffectChains[i];
5887 break;
5888 }
5889 }
5890 return chain;
5891}
5892
Glenn Kastenf78aee72012-01-04 11:00:47 -08005893void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005894{
5895 Mutex::Autolock _l(mLock);
5896 size_t size = mEffectChains.size();
5897 for (size_t i = 0; i < size; i++) {
5898 mEffectChains[i]->setMode_l(mode);
5899 }
5900}
5901
5902void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005903 const wp<EffectHandle>& handle,
5904 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005905
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005907 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 // delete the effect module if removing last handle on it
5909 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005910 if (!effect->isPinned() || unpiniflast) {
5911 removeEffect_l(effect);
5912 AudioSystem::unregisterEffect(effect->id());
5913 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 }
5915}
5916
5917status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5918{
5919 int session = chain->sessionId();
5920 int16_t *buffer = mMixBuffer;
5921 bool ownsBuffer = false;
5922
Steve Block3856b092011-10-20 11:56:00 +01005923 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 if (session > 0) {
5925 // Only one effect chain can be present in direct output thread and it uses
5926 // the mix buffer as input
5927 if (mType != DIRECT) {
5928 size_t numSamples = mFrameCount * mChannelCount;
5929 buffer = new int16_t[numSamples];
5930 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005931 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 ownsBuffer = true;
5933 }
5934
5935 // Attach all tracks with same session ID to this chain.
5936 for (size_t i = 0; i < mTracks.size(); ++i) {
5937 sp<Track> track = mTracks[i];
5938 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005939 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005941 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 }
5943 }
5944
5945 // indicate all active tracks in the chain
5946 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5947 sp<Track> track = mActiveTracks[i].promote();
5948 if (track == 0) continue;
5949 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005950 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005951 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 }
5953 }
5954 }
5955
5956 chain->setInBuffer(buffer, ownsBuffer);
5957 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005958 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005959 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005960 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5961 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005963 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5964 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005965 // Effect chain for other sessions are inserted at beginning of effect
5966 // chains list to be processed before output mix effects. Relative order between other
5967 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 size_t size = mEffectChains.size();
5969 size_t i = 0;
5970 for (i = 0; i < size; i++) {
5971 if (mEffectChains[i]->sessionId() < session) break;
5972 }
5973 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005974 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975
5976 return NO_ERROR;
5977}
5978
5979size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5980{
5981 int session = chain->sessionId();
5982
Steve Block3856b092011-10-20 11:56:00 +01005983 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984
5985 for (size_t i = 0; i < mEffectChains.size(); i++) {
5986 if (chain == mEffectChains[i]) {
5987 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005988 // detach all active tracks from the chain
5989 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5990 sp<Track> track = mActiveTracks[i].promote();
5991 if (track == 0) continue;
5992 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005993 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005994 chain.get(), session);
5995 chain->decActiveTrackCnt();
5996 }
5997 }
5998
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 // detach all tracks with same session ID from this chain
6000 for (size_t i = 0; i < mTracks.size(); ++i) {
6001 sp<Track> track = mTracks[i];
6002 if (session == track->sessionId()) {
6003 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006004 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 }
6006 }
Eric Laurentde070132010-07-13 04:45:46 -07006007 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008 }
6009 }
6010 return mEffectChains.size();
6011}
6012
Eric Laurentde070132010-07-13 04:45:46 -07006013status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6014 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015{
6016 Mutex::Autolock _l(mLock);
6017 return attachAuxEffect_l(track, EffectId);
6018}
6019
Eric Laurentde070132010-07-13 04:45:46 -07006020status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6021 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006022{
6023 status_t status = NO_ERROR;
6024
6025 if (EffectId == 0) {
6026 track->setAuxBuffer(0, NULL);
6027 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006028 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6029 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 if (effect != 0) {
6031 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6032 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6033 } else {
6034 status = INVALID_OPERATION;
6035 }
6036 } else {
6037 status = BAD_VALUE;
6038 }
6039 }
6040 return status;
6041}
6042
6043void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6044{
6045 for (size_t i = 0; i < mTracks.size(); ++i) {
6046 sp<Track> track = mTracks[i];
6047 if (track->auxEffectId() == effectId) {
6048 attachAuxEffect_l(track, 0);
6049 }
6050 }
6051}
6052
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006053status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6054{
6055 // only one chain per input thread
6056 if (mEffectChains.size() != 0) {
6057 return INVALID_OPERATION;
6058 }
Steve Block3856b092011-10-20 11:56:00 +01006059 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006060
6061 chain->setInBuffer(NULL);
6062 chain->setOutBuffer(NULL);
6063
Eric Laurent59255e42011-07-27 19:49:51 -07006064 checkSuspendOnAddEffectChain_l(chain);
6065
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006066 mEffectChains.add(chain);
6067
6068 return NO_ERROR;
6069}
6070
6071size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6072{
Steve Block3856b092011-10-20 11:56:00 +01006073 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006074 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006075 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6076 chain.get(), mEffectChains.size(), this);
6077 if (mEffectChains.size() == 1) {
6078 mEffectChains.removeAt(0);
6079 }
6080 return 0;
6081}
6082
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083// ----------------------------------------------------------------------------
6084// EffectModule implementation
6085// ----------------------------------------------------------------------------
6086
6087#undef LOG_TAG
6088#define LOG_TAG "AudioFlinger::EffectModule"
6089
6090AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6091 const wp<AudioFlinger::EffectChain>& chain,
6092 effect_descriptor_t *desc,
6093 int id,
6094 int sessionId)
6095 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006096 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097{
Steve Block3856b092011-10-20 11:56:00 +01006098 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 int lStatus;
6100 sp<ThreadBase> thread = mThread.promote();
6101 if (thread == 0) {
6102 return;
6103 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104
6105 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6106
6107 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006108 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109
6110 if (mStatus != NO_ERROR) {
6111 return;
6112 }
6113 lStatus = init();
6114 if (lStatus < 0) {
6115 mStatus = lStatus;
6116 goto Error;
6117 }
6118
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006119 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6120 mPinned = true;
6121 }
Steve Block3856b092011-10-20 11:56:00 +01006122 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 return;
6124Error:
6125 EffectRelease(mEffectInterface);
6126 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006127 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128}
6129
6130AudioFlinger::EffectModule::~EffectModule()
6131{
Steve Block3856b092011-10-20 11:56:00 +01006132 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006134 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6135 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6136 sp<ThreadBase> thread = mThread.promote();
6137 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006138 audio_stream_t *stream = thread->stream();
6139 if (stream != NULL) {
6140 stream->remove_audio_effect(stream, mEffectInterface);
6141 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006142 }
6143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 // release effect engine
6145 EffectRelease(mEffectInterface);
6146 }
6147}
6148
Glenn Kasten435dbe62012-01-30 10:15:48 -08006149status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150{
6151 status_t status;
6152
6153 Mutex::Autolock _l(mLock);
6154 // First handle in mHandles has highest priority and controls the effect module
6155 int priority = handle->priority();
6156 size_t size = mHandles.size();
6157 sp<EffectHandle> h;
6158 size_t i;
6159 for (i = 0; i < size; i++) {
6160 h = mHandles[i].promote();
6161 if (h == 0) continue;
6162 if (h->priority() <= priority) break;
6163 }
6164 // if inserted in first place, move effect control from previous owner to this handle
6165 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006166 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006167 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006168 enabled = h->enabled();
6169 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 }
Eric Laurent59255e42011-07-27 19:49:51 -07006171 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 status = NO_ERROR;
6173 } else {
6174 status = ALREADY_EXISTS;
6175 }
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 mHandles.insertAt(handle, i);
6178 return status;
6179}
6180
6181size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6182{
6183 Mutex::Autolock _l(mLock);
6184 size_t size = mHandles.size();
6185 size_t i;
6186 for (i = 0; i < size; i++) {
6187 if (mHandles[i] == handle) break;
6188 }
6189 if (i == size) {
6190 return size;
6191 }
Steve Block3856b092011-10-20 11:56:00 +01006192 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006193
6194 bool enabled = false;
6195 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006196 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006197 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006198 enabled = hdl->enabled();
6199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 mHandles.removeAt(i);
6201 size = mHandles.size();
6202 // if removed from first place, move effect control from this handle to next in line
6203 if (i == 0 && size != 0) {
6204 sp<EffectHandle> h = mHandles[0].promote();
6205 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006206 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 }
6208 }
6209
Eric Laurentec437d82011-07-26 20:54:46 -07006210 // Prevent calls to process() and other functions on effect interface from now on.
6211 // The effect engine will be released by the destructor when the last strong reference on
6212 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006213 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006214 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006215 }
6216
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 return size;
6218}
6219
Eric Laurent59255e42011-07-27 19:49:51 -07006220sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6221{
6222 Mutex::Autolock _l(mLock);
6223 sp<EffectHandle> handle;
6224 if (mHandles.size() != 0) {
6225 handle = mHandles[0].promote();
6226 }
6227 return handle;
6228}
6229
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006230void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006231{
Steve Block3856b092011-10-20 11:56:00 +01006232 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 // keep a strong reference on this EffectModule to avoid calling the
6234 // destructor before we exit
6235 sp<EffectModule> keep(this);
6236 {
6237 sp<ThreadBase> thread = mThread.promote();
6238 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006239 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 }
6241 }
6242}
6243
6244void AudioFlinger::EffectModule::updateState() {
6245 Mutex::Autolock _l(mLock);
6246
6247 switch (mState) {
6248 case RESTART:
6249 reset_l();
6250 // FALL THROUGH
6251
6252 case STARTING:
6253 // clear auxiliary effect input buffer for next accumulation
6254 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6255 memset(mConfig.inputCfg.buffer.raw,
6256 0,
6257 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6258 }
6259 start_l();
6260 mState = ACTIVE;
6261 break;
6262 case STOPPING:
6263 stop_l();
6264 mDisableWaitCnt = mMaxDisableWaitCnt;
6265 mState = STOPPED;
6266 break;
6267 case STOPPED:
6268 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6269 // turn off sequence.
6270 if (--mDisableWaitCnt == 0) {
6271 reset_l();
6272 mState = IDLE;
6273 }
6274 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006275 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 break;
6277 }
6278}
6279
6280void AudioFlinger::EffectModule::process()
6281{
6282 Mutex::Autolock _l(mLock);
6283
Eric Laurentec437d82011-07-26 20:54:46 -07006284 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 mConfig.inputCfg.buffer.raw == NULL ||
6286 mConfig.outputCfg.buffer.raw == NULL) {
6287 return;
6288 }
6289
Eric Laurent8f45bd72010-08-31 13:50:07 -07006290 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6292 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006293 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006295 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 }
6297
6298 // do the actual processing in the effect engine
6299 int ret = (*mEffectInterface)->process(mEffectInterface,
6300 &mConfig.inputCfg.buffer,
6301 &mConfig.outputCfg.buffer);
6302
6303 // force transition to IDLE state when engine is ready
6304 if (mState == STOPPED && ret == -ENODATA) {
6305 mDisableWaitCnt = 1;
6306 }
6307
6308 // clear auxiliary effect input buffer for next accumulation
6309 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006310 memset(mConfig.inputCfg.buffer.raw, 0,
6311 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 }
6313 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006314 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6315 // If an insert effect is idle and input buffer is different from output buffer,
6316 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006317 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006318 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006319 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6320 int16_t *in = mConfig.inputCfg.buffer.s16;
6321 int16_t *out = mConfig.outputCfg.buffer.s16;
6322 for (size_t i = 0; i < frameCnt; i++) {
6323 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 }
6326 }
6327}
6328
6329void AudioFlinger::EffectModule::reset_l()
6330{
6331 if (mEffectInterface == NULL) {
6332 return;
6333 }
6334 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6335}
6336
6337status_t AudioFlinger::EffectModule::configure()
6338{
6339 uint32_t channels;
6340 if (mEffectInterface == NULL) {
6341 return NO_INIT;
6342 }
6343
6344 sp<ThreadBase> thread = mThread.promote();
6345 if (thread == 0) {
6346 return DEAD_OBJECT;
6347 }
6348
6349 // TODO: handle configuration of effects replacing track process
6350 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006351 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006353 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354 }
6355
6356 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006357 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006358 } else {
6359 mConfig.inputCfg.channels = channels;
6360 }
6361 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006362 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6363 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 mConfig.inputCfg.samplingRate = thread->sampleRate();
6365 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6366 mConfig.inputCfg.bufferProvider.cookie = NULL;
6367 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6368 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6369 mConfig.outputCfg.bufferProvider.cookie = NULL;
6370 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6371 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6372 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6373 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006374 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006375 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 // - in other sessions:
6377 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6378 // other effect: overwrites output buffer: input buffer == output buffer
6379 // Auxiliary effect:
6380 // accumulates in output buffer: input buffer != output buffer
6381 // Therefore: accumulate <=> input buffer != output buffer
6382 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6383 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6384 } else {
6385 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6386 }
6387 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6388 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6389 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6390 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6391
Steve Block3856b092011-10-20 11:56:00 +01006392 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006393 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6394
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006396 uint32_t size = sizeof(int);
6397 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006398 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006399 sizeof(effect_config_t),
6400 &mConfig,
6401 &size,
6402 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 if (status == 0) {
6404 status = cmdStatus;
6405 }
6406
6407 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6408 (1000 * mConfig.outputCfg.buffer.frameCount);
6409
6410 return status;
6411}
6412
6413status_t AudioFlinger::EffectModule::init()
6414{
6415 Mutex::Autolock _l(mLock);
6416 if (mEffectInterface == NULL) {
6417 return NO_INIT;
6418 }
6419 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006420 uint32_t size = sizeof(status_t);
6421 status_t status = (*mEffectInterface)->command(mEffectInterface,
6422 EFFECT_CMD_INIT,
6423 0,
6424 NULL,
6425 &size,
6426 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427 if (status == 0) {
6428 status = cmdStatus;
6429 }
6430 return status;
6431}
6432
Eric Laurentec35a142011-10-05 17:42:25 -07006433status_t AudioFlinger::EffectModule::start()
6434{
6435 Mutex::Autolock _l(mLock);
6436 return start_l();
6437}
6438
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439status_t AudioFlinger::EffectModule::start_l()
6440{
6441 if (mEffectInterface == NULL) {
6442 return NO_INIT;
6443 }
6444 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006445 uint32_t size = sizeof(status_t);
6446 status_t status = (*mEffectInterface)->command(mEffectInterface,
6447 EFFECT_CMD_ENABLE,
6448 0,
6449 NULL,
6450 &size,
6451 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 if (status == 0) {
6453 status = cmdStatus;
6454 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006455 if (status == 0 &&
6456 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6457 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6458 sp<ThreadBase> thread = mThread.promote();
6459 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006460 audio_stream_t *stream = thread->stream();
6461 if (stream != NULL) {
6462 stream->add_audio_effect(stream, mEffectInterface);
6463 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006464 }
6465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006466 return status;
6467}
6468
Eric Laurentec437d82011-07-26 20:54:46 -07006469status_t AudioFlinger::EffectModule::stop()
6470{
6471 Mutex::Autolock _l(mLock);
6472 return stop_l();
6473}
6474
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475status_t AudioFlinger::EffectModule::stop_l()
6476{
6477 if (mEffectInterface == NULL) {
6478 return NO_INIT;
6479 }
6480 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006481 uint32_t size = sizeof(status_t);
6482 status_t status = (*mEffectInterface)->command(mEffectInterface,
6483 EFFECT_CMD_DISABLE,
6484 0,
6485 NULL,
6486 &size,
6487 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 if (status == 0) {
6489 status = cmdStatus;
6490 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006491 if (status == 0 &&
6492 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6493 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6494 sp<ThreadBase> thread = mThread.promote();
6495 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006496 audio_stream_t *stream = thread->stream();
6497 if (stream != NULL) {
6498 stream->remove_audio_effect(stream, mEffectInterface);
6499 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006500 }
6501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 return status;
6503}
6504
Eric Laurent25f43952010-07-28 05:40:18 -07006505status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6506 uint32_t cmdSize,
6507 void *pCmdData,
6508 uint32_t *replySize,
6509 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006510{
6511 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006512// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513
Eric Laurentec437d82011-07-26 20:54:46 -07006514 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 return NO_INIT;
6516 }
Eric Laurent25f43952010-07-28 05:40:18 -07006517 status_t status = (*mEffectInterface)->command(mEffectInterface,
6518 cmdCode,
6519 cmdSize,
6520 pCmdData,
6521 replySize,
6522 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006524 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 for (size_t i = 1; i < mHandles.size(); i++) {
6526 sp<EffectHandle> h = mHandles[i].promote();
6527 if (h != 0) {
6528 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6529 }
6530 }
6531 }
6532 return status;
6533}
6534
6535status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6536{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006537
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006539 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540
6541 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006542 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6543 if (enabled && status != NO_ERROR) {
6544 return status;
6545 }
6546
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 switch (mState) {
6548 // going from disabled to enabled
6549 case IDLE:
6550 mState = STARTING;
6551 break;
6552 case STOPPED:
6553 mState = RESTART;
6554 break;
6555 case STOPPING:
6556 mState = ACTIVE;
6557 break;
6558
6559 // going from enabled to disabled
6560 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006561 mState = STOPPED;
6562 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563 case STARTING:
6564 mState = IDLE;
6565 break;
6566 case ACTIVE:
6567 mState = STOPPING;
6568 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006569 case DESTROYED:
6570 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571 }
6572 for (size_t i = 1; i < mHandles.size(); i++) {
6573 sp<EffectHandle> h = mHandles[i].promote();
6574 if (h != 0) {
6575 h->setEnabled(enabled);
6576 }
6577 }
6578 }
6579 return NO_ERROR;
6580}
6581
Glenn Kastenc59c0042012-02-02 14:06:11 -08006582bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583{
6584 switch (mState) {
6585 case RESTART:
6586 case STARTING:
6587 case ACTIVE:
6588 return true;
6589 case IDLE:
6590 case STOPPING:
6591 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006592 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593 default:
6594 return false;
6595 }
6596}
6597
Glenn Kastenc59c0042012-02-02 14:06:11 -08006598bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006599{
6600 switch (mState) {
6601 case RESTART:
6602 case ACTIVE:
6603 case STOPPING:
6604 case STOPPED:
6605 return true;
6606 case IDLE:
6607 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006608 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006609 default:
6610 return false;
6611 }
6612}
6613
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6615{
6616 Mutex::Autolock _l(mLock);
6617 status_t status = NO_ERROR;
6618
6619 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6620 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006621 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006622 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6623 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624 status_t cmdStatus;
6625 uint32_t volume[2];
6626 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006627 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 volume[0] = *left;
6629 volume[1] = *right;
6630 if (controller) {
6631 pVolume = volume;
6632 }
Eric Laurent25f43952010-07-28 05:40:18 -07006633 status = (*mEffectInterface)->command(mEffectInterface,
6634 EFFECT_CMD_SET_VOLUME,
6635 size,
6636 volume,
6637 &size,
6638 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6640 *left = volume[0];
6641 *right = volume[1];
6642 }
6643 }
6644 return status;
6645}
6646
6647status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6648{
6649 Mutex::Autolock _l(mLock);
6650 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006651 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6652 // audio pre processing modules on RecordThread can receive both output and
6653 // input device indication in the same call
6654 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6655 if (dev) {
6656 status_t cmdStatus;
6657 uint32_t size = sizeof(status_t);
6658
6659 status = (*mEffectInterface)->command(mEffectInterface,
6660 EFFECT_CMD_SET_DEVICE,
6661 sizeof(uint32_t),
6662 &dev,
6663 &size,
6664 &cmdStatus);
6665 if (status == NO_ERROR) {
6666 status = cmdStatus;
6667 }
6668 }
6669 dev = device & AUDIO_DEVICE_IN_ALL;
6670 if (dev) {
6671 status_t cmdStatus;
6672 uint32_t size = sizeof(status_t);
6673
6674 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6675 EFFECT_CMD_SET_INPUT_DEVICE,
6676 sizeof(uint32_t),
6677 &dev,
6678 &size,
6679 &cmdStatus);
6680 if (status2 == NO_ERROR) {
6681 status2 = cmdStatus;
6682 }
6683 if (status == NO_ERROR) {
6684 status = status2;
6685 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006686 }
6687 }
6688 return status;
6689}
6690
Glenn Kastenf78aee72012-01-04 11:00:47 -08006691status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006692{
6693 Mutex::Autolock _l(mLock);
6694 status_t status = NO_ERROR;
6695 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006697 uint32_t size = sizeof(status_t);
6698 status = (*mEffectInterface)->command(mEffectInterface,
6699 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006700 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006701 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006702 &size,
6703 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006704 if (status == NO_ERROR) {
6705 status = cmdStatus;
6706 }
6707 }
6708 return status;
6709}
6710
Eric Laurent59255e42011-07-27 19:49:51 -07006711void AudioFlinger::EffectModule::setSuspended(bool suspended)
6712{
6713 Mutex::Autolock _l(mLock);
6714 mSuspended = suspended;
6715}
Glenn Kastena3a85482012-01-04 11:01:11 -08006716
6717bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006718{
6719 Mutex::Autolock _l(mLock);
6720 return mSuspended;
6721}
6722
Mathias Agopian65ab4712010-07-14 17:59:35 -07006723status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6724{
6725 const size_t SIZE = 256;
6726 char buffer[SIZE];
6727 String8 result;
6728
6729 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6730 result.append(buffer);
6731
6732 bool locked = tryLock(mLock);
6733 // failed to lock - AudioFlinger is probably deadlocked
6734 if (!locked) {
6735 result.append("\t\tCould not lock Fx mutex:\n");
6736 }
6737
6738 result.append("\t\tSession Status State Engine:\n");
6739 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6740 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6741 result.append(buffer);
6742
6743 result.append("\t\tDescriptor:\n");
6744 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6745 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6746 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6747 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6748 result.append(buffer);
6749 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6750 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6751 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6752 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6753 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006754 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 mDescriptor.apiVersion,
6756 mDescriptor.flags);
6757 result.append(buffer);
6758 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6759 mDescriptor.name);
6760 result.append(buffer);
6761 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6762 mDescriptor.implementor);
6763 result.append(buffer);
6764
6765 result.append("\t\t- Input configuration:\n");
6766 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6767 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6768 (uint32_t)mConfig.inputCfg.buffer.raw,
6769 mConfig.inputCfg.buffer.frameCount,
6770 mConfig.inputCfg.samplingRate,
6771 mConfig.inputCfg.channels,
6772 mConfig.inputCfg.format);
6773 result.append(buffer);
6774
6775 result.append("\t\t- Output configuration:\n");
6776 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6777 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6778 (uint32_t)mConfig.outputCfg.buffer.raw,
6779 mConfig.outputCfg.buffer.frameCount,
6780 mConfig.outputCfg.samplingRate,
6781 mConfig.outputCfg.channels,
6782 mConfig.outputCfg.format);
6783 result.append(buffer);
6784
6785 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6786 result.append(buffer);
6787 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6788 for (size_t i = 0; i < mHandles.size(); ++i) {
6789 sp<EffectHandle> handle = mHandles[i].promote();
6790 if (handle != 0) {
6791 handle->dump(buffer, SIZE);
6792 result.append(buffer);
6793 }
6794 }
6795
6796 result.append("\n");
6797
6798 write(fd, result.string(), result.length());
6799
6800 if (locked) {
6801 mLock.unlock();
6802 }
6803
6804 return NO_ERROR;
6805}
6806
6807// ----------------------------------------------------------------------------
6808// EffectHandle implementation
6809// ----------------------------------------------------------------------------
6810
6811#undef LOG_TAG
6812#define LOG_TAG "AudioFlinger::EffectHandle"
6813
6814AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6815 const sp<AudioFlinger::Client>& client,
6816 const sp<IEffectClient>& effectClient,
6817 int32_t priority)
6818 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006819 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006820 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821{
Steve Block3856b092011-10-20 11:56:00 +01006822 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006824 if (client == 0) {
6825 return;
6826 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6828 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6829 if (mCblkMemory != 0) {
6830 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6831
Glenn Kastena0d68332012-01-27 16:47:15 -08006832 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833 new(mCblk) effect_param_cblk_t();
6834 mBuffer = (uint8_t *)mCblk + bufOffset;
6835 }
6836 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006837 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 return;
6839 }
6840}
6841
6842AudioFlinger::EffectHandle::~EffectHandle()
6843{
Steve Block3856b092011-10-20 11:56:00 +01006844 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006845 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006846 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006847}
6848
6849status_t AudioFlinger::EffectHandle::enable()
6850{
Steve Block3856b092011-10-20 11:56:00 +01006851 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852 if (!mHasControl) return INVALID_OPERATION;
6853 if (mEffect == 0) return DEAD_OBJECT;
6854
Eric Laurentdb7c0792011-08-10 10:37:50 -07006855 if (mEnabled) {
6856 return NO_ERROR;
6857 }
6858
Eric Laurent59255e42011-07-27 19:49:51 -07006859 mEnabled = true;
6860
6861 sp<ThreadBase> thread = mEffect->thread().promote();
6862 if (thread != 0) {
6863 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6864 }
6865
6866 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6867 if (mEffect->suspended()) {
6868 return NO_ERROR;
6869 }
6870
Eric Laurentdb7c0792011-08-10 10:37:50 -07006871 status_t status = mEffect->setEnabled(true);
6872 if (status != NO_ERROR) {
6873 if (thread != 0) {
6874 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6875 }
6876 mEnabled = false;
6877 }
6878 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879}
6880
6881status_t AudioFlinger::EffectHandle::disable()
6882{
Steve Block3856b092011-10-20 11:56:00 +01006883 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006885 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886
Eric Laurentdb7c0792011-08-10 10:37:50 -07006887 if (!mEnabled) {
6888 return NO_ERROR;
6889 }
Eric Laurent59255e42011-07-27 19:49:51 -07006890 mEnabled = false;
6891
6892 if (mEffect->suspended()) {
6893 return NO_ERROR;
6894 }
6895
6896 status_t status = mEffect->setEnabled(false);
6897
6898 sp<ThreadBase> thread = mEffect->thread().promote();
6899 if (thread != 0) {
6900 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6901 }
6902
6903 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904}
6905
6906void AudioFlinger::EffectHandle::disconnect()
6907{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006908 disconnect(true);
6909}
6910
6911void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6912{
Steve Block3856b092011-10-20 11:56:00 +01006913 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914 if (mEffect == 0) {
6915 return;
6916 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006917 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006918
Eric Laurenta85a74a2011-10-19 11:44:54 -07006919 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006920 sp<ThreadBase> thread = mEffect->thread().promote();
6921 if (thread != 0) {
6922 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6923 }
Eric Laurent59255e42011-07-27 19:49:51 -07006924 }
6925
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926 // release sp on module => module destructor can be called now
6927 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006929 if (mCblk != NULL) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006930 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6931 }
6932 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6934 mClient.clear();
6935 }
6936}
6937
Eric Laurent25f43952010-07-28 05:40:18 -07006938status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6939 uint32_t cmdSize,
6940 void *pCmdData,
6941 uint32_t *replySize,
6942 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943{
Steve Block3856b092011-10-20 11:56:00 +01006944// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006945// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946
6947 // only get parameter command is permitted for applications not controlling the effect
6948 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6949 return INVALID_OPERATION;
6950 }
6951 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006952 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953
6954 // handle commands that are not forwarded transparently to effect engine
6955 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6956 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6957 // no risk to block the whole media server process or mixer threads is we are stuck here
6958 Mutex::Autolock _l(mCblk->lock);
6959 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6960 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6961 mCblk->serverIndex = 0;
6962 mCblk->clientIndex = 0;
6963 return BAD_VALUE;
6964 }
6965 status_t status = NO_ERROR;
6966 while (mCblk->serverIndex < mCblk->clientIndex) {
6967 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006968 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969 int *p = (int *)(mBuffer + mCblk->serverIndex);
6970 int size = *p++;
6971 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006972 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 break;
6974 }
6975 effect_param_t *param = (effect_param_t *)p;
6976 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006977 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 mCblk->serverIndex += size;
6979 continue;
6980 }
Eric Laurent25f43952010-07-28 05:40:18 -07006981 uint32_t psize = sizeof(effect_param_t) +
6982 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6983 param->vsize;
6984 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6985 psize,
6986 p,
6987 &rsize,
6988 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006989 // stop at first error encountered
6990 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006992 *(int *)pReplyData = reply;
6993 break;
6994 } else if (reply != NO_ERROR) {
6995 *(int *)pReplyData = reply;
6996 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997 }
6998 mCblk->serverIndex += size;
6999 }
7000 mCblk->serverIndex = 0;
7001 mCblk->clientIndex = 0;
7002 return status;
7003 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007004 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007005 return enable();
7006 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007007 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008 return disable();
7009 }
7010
7011 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7012}
7013
Eric Laurent59255e42011-07-27 19:49:51 -07007014void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015{
Steve Block3856b092011-10-20 11:56:00 +01007016 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017
7018 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007019 mEnabled = enabled;
7020
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 if (signal && mEffectClient != 0) {
7022 mEffectClient->controlStatusChanged(hasControl);
7023 }
7024}
7025
Eric Laurent25f43952010-07-28 05:40:18 -07007026void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7027 uint32_t cmdSize,
7028 void *pCmdData,
7029 uint32_t replySize,
7030 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031{
7032 if (mEffectClient != 0) {
7033 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7034 }
7035}
7036
7037
7038
7039void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7040{
7041 if (mEffectClient != 0) {
7042 mEffectClient->enableStatusChanged(enabled);
7043 }
7044}
7045
7046status_t AudioFlinger::EffectHandle::onTransact(
7047 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7048{
7049 return BnEffect::onTransact(code, data, reply, flags);
7050}
7051
7052
7053void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7054{
Glenn Kastena0d68332012-01-27 16:47:15 -08007055 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056
7057 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7058 (mClient == NULL) ? getpid() : mClient->pid(),
7059 mPriority,
7060 mHasControl,
7061 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007062 mCblk ? mCblk->clientIndex : 0,
7063 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064 );
7065
7066 if (locked) {
7067 mCblk->lock.unlock();
7068 }
7069}
7070
7071#undef LOG_TAG
7072#define LOG_TAG "AudioFlinger::EffectChain"
7073
7074AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7075 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007076 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007077 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7078 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007079{
Dima Zavinfce7a472011-04-19 22:30:36 -07007080 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007081 sp<ThreadBase> thread = mThread.promote();
7082 if (thread == 0) {
7083 return;
7084 }
7085 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7086 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007087}
7088
7089AudioFlinger::EffectChain::~EffectChain()
7090{
7091 if (mOwnInBuffer) {
7092 delete mInBuffer;
7093 }
7094
7095}
7096
Eric Laurent59255e42011-07-27 19:49:51 -07007097// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007098sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099{
7100 sp<EffectModule> effect;
7101 size_t size = mEffects.size();
7102
7103 for (size_t i = 0; i < size; i++) {
7104 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7105 effect = mEffects[i];
7106 break;
7107 }
7108 }
7109 return effect;
7110}
7111
Eric Laurent59255e42011-07-27 19:49:51 -07007112// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007113sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114{
7115 sp<EffectModule> effect;
7116 size_t size = mEffects.size();
7117
7118 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007119 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7120 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007121 effect = mEffects[i];
7122 break;
7123 }
7124 }
7125 return effect;
7126}
7127
Eric Laurent59255e42011-07-27 19:49:51 -07007128// getEffectFromType_l() must be called with ThreadBase::mLock held
7129sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7130 const effect_uuid_t *type)
7131{
7132 sp<EffectModule> effect;
7133 size_t size = mEffects.size();
7134
7135 for (size_t i = 0; i < size; i++) {
7136 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7137 effect = mEffects[i];
7138 break;
7139 }
7140 }
7141 return effect;
7142}
7143
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144// Must be called with EffectChain::mLock locked
7145void AudioFlinger::EffectChain::process_l()
7146{
Eric Laurentdac69112010-09-28 14:09:57 -07007147 sp<ThreadBase> thread = mThread.promote();
7148 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007149 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007150 return;
7151 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007152 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7153 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007154 // always process effects unless no more tracks are on the session and the effect tail
7155 // has been rendered
7156 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007157 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007158 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007159
Eric Laurent544fe9b2011-11-11 15:42:52 -08007160 if (!tracksOnSession && mTailBufferCount == 0) {
7161 doProcess = false;
7162 }
7163
7164 if (activeTrackCnt() == 0) {
7165 // if no track is active and the effect tail has not been rendered,
7166 // the input buffer must be cleared here as the mixer process will not do it
7167 if (tracksOnSession || mTailBufferCount > 0) {
7168 size_t numSamples = thread->frameCount() * thread->channelCount();
7169 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7170 if (mTailBufferCount > 0) {
7171 mTailBufferCount--;
7172 }
7173 }
7174 }
Eric Laurentdac69112010-09-28 14:09:57 -07007175 }
7176
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007178 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007179 for (size_t i = 0; i < size; i++) {
7180 mEffects[i]->process();
7181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 }
7183 for (size_t i = 0; i < size; i++) {
7184 mEffects[i]->updateState();
7185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007186}
7187
Eric Laurentcab11242010-07-15 12:50:15 -07007188// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007189status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190{
7191 effect_descriptor_t desc = effect->desc();
7192 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7193
7194 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007195 effect->setChain(this);
7196 sp<ThreadBase> thread = mThread.promote();
7197 if (thread == 0) {
7198 return NO_INIT;
7199 }
7200 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007201
7202 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7203 // Auxiliary effects are inserted at the beginning of mEffects vector as
7204 // they are processed first and accumulated in chain input buffer
7205 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007206
Mathias Agopian65ab4712010-07-14 17:59:35 -07007207 // the input buffer for auxiliary effect contains mono samples in
7208 // 32 bit format. This is to avoid saturation in AudoMixer
7209 // accumulation stage. Saturation is done in EffectModule::process() before
7210 // calling the process in effect engine
7211 size_t numSamples = thread->frameCount();
7212 int32_t *buffer = new int32_t[numSamples];
7213 memset(buffer, 0, numSamples * sizeof(int32_t));
7214 effect->setInBuffer((int16_t *)buffer);
7215 // auxiliary effects output samples to chain input buffer for further processing
7216 // by insert effects
7217 effect->setOutBuffer(mInBuffer);
7218 } else {
7219 // Insert effects are inserted at the end of mEffects vector as they are processed
7220 // after track and auxiliary effects.
7221 // Insert effect order as a function of indicated preference:
7222 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7223 // another effect is present
7224 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7225 // last effect claiming first position
7226 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7227 // first effect claiming last position
7228 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7229 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7230 // already present
7231
7232 int size = (int)mEffects.size();
7233 int idx_insert = size;
7234 int idx_insert_first = -1;
7235 int idx_insert_last = -1;
7236
7237 for (int i = 0; i < size; i++) {
7238 effect_descriptor_t d = mEffects[i]->desc();
7239 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7240 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7241 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7242 // check invalid effect chaining combinations
7243 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7244 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007245 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246 return INVALID_OPERATION;
7247 }
7248 // remember position of first insert effect and by default
7249 // select this as insert position for new effect
7250 if (idx_insert == size) {
7251 idx_insert = i;
7252 }
7253 // remember position of last insert effect claiming
7254 // first position
7255 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7256 idx_insert_first = i;
7257 }
7258 // remember position of first insert effect claiming
7259 // last position
7260 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7261 idx_insert_last == -1) {
7262 idx_insert_last = i;
7263 }
7264 }
7265 }
7266
7267 // modify idx_insert from first position if needed
7268 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7269 if (idx_insert_last != -1) {
7270 idx_insert = idx_insert_last;
7271 } else {
7272 idx_insert = size;
7273 }
7274 } else {
7275 if (idx_insert_first != -1) {
7276 idx_insert = idx_insert_first + 1;
7277 }
7278 }
7279
7280 // always read samples from chain input buffer
7281 effect->setInBuffer(mInBuffer);
7282
7283 // if last effect in the chain, output samples to chain
7284 // output buffer, otherwise to chain input buffer
7285 if (idx_insert == size) {
7286 if (idx_insert != 0) {
7287 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7288 mEffects[idx_insert-1]->configure();
7289 }
7290 effect->setOutBuffer(mOutBuffer);
7291 } else {
7292 effect->setOutBuffer(mInBuffer);
7293 }
7294 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295
Steve Block3856b092011-10-20 11:56:00 +01007296 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297 }
7298 effect->configure();
7299 return NO_ERROR;
7300}
7301
Eric Laurentcab11242010-07-15 12:50:15 -07007302// removeEffect_l() must be called with PlaybackThread::mLock held
7303size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304{
7305 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306 int size = (int)mEffects.size();
7307 int i;
7308 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7309
7310 for (i = 0; i < size; i++) {
7311 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007312 // calling stop here will remove pre-processing effect from the audio HAL.
7313 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7314 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007315 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7316 mEffects[i]->state() == EffectModule::STOPPING) {
7317 mEffects[i]->stop();
7318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007319 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7320 delete[] effect->inBuffer();
7321 } else {
7322 if (i == size - 1 && i != 0) {
7323 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7324 mEffects[i - 1]->configure();
7325 }
7326 }
7327 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007328 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329 break;
7330 }
7331 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332
7333 return mEffects.size();
7334}
7335
Eric Laurentcab11242010-07-15 12:50:15 -07007336// setDevice_l() must be called with PlaybackThread::mLock held
7337void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338{
7339 size_t size = mEffects.size();
7340 for (size_t i = 0; i < size; i++) {
7341 mEffects[i]->setDevice(device);
7342 }
7343}
7344
Eric Laurentcab11242010-07-15 12:50:15 -07007345// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007346void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347{
7348 size_t size = mEffects.size();
7349 for (size_t i = 0; i < size; i++) {
7350 mEffects[i]->setMode(mode);
7351 }
7352}
7353
Eric Laurentcab11242010-07-15 12:50:15 -07007354// setVolume_l() must be called with PlaybackThread::mLock held
7355bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007356{
7357 uint32_t newLeft = *left;
7358 uint32_t newRight = *right;
7359 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007360 int ctrlIdx = -1;
7361 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362
Eric Laurentcab11242010-07-15 12:50:15 -07007363 // first update volume controller
7364 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007365 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007366 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7367 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007368 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007369 break;
7370 }
7371 }
7372
7373 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007374 if (hasControl) {
7375 *left = mNewLeftVolume;
7376 *right = mNewRightVolume;
7377 }
7378 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007379 }
7380
7381 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007382 mLeftVolume = newLeft;
7383 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007384
7385 // second get volume update from volume controller
7386 if (ctrlIdx >= 0) {
7387 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007388 mNewLeftVolume = newLeft;
7389 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 }
7391 // then indicate volume to all other effects in chain.
7392 // Pass altered volume to effects before volume controller
7393 // and requested volume to effects after controller
7394 uint32_t lVol = newLeft;
7395 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007396
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007398 if ((int)i == ctrlIdx) continue;
7399 // this also works for ctrlIdx == -1 when there is no volume controller
7400 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401 lVol = *left;
7402 rVol = *right;
7403 }
7404 mEffects[i]->setVolume(&lVol, &rVol, false);
7405 }
7406 *left = newLeft;
7407 *right = newRight;
7408
7409 return hasControl;
7410}
7411
Mathias Agopian65ab4712010-07-14 17:59:35 -07007412status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7413{
7414 const size_t SIZE = 256;
7415 char buffer[SIZE];
7416 String8 result;
7417
7418 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7419 result.append(buffer);
7420
7421 bool locked = tryLock(mLock);
7422 // failed to lock - AudioFlinger is probably deadlocked
7423 if (!locked) {
7424 result.append("\tCould not lock mutex:\n");
7425 }
7426
Eric Laurentcab11242010-07-15 12:50:15 -07007427 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7428 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429 mEffects.size(),
7430 (uint32_t)mInBuffer,
7431 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432 mActiveTrackCnt);
7433 result.append(buffer);
7434 write(fd, result.string(), result.size());
7435
7436 for (size_t i = 0; i < mEffects.size(); ++i) {
7437 sp<EffectModule> effect = mEffects[i];
7438 if (effect != 0) {
7439 effect->dump(fd, args);
7440 }
7441 }
7442
7443 if (locked) {
7444 mLock.unlock();
7445 }
7446
7447 return NO_ERROR;
7448}
7449
Eric Laurent59255e42011-07-27 19:49:51 -07007450// must be called with ThreadBase::mLock held
7451void AudioFlinger::EffectChain::setEffectSuspended_l(
7452 const effect_uuid_t *type, bool suspend)
7453{
7454 sp<SuspendedEffectDesc> desc;
7455 // use effect type UUID timelow as key as there is no real risk of identical
7456 // timeLow fields among effect type UUIDs.
7457 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7458 if (suspend) {
7459 if (index >= 0) {
7460 desc = mSuspendedEffects.valueAt(index);
7461 } else {
7462 desc = new SuspendedEffectDesc();
7463 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7464 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007465 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007466 }
7467 if (desc->mRefCount++ == 0) {
7468 sp<EffectModule> effect = getEffectIfEnabled(type);
7469 if (effect != 0) {
7470 desc->mEffect = effect;
7471 effect->setSuspended(true);
7472 effect->setEnabled(false);
7473 }
7474 }
7475 } else {
7476 if (index < 0) {
7477 return;
7478 }
7479 desc = mSuspendedEffects.valueAt(index);
7480 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007481 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007482 desc->mRefCount = 1;
7483 }
7484 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007485 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007486 if (desc->mEffect != 0) {
7487 sp<EffectModule> effect = desc->mEffect.promote();
7488 if (effect != 0) {
7489 effect->setSuspended(false);
7490 sp<EffectHandle> handle = effect->controlHandle();
7491 if (handle != 0) {
7492 effect->setEnabled(handle->enabled());
7493 }
7494 }
7495 desc->mEffect.clear();
7496 }
7497 mSuspendedEffects.removeItemsAt(index);
7498 }
7499 }
7500}
7501
7502// must be called with ThreadBase::mLock held
7503void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7504{
7505 sp<SuspendedEffectDesc> desc;
7506
7507 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7508 if (suspend) {
7509 if (index >= 0) {
7510 desc = mSuspendedEffects.valueAt(index);
7511 } else {
7512 desc = new SuspendedEffectDesc();
7513 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007514 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007515 }
7516 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007517 Vector< sp<EffectModule> > effects;
7518 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007519 for (size_t i = 0; i < effects.size(); i++) {
7520 setEffectSuspended_l(&effects[i]->desc().type, true);
7521 }
7522 }
7523 } else {
7524 if (index < 0) {
7525 return;
7526 }
7527 desc = mSuspendedEffects.valueAt(index);
7528 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007529 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007530 desc->mRefCount = 1;
7531 }
7532 if (--desc->mRefCount == 0) {
7533 Vector<const effect_uuid_t *> types;
7534 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7535 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7536 continue;
7537 }
7538 types.add(&mSuspendedEffects.valueAt(i)->mType);
7539 }
7540 for (size_t i = 0; i < types.size(); i++) {
7541 setEffectSuspended_l(types[i], false);
7542 }
Steve Block3856b092011-10-20 11:56:00 +01007543 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007544 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7545 }
7546 }
7547}
7548
Eric Laurent6bffdb82011-09-23 08:40:41 -07007549
7550// The volume effect is used for automated tests only
7551#ifndef OPENSL_ES_H_
7552static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7553 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7554const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7555#endif //OPENSL_ES_H_
7556
Eric Laurentdb7c0792011-08-10 10:37:50 -07007557bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7558{
7559 // auxiliary effects and visualizer are never suspended on output mix
7560 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7561 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007562 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7563 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007564 return false;
7565 }
7566 return true;
7567}
7568
Glenn Kastend0539712012-01-30 12:56:03 -08007569void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007570{
Glenn Kastend0539712012-01-30 12:56:03 -08007571 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007572 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007573 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7574 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007575 }
Eric Laurent59255e42011-07-27 19:49:51 -07007576 }
Eric Laurent59255e42011-07-27 19:49:51 -07007577}
7578
7579sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7580 const effect_uuid_t *type)
7581{
7582 sp<EffectModule> effect;
7583 effect = getEffectFromType_l(type);
7584 if (effect != 0 && !effect->isEnabled()) {
7585 effect.clear();
7586 }
7587 return effect;
7588}
7589
7590void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7591 bool enabled)
7592{
7593 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7594 if (enabled) {
7595 if (index < 0) {
7596 // if the effect is not suspend check if all effects are suspended
7597 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7598 if (index < 0) {
7599 return;
7600 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007601 if (!isEffectEligibleForSuspend(effect->desc())) {
7602 return;
7603 }
Eric Laurent59255e42011-07-27 19:49:51 -07007604 setEffectSuspended_l(&effect->desc().type, enabled);
7605 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007606 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007607 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007608 return;
7609 }
Eric Laurent59255e42011-07-27 19:49:51 -07007610 }
Steve Block3856b092011-10-20 11:56:00 +01007611 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007612 effect->desc().type.timeLow);
7613 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7614 // if effect is requested to suspended but was not yet enabled, supend it now.
7615 if (desc->mEffect == 0) {
7616 desc->mEffect = effect;
7617 effect->setEnabled(false);
7618 effect->setSuspended(true);
7619 }
7620 } else {
7621 if (index < 0) {
7622 return;
7623 }
Steve Block3856b092011-10-20 11:56:00 +01007624 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007625 effect->desc().type.timeLow);
7626 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7627 desc->mEffect.clear();
7628 effect->setSuspended(false);
7629 }
7630}
7631
Mathias Agopian65ab4712010-07-14 17:59:35 -07007632#undef LOG_TAG
7633#define LOG_TAG "AudioFlinger"
7634
7635// ----------------------------------------------------------------------------
7636
7637status_t AudioFlinger::onTransact(
7638 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7639{
7640 return BnAudioFlinger::onTransact(code, data, reply, flags);
7641}
7642
Mathias Agopian65ab4712010-07-14 17:59:35 -07007643}; // namespace android