blob: 1c19057557118bddd04b1da58a36775d6ae2a80e [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 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800812 if (thread != 0) {
813 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 }
815 return BAD_VALUE;
816}
817
818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
819{
Steve Block3856b092011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin799a70e2011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700832 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 }
834
835 Mutex::Autolock _l(mLock);
836
837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
846}
847
Glenn Kasten58f30212012-01-12 12:27:51 -0800848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849{
Eric Laurenta1884f92011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856}
857
858unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurenta1884f92011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
909
910 Mutex::Autolock _l(mLock);
911
912 int pid = IPCThreadState::self()->getCallingPid();
913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block3856b092011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918
919 mNotificationClients.add(pid, notificationClient);
920
921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
923
924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
929
930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
932 }
933 }
934}
935
936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700946
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965}
966
967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800972 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
973 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 }
975}
976
977// removeClient_l() must be called with AudioFlinger::mLock held
978void AudioFlinger::removeClient_l(pid_t pid)
979{
Steve Block3856b092011-10-20 11:56:00 +0100980 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 mClients.removeItem(pid);
982}
983
984
985// ----------------------------------------------------------------------------
986
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800987AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device,
988 type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800990 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800991 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
992 // mChannelMask
993 mChannelCount(0),
994 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
995 mParamStatus(NO_ERROR),
996 mStandby(false), mId(id), mExiting(false),
997 mDevice(device),
998 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999{
1000}
1001
1002AudioFlinger::ThreadBase::~ThreadBase()
1003{
1004 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001005 // do not lock the mutex in destructor
1006 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001007 if (mPowerManager != 0) {
1008 sp<IBinder> binder = mPowerManager->asBinder();
1009 binder->unlinkToDeath(mDeathRecipient);
1010 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001011}
1012
1013void AudioFlinger::ThreadBase::exit()
1014{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001015 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016 // destroyed in the middle of requestExitAndWait()
1017 sp <ThreadBase> strongMe = this;
1018
Steve Block3856b092011-10-20 11:56:00 +01001019 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001021 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 mExiting = true;
1023 requestExit();
1024 mWaitWorkCV.signal();
1025 }
1026 requestExitAndWait();
1027}
1028
1029uint32_t AudioFlinger::ThreadBase::sampleRate() const
1030{
1031 return mSampleRate;
1032}
1033
1034int AudioFlinger::ThreadBase::channelCount() const
1035{
1036 return (int)mChannelCount;
1037}
1038
Glenn Kasten58f30212012-01-12 12:27:51 -08001039audio_format_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040{
1041 return mFormat;
1042}
1043
1044size_t AudioFlinger::ThreadBase::frameCount() const
1045{
1046 return mFrameCount;
1047}
1048
1049status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1050{
1051 status_t status;
1052
Steve Block3856b092011-10-20 11:56:00 +01001053 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 Mutex::Autolock _l(mLock);
1055
1056 mNewParameters.add(keyValuePairs);
1057 mWaitWorkCV.signal();
1058 // wait condition with timeout in case the thread loop has exited
1059 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001060 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001061 status = mParamStatus;
1062 mWaitWorkCV.signal();
1063 } else {
1064 status = TIMED_OUT;
1065 }
1066 return status;
1067}
1068
1069void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1070{
1071 Mutex::Autolock _l(mLock);
1072 sendConfigEvent_l(event, param);
1073}
1074
1075// sendConfigEvent_l() must be called with ThreadBase::mLock held
1076void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1077{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001078 ConfigEvent configEvent;
1079 configEvent.mEvent = event;
1080 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001082 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 mWaitWorkCV.signal();
1084}
1085
1086void AudioFlinger::ThreadBase::processConfigEvents()
1087{
1088 mLock.lock();
1089 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001090 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001091 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 mConfigEvents.removeAt(0);
1093 // release mLock before locking AudioFlinger mLock: lock order is always
1094 // AudioFlinger then ThreadBase to avoid cross deadlock
1095 mLock.unlock();
1096 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001097 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001098 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001099 mLock.lock();
1100 }
1101 mLock.unlock();
1102}
1103
1104status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1105{
1106 const size_t SIZE = 256;
1107 char buffer[SIZE];
1108 String8 result;
1109
1110 bool locked = tryLock(mLock);
1111 if (!locked) {
1112 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1113 write(fd, buffer, strlen(buffer));
1114 }
1115
1116 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1117 result.append(buffer);
1118 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1119 result.append(buffer);
1120 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1123 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001124 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1125 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1127 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001128 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001129 result.append(buffer);
1130
1131 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1132 result.append(buffer);
1133 result.append(" Index Command");
1134 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1135 snprintf(buffer, SIZE, "\n %02d ", i);
1136 result.append(buffer);
1137 result.append(mNewParameters[i]);
1138 }
1139
1140 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1141 result.append(buffer);
1142 snprintf(buffer, SIZE, " Index event param\n");
1143 result.append(buffer);
1144 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001145 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001146 result.append(buffer);
1147 }
1148 result.append("\n");
1149
1150 write(fd, result.string(), result.size());
1151
1152 if (locked) {
1153 mLock.unlock();
1154 }
1155 return NO_ERROR;
1156}
1157
Eric Laurent1d2bff02011-07-24 17:49:51 -07001158status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1159{
1160 const size_t SIZE = 256;
1161 char buffer[SIZE];
1162 String8 result;
1163
1164 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1165 write(fd, buffer, strlen(buffer));
1166
1167 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1168 sp<EffectChain> chain = mEffectChains[i];
1169 if (chain != 0) {
1170 chain->dump(fd, args);
1171 }
1172 }
1173 return NO_ERROR;
1174}
1175
Eric Laurentfeb0db62011-07-22 09:04:31 -07001176void AudioFlinger::ThreadBase::acquireWakeLock()
1177{
1178 Mutex::Autolock _l(mLock);
1179 acquireWakeLock_l();
1180}
1181
1182void AudioFlinger::ThreadBase::acquireWakeLock_l()
1183{
1184 if (mPowerManager == 0) {
1185 // use checkService() to avoid blocking if power service is not up yet
1186 sp<IBinder> binder =
1187 defaultServiceManager()->checkService(String16("power"));
1188 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001189 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001190 } else {
1191 mPowerManager = interface_cast<IPowerManager>(binder);
1192 binder->linkToDeath(mDeathRecipient);
1193 }
1194 }
1195 if (mPowerManager != 0) {
1196 sp<IBinder> binder = new BBinder();
1197 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1198 binder,
1199 String16(mName));
1200 if (status == NO_ERROR) {
1201 mWakeLockToken = binder;
1202 }
Steve Block3856b092011-10-20 11:56:00 +01001203 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001204 }
1205}
1206
1207void AudioFlinger::ThreadBase::releaseWakeLock()
1208{
1209 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001210 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001211}
1212
1213void AudioFlinger::ThreadBase::releaseWakeLock_l()
1214{
1215 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001216 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001217 if (mPowerManager != 0) {
1218 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1219 }
1220 mWakeLockToken.clear();
1221 }
1222}
1223
1224void AudioFlinger::ThreadBase::clearPowerManager()
1225{
1226 Mutex::Autolock _l(mLock);
1227 releaseWakeLock_l();
1228 mPowerManager.clear();
1229}
1230
1231void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1232{
1233 sp<ThreadBase> thread = mThread.promote();
1234 if (thread != 0) {
1235 thread->clearPowerManager();
1236 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001237 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001238}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001239
Eric Laurent59255e42011-07-27 19:49:51 -07001240void AudioFlinger::ThreadBase::setEffectSuspended(
1241 const effect_uuid_t *type, bool suspend, int sessionId)
1242{
1243 Mutex::Autolock _l(mLock);
1244 setEffectSuspended_l(type, suspend, sessionId);
1245}
1246
1247void AudioFlinger::ThreadBase::setEffectSuspended_l(
1248 const effect_uuid_t *type, bool suspend, int sessionId)
1249{
1250 sp<EffectChain> chain;
1251 chain = getEffectChain_l(sessionId);
1252 if (chain != 0) {
1253 if (type != NULL) {
1254 chain->setEffectSuspended_l(type, suspend);
1255 } else {
1256 chain->setEffectSuspendedAll_l(suspend);
1257 }
1258 }
1259
1260 updateSuspendedSessions_l(type, suspend, sessionId);
1261}
1262
1263void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1264{
1265 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1266 if (index < 0) {
1267 return;
1268 }
1269
1270 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1271 mSuspendedSessions.editValueAt(index);
1272
1273 for (size_t i = 0; i < sessionEffects.size(); i++) {
1274 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1275 for (int j = 0; j < desc->mRefCount; j++) {
1276 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1277 chain->setEffectSuspendedAll_l(true);
1278 } else {
Steve Block3856b092011-10-20 11:56:00 +01001279 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001280 desc->mType.timeLow);
1281 chain->setEffectSuspended_l(&desc->mType, true);
1282 }
1283 }
1284 }
1285}
1286
Eric Laurent59255e42011-07-27 19:49:51 -07001287void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1288 bool suspend,
1289 int sessionId)
1290{
1291 int index = mSuspendedSessions.indexOfKey(sessionId);
1292
1293 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1294
1295 if (suspend) {
1296 if (index >= 0) {
1297 sessionEffects = mSuspendedSessions.editValueAt(index);
1298 } else {
1299 mSuspendedSessions.add(sessionId, sessionEffects);
1300 }
1301 } else {
1302 if (index < 0) {
1303 return;
1304 }
1305 sessionEffects = mSuspendedSessions.editValueAt(index);
1306 }
1307
1308
1309 int key = EffectChain::kKeyForSuspendAll;
1310 if (type != NULL) {
1311 key = type->timeLow;
1312 }
1313 index = sessionEffects.indexOfKey(key);
1314
1315 sp <SuspendedSessionDesc> desc;
1316 if (suspend) {
1317 if (index >= 0) {
1318 desc = sessionEffects.valueAt(index);
1319 } else {
1320 desc = new SuspendedSessionDesc();
1321 if (type != NULL) {
1322 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1323 }
1324 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001325 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001326 }
1327 desc->mRefCount++;
1328 } else {
1329 if (index < 0) {
1330 return;
1331 }
1332 desc = sessionEffects.valueAt(index);
1333 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001335 sessionEffects.removeItemsAt(index);
1336 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001337 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001338 sessionId);
1339 mSuspendedSessions.removeItem(sessionId);
1340 }
1341 }
1342 }
1343 if (!sessionEffects.isEmpty()) {
1344 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1345 }
1346}
1347
1348void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1349 bool enabled,
1350 int sessionId)
1351{
1352 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001353 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1354}
Eric Laurent59255e42011-07-27 19:49:51 -07001355
Eric Laurenta85a74a2011-10-19 11:44:54 -07001356void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1357 bool enabled,
1358 int sessionId)
1359{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001360 if (mType != RECORD) {
1361 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1362 // another session. This gives the priority to well behaved effect control panels
1363 // and applications not using global effects.
1364 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1365 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1366 }
1367 }
Eric Laurent59255e42011-07-27 19:49:51 -07001368
1369 sp<EffectChain> chain = getEffectChain_l(sessionId);
1370 if (chain != 0) {
1371 chain->checkSuspendOnEffectEnabled(effect, enabled);
1372 }
1373}
1374
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375// ----------------------------------------------------------------------------
1376
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001377AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1378 AudioStreamOut* output,
1379 int id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001380 uint32_t device,
1381 type_t type)
1382 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001383 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1384 // Assumes constructor is called by AudioFlinger with it's mLock held,
1385 // but it would be safer to explicitly pass initial masterMute as parameter
1386 mMasterMute(audioFlinger->masterMute_l()),
1387 // mStreamTypes[] initialized in constructor body
1388 mOutput(output),
1389 // Assumes constructor is called by AudioFlinger with it's mLock held,
1390 // but it would be safer to explicitly pass initial masterVolume as parameter
1391 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001392 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001394 snprintf(mName, kNameLength, "AudioOut_%d", id);
1395
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 readOutputParameters();
1397
Glenn Kasten263709e2012-01-06 08:40:01 -08001398 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001399 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1400 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1401 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001402 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1403 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001404 // initialized by stream_type_t default constructor
1405 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406 }
1407}
1408
1409AudioFlinger::PlaybackThread::~PlaybackThread()
1410{
1411 delete [] mMixBuffer;
1412}
1413
1414status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1415{
1416 dumpInternals(fd, args);
1417 dumpTracks(fd, args);
1418 dumpEffectChains(fd, args);
1419 return NO_ERROR;
1420}
1421
1422status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1423{
1424 const size_t SIZE = 256;
1425 char buffer[SIZE];
1426 String8 result;
1427
1428 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1429 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001430 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 for (size_t i = 0; i < mTracks.size(); ++i) {
1432 sp<Track> track = mTracks[i];
1433 if (track != 0) {
1434 track->dump(buffer, SIZE);
1435 result.append(buffer);
1436 }
1437 }
1438
1439 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1440 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001441 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 -07001442 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001443 sp<Track> track = mActiveTracks[i].promote();
1444 if (track != 0) {
1445 track->dump(buffer, SIZE);
1446 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447 }
1448 }
1449 write(fd, result.string(), result.size());
1450 return NO_ERROR;
1451}
1452
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1454{
1455 const size_t SIZE = 256;
1456 char buffer[SIZE];
1457 String8 result;
1458
1459 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1460 result.append(buffer);
1461 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1462 result.append(buffer);
1463 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1464 result.append(buffer);
1465 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1466 result.append(buffer);
1467 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1468 result.append(buffer);
1469 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1470 result.append(buffer);
1471 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1472 result.append(buffer);
1473 write(fd, result.string(), result.size());
1474
1475 dumpBase(fd, args);
1476
1477 return NO_ERROR;
1478}
1479
1480// Thread virtuals
1481status_t AudioFlinger::PlaybackThread::readyToRun()
1482{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001483 status_t status = initCheck();
1484 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001485 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001486 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001487 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001489 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490}
1491
1492void AudioFlinger::PlaybackThread::onFirstRef()
1493{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001494 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001495}
1496
1497// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1498sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1499 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001500 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001502 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001503 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 int frameCount,
1505 const sp<IMemory>& sharedBuffer,
1506 int sessionId,
1507 status_t *status)
1508{
1509 sp<Track> track;
1510 status_t lStatus;
1511
1512 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001513 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1514 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001515 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001516 "for output %p with format %d",
1517 sampleRate, format, channelMask, mOutput, mFormat);
1518 lStatus = BAD_VALUE;
1519 goto Exit;
1520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 }
1522 } else {
1523 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1524 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001525 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 lStatus = BAD_VALUE;
1527 goto Exit;
1528 }
1529 }
1530
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001531 lStatus = initCheck();
1532 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001533 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 goto Exit;
1535 }
1536
1537 { // scope for mLock
1538 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001539
1540 // all tracks in same audio session must share the same routing strategy otherwise
1541 // conflicts will happen when tracks are moved from one output to another by audio policy
1542 // manager
1543 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001544 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001545 for (size_t i = 0; i < mTracks.size(); ++i) {
1546 sp<Track> t = mTracks[i];
1547 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001548 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1549 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001550 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001551 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001552 lStatus = BAD_VALUE;
1553 goto Exit;
1554 }
1555 }
1556 }
1557
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001559 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 if (track->getCblk() == NULL || track->name() < 0) {
1561 lStatus = NO_MEMORY;
1562 goto Exit;
1563 }
1564 mTracks.add(track);
1565
1566 sp<EffectChain> chain = getEffectChain_l(sessionId);
1567 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001568 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001570 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001571 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001573
1574 // invalidate track immediately if the stream type was moved to another thread since
1575 // createTrack() was called by the client process.
1576 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001577 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001578 this, streamType);
1579 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1580 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 }
1582 lStatus = NO_ERROR;
1583
1584Exit:
1585 if(status) {
1586 *status = lStatus;
1587 }
1588 return track;
1589}
1590
1591uint32_t AudioFlinger::PlaybackThread::latency() const
1592{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001593 Mutex::Autolock _l(mLock);
1594 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001595 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001596 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 return 0;
1598 }
1599}
1600
1601status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1602{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 mMasterVolume = value;
1604 return NO_ERROR;
1605}
1606
1607status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1608{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 mMasterMute = muted;
1610 return NO_ERROR;
1611}
1612
1613float AudioFlinger::PlaybackThread::masterVolume() const
1614{
1615 return mMasterVolume;
1616}
1617
1618bool AudioFlinger::PlaybackThread::masterMute() const
1619{
1620 return mMasterMute;
1621}
1622
Glenn Kastenfff6d712012-01-12 16:38:12 -08001623status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 mStreamTypes[stream].volume = value;
1626 return NO_ERROR;
1627}
1628
Glenn Kastenfff6d712012-01-12 16:38:12 -08001629status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631 mStreamTypes[stream].mute = muted;
1632 return NO_ERROR;
1633}
1634
Glenn Kastenfff6d712012-01-12 16:38:12 -08001635float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636{
1637 return mStreamTypes[stream].volume;
1638}
1639
Glenn Kastenfff6d712012-01-12 16:38:12 -08001640bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641{
1642 return mStreamTypes[stream].mute;
1643}
1644
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645// addTrack_l() must be called with ThreadBase::mLock held
1646status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1647{
1648 status_t status = ALREADY_EXISTS;
1649
1650 // set retry count for buffer fill
1651 track->mRetryCount = kMaxTrackStartupRetries;
1652 if (mActiveTracks.indexOf(track) < 0) {
1653 // the track is newly added, make sure it fills up all its
1654 // buffers before playing. This is to ensure the client will
1655 // effectively get the latency it requested.
1656 track->mFillingUpStatus = Track::FS_FILLING;
1657 track->mResetDone = false;
1658 mActiveTracks.add(track);
1659 if (track->mainBuffer() != mMixBuffer) {
1660 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1661 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001662 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001663 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664 }
1665 }
1666
1667 status = NO_ERROR;
1668 }
1669
Steve Block3856b092011-10-20 11:56:00 +01001670 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 mWaitWorkCV.broadcast();
1672
1673 return status;
1674}
1675
1676// destroyTrack_l() must be called with ThreadBase::mLock held
1677void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1678{
1679 track->mState = TrackBase::TERMINATED;
1680 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001681 removeTrack_l(track);
1682 }
1683}
1684
1685void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1686{
1687 mTracks.remove(track);
1688 deleteTrackName_l(track->name());
1689 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1690 if (chain != 0) {
1691 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001692 }
1693}
1694
1695String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1696{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001697 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001698 char *s;
1699
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001700 Mutex::Autolock _l(mLock);
1701 if (initCheck() != NO_ERROR) {
1702 return out_s8;
1703 }
1704
Dima Zavin799a70e2011-04-18 16:57:27 -07001705 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001706 out_s8 = String8(s);
1707 free(s);
1708 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709}
1710
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001711// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1713 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001714 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715
Steve Block3856b092011-10-20 11:56:00 +01001716 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717
1718 switch (event) {
1719 case AudioSystem::OUTPUT_OPENED:
1720 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001721 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001722 desc.samplingRate = mSampleRate;
1723 desc.format = mFormat;
1724 desc.frameCount = mFrameCount;
1725 desc.latency = latency();
1726 param2 = &desc;
1727 break;
1728
1729 case AudioSystem::STREAM_CONFIG_CHANGED:
1730 param2 = &param;
1731 case AudioSystem::OUTPUT_CLOSED:
1732 default:
1733 break;
1734 }
1735 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1736}
1737
1738void AudioFlinger::PlaybackThread::readOutputParameters()
1739{
Dima Zavin799a70e2011-04-18 16:57:27 -07001740 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001741 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1742 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001743 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001744 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001745 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746
1747 // FIXME - Current mixer implementation only supports stereo output: Always
1748 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001749 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 mMixBuffer = new int16_t[mFrameCount * 2];
1751 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1752
Eric Laurentde070132010-07-13 04:45:46 -07001753 // force reconfiguration of effect chains and engines to take new buffer size and audio
1754 // parameters into account
1755 // Note that mLock is not held when readOutputParameters() is called from the constructor
1756 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1757 // matter.
1758 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1759 Vector< sp<EffectChain> > effectChains = mEffectChains;
1760 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001761 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763}
1764
1765status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1766{
Glenn Kastena0d68332012-01-27 16:47:15 -08001767 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 return BAD_VALUE;
1769 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001770 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001771 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 return INVALID_OPERATION;
1773 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001774 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775
Dima Zavin799a70e2011-04-18 16:57:27 -07001776 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777}
1778
Eric Laurent39e94f82010-07-28 01:32:47 -07001779uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780{
1781 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001782 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001784 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 }
1786
1787 for (size_t i = 0; i < mTracks.size(); ++i) {
1788 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001789 if (sessionId == track->sessionId() &&
1790 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001791 result |= TRACK_SESSION;
1792 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793 }
1794 }
1795
Eric Laurent39e94f82010-07-28 01:32:47 -07001796 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797}
1798
Eric Laurentde070132010-07-13 04:45:46 -07001799uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1800{
Dima Zavinfce7a472011-04-19 22:30:36 -07001801 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001802 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001803 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1804 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001805 }
1806 for (size_t i = 0; i < mTracks.size(); i++) {
1807 sp<Track> track = mTracks[i];
1808 if (sessionId == track->sessionId() &&
1809 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001810 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001811 }
1812 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001813 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001814}
1815
Mathias Agopian65ab4712010-07-14 17:59:35 -07001816
Glenn Kastenaed850d2012-01-26 09:46:34 -08001817AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001818{
1819 Mutex::Autolock _l(mLock);
1820 return mOutput;
1821}
1822
1823AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1824{
1825 Mutex::Autolock _l(mLock);
1826 AudioStreamOut *output = mOutput;
1827 mOutput = NULL;
1828 return output;
1829}
1830
1831// this method must always be called either with ThreadBase mLock held or inside the thread loop
1832audio_stream_t* AudioFlinger::PlaybackThread::stream()
1833{
1834 if (mOutput == NULL) {
1835 return NULL;
1836 }
1837 return &mOutput->stream->common;
1838}
1839
Eric Laurent162b40b2011-12-05 09:47:19 -08001840uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1841{
1842 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1843 // decoding and transfer time. So sleeping for half of the latency would likely cause
1844 // underruns
1845 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1846 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1847 } else {
1848 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1849 }
1850}
1851
Mathias Agopian65ab4712010-07-14 17:59:35 -07001852// ----------------------------------------------------------------------------
1853
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001854AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
1855 int id, uint32_t device, type_t type)
1856 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001857 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1858 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001859{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 // FIXME - Current mixer implementation only supports stereo output
1861 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001862 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 }
1864}
1865
1866AudioFlinger::MixerThread::~MixerThread()
1867{
1868 delete mAudioMixer;
1869}
1870
1871bool AudioFlinger::MixerThread::threadLoop()
1872{
1873 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001874 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 nsecs_t standbyTime = systemTime();
1876 size_t mixBufferSize = mFrameCount * mFrameSize;
1877 // FIXME: Relaxed timing because of a certain device that can't meet latency
1878 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001879 // increase threshold again due to low power audio mode. The way this warning threshold is
1880 // calculated and its usefulness should be reconsidered anyway.
1881 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882 nsecs_t lastWarning = 0;
1883 bool longStandbyExit = false;
1884 uint32_t activeSleepTime = activeSleepTimeUs();
1885 uint32_t idleSleepTime = idleSleepTimeUs();
1886 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001887 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001889#ifdef DEBUG_CPU_USAGE
1890 ThreadCpuUsage cpu;
1891 const CentralTendencyStatistics& stats = cpu.statistics();
1892#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893
Eric Laurentfeb0db62011-07-22 09:04:31 -07001894 acquireWakeLock();
1895
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896 while (!exitPending())
1897 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001898#ifdef DEBUG_CPU_USAGE
1899 cpu.sampleAndEnable();
1900 unsigned n = stats.n();
1901 // cpu.elapsed() is expensive, so don't call it every loop
1902 if ((n & 127) == 1) {
1903 long long elapsed = cpu.elapsed();
1904 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1905 double perLoop = elapsed / (double) n;
1906 double perLoop100 = perLoop * 0.01;
1907 double mean = stats.mean();
1908 double stddev = stats.stddev();
1909 double minimum = stats.minimum();
1910 double maximum = stats.maximum();
1911 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001912 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 -07001913 elapsed * .000000001, n, perLoop * .000001,
1914 mean * .001,
1915 stddev * .001,
1916 minimum * .001,
1917 maximum * .001,
1918 mean / perLoop100,
1919 stddev / perLoop100,
1920 minimum / perLoop100,
1921 maximum / perLoop100);
1922 }
1923 }
1924#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 processConfigEvents();
1926
1927 mixerStatus = MIXER_IDLE;
1928 { // scope for mLock
1929
1930 Mutex::Autolock _l(mLock);
1931
1932 if (checkForNewParameters_l()) {
1933 mixBufferSize = mFrameCount * mFrameSize;
1934 // FIXME: Relaxed timing because of a certain device that can't meet latency
1935 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001936 // increase threshold again due to low power audio mode. The way this warning
1937 // threshold is calculated and its usefulness should be reconsidered anyway.
1938 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 activeSleepTime = activeSleepTimeUs();
1940 idleSleepTime = idleSleepTimeUs();
1941 }
1942
1943 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1944
1945 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001946 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1947 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001949 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001950 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 mStandby = true;
1952 mBytesWritten = 0;
1953 }
1954
1955 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1956 // we're about to wait, flush the binder command buffer
1957 IPCThreadState::self()->flushCommands();
1958
1959 if (exitPending()) break;
1960
Eric Laurentfeb0db62011-07-22 09:04:31 -07001961 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001963 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001965 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001966 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967
Eric Laurent27741442012-01-17 19:20:12 -08001968 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001969 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 char value[PROPERTY_VALUE_MAX];
1971 property_get("ro.audio.silent", value, "0");
1972 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001973 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001974 setMasterMute(true);
1975 }
1976 }
1977
1978 standbyTime = systemTime() + kStandbyTimeInNsecs;
1979 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001980 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 continue;
1982 }
1983 }
1984
1985 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1986
1987 // prevent any changes in effect chain list and in each effect chain
1988 // during mixing and effect process as the audio buffers could be deleted
1989 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001990 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001992
Glenn Kastenf6b16782011-12-15 09:51:17 -08001993 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 // mix buffers...
1995 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001996 // increase sleep time progressively when application underrun condition clears.
1997 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1998 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1999 // such that we would underrun the audio HAL.
2000 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002001 sleepTimeShift--;
2002 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08002003 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 standbyTime = systemTime() + kStandbyTimeInNsecs;
2005 //TODO: delay standby when effects have a tail
2006 } else {
2007 // If no tracks are ready, sleep once for the duration of an output
2008 // buffer size, then write 0s to the output
2009 if (sleepTime == 0) {
2010 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002011 sleepTime = activeSleepTime >> sleepTimeShift;
2012 if (sleepTime < kMinThreadSleepTimeUs) {
2013 sleepTime = kMinThreadSleepTimeUs;
2014 }
2015 // reduce sleep time in case of consecutive application underruns to avoid
2016 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2017 // duration we would end up writing less data than needed by the audio HAL if
2018 // the condition persists.
2019 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2020 sleepTimeShift++;
2021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 } else {
2023 sleepTime = idleSleepTime;
2024 }
2025 } else if (mBytesWritten != 0 ||
2026 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2027 memset (mMixBuffer, 0, mixBufferSize);
2028 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002029 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 }
2031 // TODO add standby time extension fct of effect tail
2032 }
2033
2034 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002035 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 }
2037 // sleepTime == 0 means we must write to audio hardware
2038 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002039 for (size_t i = 0; i < effectChains.size(); i ++) {
2040 effectChains[i]->process_l();
2041 }
2042 // enable changes in effect chain
2043 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 mLastWriteTime = systemTime();
2045 mInWrite = true;
2046 mBytesWritten += mixBufferSize;
2047
Dima Zavin799a70e2011-04-18 16:57:27 -07002048 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2050 mNumWrites++;
2051 mInWrite = false;
2052 nsecs_t now = systemTime();
2053 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002054 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002056 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002057 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 ns2ms(delta), mNumDelayedWrites, this);
2059 lastWarning = now;
2060 }
2061 if (mStandby) {
2062 longStandbyExit = true;
2063 }
2064 }
2065 mStandby = false;
2066 } else {
2067 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002068 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069 usleep(sleepTime);
2070 }
2071
2072 // finally let go of all our tracks, without the lock held
2073 // since we can't guarantee the destructors won't acquire that
2074 // same lock.
2075 tracksToRemove.clear();
2076
2077 // Effect chains will be actually deleted here if they were removed from
2078 // mEffectChains list during mixing or effects processing
2079 effectChains.clear();
2080 }
2081
2082 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002083 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 }
2085
Eric Laurentfeb0db62011-07-22 09:04:31 -07002086 releaseWakeLock();
2087
Steve Block3856b092011-10-20 11:56:00 +01002088 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 return false;
2090}
2091
2092// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002093AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2094 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095{
2096
Glenn Kasten29c23c32012-01-26 13:37:52 -08002097 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002098 // find out which tracks need to be processed
2099 size_t count = activeTracks.size();
2100 size_t mixedTracks = 0;
2101 size_t tracksWithEffect = 0;
2102
2103 float masterVolume = mMasterVolume;
2104 bool masterMute = mMasterMute;
2105
Eric Laurent571d49c2010-08-11 05:20:11 -07002106 if (masterMute) {
2107 masterVolume = 0;
2108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002110 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002112 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002113 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002114 masterVolume = (float)((v + (1 << 23)) >> 24);
2115 chain.clear();
2116 }
2117
2118 for (size_t i=0 ; i<count ; i++) {
2119 sp<Track> t = activeTracks[i].promote();
2120 if (t == 0) continue;
2121
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002122 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 Track* const track = t.get();
2124 audio_track_cblk_t* cblk = track->cblk();
2125
2126 // The first time a track is added we wait
2127 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002128 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002129 // make sure that we have enough frames to mix one full buffer.
2130 // enforce this condition only once to enable draining the buffer in case the client
2131 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002132 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002133 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002134 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002135 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002136 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002137 if (t->sampleRate() == (int)mSampleRate) {
2138 minFrames = mFrameCount;
2139 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002140 // +1 for rounding and +1 for additional sample needed for interpolation
2141 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2142 // add frames already consumed but not yet released by the resampler
2143 // because cblk->framesReady() will include these frames
2144 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2145 // the minimum track buffer size is normally twice the number of frames necessary
2146 // to fill one buffer and the resampler should not leave more than one buffer worth
2147 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002148 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002149 }
2150 }
2151 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 !track->isPaused() && !track->isTerminated())
2153 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002154 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155
2156 mixedTracks++;
2157
2158 // track->mainBuffer() != mMixBuffer means there is an effect chain
2159 // connected to the track
2160 chain.clear();
2161 if (track->mainBuffer() != mMixBuffer) {
2162 chain = getEffectChain_l(track->sessionId());
2163 // Delegate volume control to effect in track effect chain if needed
2164 if (chain != 0) {
2165 tracksWithEffect++;
2166 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002167 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002168 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 }
2170 }
2171
2172
2173 int param = AudioMixer::VOLUME;
2174 if (track->mFillingUpStatus == Track::FS_FILLED) {
2175 // no ramp for the first volume setting
2176 track->mFillingUpStatus = Track::FS_ACTIVE;
2177 if (track->mState == TrackBase::RESUMING) {
2178 track->mState = TrackBase::ACTIVE;
2179 param = AudioMixer::RAMP_VOLUME;
2180 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002181 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 } else if (cblk->server != 0) {
2183 // If the track is stopped before the first frame was mixed,
2184 // do not apply ramp
2185 param = AudioMixer::RAMP_VOLUME;
2186 }
2187
2188 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002189 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002190 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002192 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 if (track->isPausing()) {
2194 track->setPaused();
2195 }
2196 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002197
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198 // read original volumes with volume control
2199 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002201 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002202 vl = vlr & 0xFFFF;
2203 vr = vlr >> 16;
2204 // track volumes come from shared memory, so can't be trusted and must be clamped
2205 if (vl > MAX_GAIN_INT) {
2206 ALOGV("Track left volume out of range: %04X", vl);
2207 vl = MAX_GAIN_INT;
2208 }
2209 if (vr > MAX_GAIN_INT) {
2210 ALOGV("Track right volume out of range: %04X", vr);
2211 vr = MAX_GAIN_INT;
2212 }
2213 // now apply the master volume and stream type volume
2214 vl = (uint32_t)(v * vl) << 12;
2215 vr = (uint32_t)(v * vr) << 12;
2216 // assuming master volume and stream type volume each go up to 1.0,
2217 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218
Glenn Kasten05632a52012-01-03 14:22:33 -08002219 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2220 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002221 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002222 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002223 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002224 }
2225 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002227 // Delegate volume control to effect in track effect chain if needed
2228 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2229 // Do not ramp volume if volume is controlled by effect
2230 param = AudioMixer::VOLUME;
2231 track->mHasVolumeController = true;
2232 } else {
2233 // force no volume ramp when volume controller was just disabled or removed
2234 // from effect chain to avoid volume spike
2235 if (track->mHasVolumeController) {
2236 param = AudioMixer::VOLUME;
2237 }
2238 track->mHasVolumeController = false;
2239 }
2240
2241 // Convert volumes from 8.24 to 4.12 format
2242 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002243 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002244 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2245 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2246 left = int16_t(v_clamped);
2247 v_clamped = (vr + (1 << 11)) >> 12;
2248 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2249 right = int16_t(v_clamped);
2250
2251 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2252 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002255 mAudioMixer->setBufferProvider(name, track);
2256 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002258 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2259 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2260 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002262 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 AudioMixer::TRACK,
2264 AudioMixer::FORMAT, (void *)track->format());
2265 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002266 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002268 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002270 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271 AudioMixer::RESAMPLE,
2272 AudioMixer::SAMPLE_RATE,
2273 (void *)(cblk->sampleRate));
2274 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002275 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 AudioMixer::TRACK,
2277 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2278 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002279 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 AudioMixer::TRACK,
2281 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2282
2283 // reset retry count
2284 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002285 // If one track is ready, set the mixer ready if:
2286 // - the mixer was not ready during previous round OR
2287 // - no other track is not ready
2288 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2289 mixerStatus != MIXER_TRACKS_ENABLED) {
2290 mixerStatus = MIXER_TRACKS_READY;
2291 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002293 //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 -07002294 if (track->isStopped()) {
2295 track->reset();
2296 }
2297 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2298 // We have consumed all the buffers of this track.
2299 // Remove it from the list of active tracks.
2300 tracksToRemove->add(track);
2301 } else {
2302 // No buffers for this track. Give it a few chances to
2303 // fill a buffer, then remove it from active list.
2304 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002305 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002307 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002308 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002309 // If one track is not ready, mark the mixer also not ready if:
2310 // - the mixer was ready during previous round OR
2311 // - no other track is ready
2312 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2313 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314 mixerStatus = MIXER_TRACKS_ENABLED;
2315 }
2316 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002317 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319 }
2320
2321 // remove all the tracks that need to be...
2322 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002323 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 for (size_t i=0 ; i<count ; i++) {
2325 const sp<Track>& track = tracksToRemove->itemAt(i);
2326 mActiveTracks.remove(track);
2327 if (track->mainBuffer() != mMixBuffer) {
2328 chain = getEffectChain_l(track->sessionId());
2329 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002330 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002331 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 }
2333 }
2334 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002335 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 }
2337 }
2338 }
2339
2340 // mix buffer must be cleared if all tracks are connected to an
2341 // effect chain as in this case the mixer will not write to
2342 // mix buffer and track effects will accumulate into it
2343 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2344 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2345 }
2346
Eric Laurent27741442012-01-17 19:20:12 -08002347 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 return mixerStatus;
2349}
2350
Glenn Kastenfff6d712012-01-12 16:38:12 -08002351void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352{
Steve Block3856b092011-10-20 11:56:00 +01002353 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002354 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002355 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002356
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 size_t size = mTracks.size();
2358 for (size_t i = 0; i < size; i++) {
2359 sp<Track> t = mTracks[i];
2360 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002361 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002362 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002363 }
2364 }
2365}
2366
Glenn Kastenfff6d712012-01-12 16:38:12 -08002367void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002368{
Steve Block3856b092011-10-20 11:56:00 +01002369 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002370 this, streamType, valid);
2371 Mutex::Autolock _l(mLock);
2372
2373 mStreamTypes[streamType].valid = valid;
2374}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002375
2376// getTrackName_l() must be called with ThreadBase::mLock held
2377int AudioFlinger::MixerThread::getTrackName_l()
2378{
2379 return mAudioMixer->getTrackName();
2380}
2381
2382// deleteTrackName_l() must be called with ThreadBase::mLock held
2383void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2384{
Steve Block3856b092011-10-20 11:56:00 +01002385 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 mAudioMixer->deleteTrackName(name);
2387}
2388
2389// checkForNewParameters_l() must be called with ThreadBase::mLock held
2390bool AudioFlinger::MixerThread::checkForNewParameters_l()
2391{
2392 bool reconfig = false;
2393
2394 while (!mNewParameters.isEmpty()) {
2395 status_t status = NO_ERROR;
2396 String8 keyValuePair = mNewParameters[0];
2397 AudioParameter param = AudioParameter(keyValuePair);
2398 int value;
2399
2400 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2401 reconfig = true;
2402 }
2403 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002404 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002405 status = BAD_VALUE;
2406 } else {
2407 reconfig = true;
2408 }
2409 }
2410 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002411 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002412 status = BAD_VALUE;
2413 } else {
2414 reconfig = true;
2415 }
2416 }
2417 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2418 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002419 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 // if frame count is changed after track creation
2421 if (!mTracks.isEmpty()) {
2422 status = INVALID_OPERATION;
2423 } else {
2424 reconfig = true;
2425 }
2426 }
2427 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002428 // when changing the audio output device, call addBatteryData to notify
2429 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002430 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002431 uint32_t params = 0;
2432 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002433 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002434 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2435 }
2436
2437 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002438 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002439 // check if any other device (except speaker) is on
2440 if (value & deviceWithoutSpeaker ) {
2441 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2442 }
2443
2444 if (params != 0) {
2445 addBatteryData(params);
2446 }
2447 }
2448
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449 // forward device change to effects that have requested to be
2450 // aware of attached audio device.
2451 mDevice = (uint32_t)value;
2452 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002453 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 }
2455 }
2456
2457 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002458 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002459 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002461 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 mStandby = true;
2463 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002464 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002465 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466 }
2467 if (status == NO_ERROR && reconfig) {
2468 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002469 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2470 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471 readOutputParameters();
2472 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2473 for (size_t i = 0; i < mTracks.size() ; i++) {
2474 int name = getTrackName_l();
2475 if (name < 0) break;
2476 mTracks[i]->mName = name;
2477 // limit track sample rate to 2 x new output sample rate
2478 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2479 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2480 }
2481 }
2482 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2483 }
2484 }
2485
2486 mNewParameters.removeAt(0);
2487
2488 mParamStatus = status;
2489 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002490 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2491 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002492 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 }
2494 return reconfig;
2495}
2496
2497status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2498{
2499 const size_t SIZE = 256;
2500 char buffer[SIZE];
2501 String8 result;
2502
2503 PlaybackThread::dumpInternals(fd, args);
2504
2505 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2506 result.append(buffer);
2507 write(fd, result.string(), result.size());
2508 return NO_ERROR;
2509}
2510
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2512{
Eric Laurent60e18242010-07-29 06:50:24 -07002513 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514}
2515
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002516uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2517{
2518 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2519}
2520
Mathias Agopian65ab4712010-07-14 17:59:35 -07002521// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002522AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002523 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002524 // mLeftVolFloat, mRightVolFloat
2525 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527}
2528
2529AudioFlinger::DirectOutputThread::~DirectOutputThread()
2530{
2531}
2532
Mathias Agopian65ab4712010-07-14 17:59:35 -07002533static inline
2534int32_t mul(int16_t in, int16_t v)
2535{
2536#if defined(__arm__) && !defined(__thumb__)
2537 int32_t out;
2538 asm( "smulbb %[out], %[in], %[v] \n"
2539 : [out]"=r"(out)
2540 : [in]"%r"(in), [v]"r"(v)
2541 : );
2542 return out;
2543#else
2544 return in * int32_t(v);
2545#endif
2546}
2547
2548void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2549{
2550 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002551 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 return;
2553 }
2554
2555 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002556 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 size_t count = mFrameCount * mChannelCount;
2558 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2559 int16_t *dst = mMixBuffer + count-1;
2560 while(count--) {
2561 *dst-- = (int16_t)(*src--^0x80) << 8;
2562 }
2563 }
2564
2565 size_t frameCount = mFrameCount;
2566 int16_t *out = mMixBuffer;
2567 if (ramp) {
2568 if (mChannelCount == 1) {
2569 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2570 int32_t vlInc = d / (int32_t)frameCount;
2571 int32_t vl = ((int32_t)mLeftVolShort << 16);
2572 do {
2573 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2574 out++;
2575 vl += vlInc;
2576 } while (--frameCount);
2577
2578 } else {
2579 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2580 int32_t vlInc = d / (int32_t)frameCount;
2581 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2582 int32_t vrInc = d / (int32_t)frameCount;
2583 int32_t vl = ((int32_t)mLeftVolShort << 16);
2584 int32_t vr = ((int32_t)mRightVolShort << 16);
2585 do {
2586 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2587 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2588 out += 2;
2589 vl += vlInc;
2590 vr += vrInc;
2591 } while (--frameCount);
2592 }
2593 } else {
2594 if (mChannelCount == 1) {
2595 do {
2596 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2597 out++;
2598 } while (--frameCount);
2599 } else {
2600 do {
2601 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2602 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2603 out += 2;
2604 } while (--frameCount);
2605 }
2606 }
2607
2608 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002609 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610 size_t count = mFrameCount * mChannelCount;
2611 int16_t *src = mMixBuffer;
2612 uint8_t *dst = (uint8_t *)mMixBuffer;
2613 while(count--) {
2614 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2615 }
2616 }
2617
2618 mLeftVolShort = leftVol;
2619 mRightVolShort = rightVol;
2620}
2621
2622bool AudioFlinger::DirectOutputThread::threadLoop()
2623{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002624 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002625 sp<Track> trackToRemove;
2626 sp<Track> activeTrack;
2627 nsecs_t standbyTime = systemTime();
2628 int8_t *curBuf;
2629 size_t mixBufferSize = mFrameCount*mFrameSize;
2630 uint32_t activeSleepTime = activeSleepTimeUs();
2631 uint32_t idleSleepTime = idleSleepTimeUs();
2632 uint32_t sleepTime = idleSleepTime;
2633 // use shorter standby delay as on normal output to release
2634 // hardware resources as soon as possible
2635 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2636
Eric Laurentfeb0db62011-07-22 09:04:31 -07002637 acquireWakeLock();
2638
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 while (!exitPending())
2640 {
2641 bool rampVolume;
2642 uint16_t leftVol;
2643 uint16_t rightVol;
2644 Vector< sp<EffectChain> > effectChains;
2645
2646 processConfigEvents();
2647
2648 mixerStatus = MIXER_IDLE;
2649
2650 { // scope for the mLock
2651
2652 Mutex::Autolock _l(mLock);
2653
2654 if (checkForNewParameters_l()) {
2655 mixBufferSize = mFrameCount*mFrameSize;
2656 activeSleepTime = activeSleepTimeUs();
2657 idleSleepTime = idleSleepTimeUs();
2658 standbyDelay = microseconds(activeSleepTime*2);
2659 }
2660
2661 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002662 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2663 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 // wait until we have something to do...
2665 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002666 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002667 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002668 mStandby = true;
2669 mBytesWritten = 0;
2670 }
2671
2672 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2673 // we're about to wait, flush the binder command buffer
2674 IPCThreadState::self()->flushCommands();
2675
2676 if (exitPending()) break;
2677
Eric Laurentfeb0db62011-07-22 09:04:31 -07002678 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002679 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002681 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002682 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002683
Glenn Kastenf1d45922012-01-13 15:54:24 -08002684 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002685 char value[PROPERTY_VALUE_MAX];
2686 property_get("ro.audio.silent", value, "0");
2687 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002688 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 setMasterMute(true);
2690 }
2691 }
2692
2693 standbyTime = systemTime() + standbyDelay;
2694 sleepTime = idleSleepTime;
2695 continue;
2696 }
2697 }
2698
2699 effectChains = mEffectChains;
2700
2701 // find out which tracks need to be processed
2702 if (mActiveTracks.size() != 0) {
2703 sp<Track> t = mActiveTracks[0].promote();
2704 if (t == 0) continue;
2705
2706 Track* const track = t.get();
2707 audio_track_cblk_t* cblk = track->cblk();
2708
2709 // The first time a track is added we wait
2710 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002711 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002712 !track->isPaused() && !track->isTerminated())
2713 {
Steve Block3856b092011-10-20 11:56:00 +01002714 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002715
2716 if (track->mFillingUpStatus == Track::FS_FILLED) {
2717 track->mFillingUpStatus = Track::FS_ACTIVE;
2718 mLeftVolFloat = mRightVolFloat = 0;
2719 mLeftVolShort = mRightVolShort = 0;
2720 if (track->mState == TrackBase::RESUMING) {
2721 track->mState = TrackBase::ACTIVE;
2722 rampVolume = true;
2723 }
2724 } else if (cblk->server != 0) {
2725 // If the track is stopped before the first frame was mixed,
2726 // do not apply ramp
2727 rampVolume = true;
2728 }
2729 // compute volume for this track
2730 float left, right;
2731 if (track->isMuted() || mMasterMute || track->isPausing() ||
2732 mStreamTypes[track->type()].mute) {
2733 left = right = 0;
2734 if (track->isPausing()) {
2735 track->setPaused();
2736 }
2737 } else {
2738 float typeVolume = mStreamTypes[track->type()].volume;
2739 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002740 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002741 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2743 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002744 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2746 right = v_clamped/MAX_GAIN;
2747 }
2748
2749 if (left != mLeftVolFloat || right != mRightVolFloat) {
2750 mLeftVolFloat = left;
2751 mRightVolFloat = right;
2752
2753 // If audio HAL implements volume control,
2754 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002755 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 left = 1.0f;
2757 right = 1.0f;
2758 }
2759
2760 // Convert volumes from float to 8.24
2761 uint32_t vl = (uint32_t)(left * (1 << 24));
2762 uint32_t vr = (uint32_t)(right * (1 << 24));
2763
2764 // Delegate volume control to effect in track effect chain if needed
2765 // only one effect chain can be present on DirectOutputThread, so if
2766 // there is one, the track is connected to it
2767 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002768 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002769 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 rampVolume = false;
2771 }
2772 }
2773
2774 // Convert volumes from 8.24 to 4.12 format
2775 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2776 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2777 leftVol = (uint16_t)v_clamped;
2778 v_clamped = (vr + (1 << 11)) >> 12;
2779 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2780 rightVol = (uint16_t)v_clamped;
2781 } else {
2782 leftVol = mLeftVolShort;
2783 rightVol = mRightVolShort;
2784 rampVolume = false;
2785 }
2786
2787 // reset retry count
2788 track->mRetryCount = kMaxTrackRetriesDirect;
2789 activeTrack = t;
2790 mixerStatus = MIXER_TRACKS_READY;
2791 } else {
Steve Block3856b092011-10-20 11:56:00 +01002792 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 if (track->isStopped()) {
2794 track->reset();
2795 }
2796 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2797 // We have consumed all the buffers of this track.
2798 // Remove it from the list of active tracks.
2799 trackToRemove = track;
2800 } else {
2801 // No buffers for this track. Give it a few chances to
2802 // fill a buffer, then remove it from active list.
2803 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002804 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 trackToRemove = track;
2806 } else {
2807 mixerStatus = MIXER_TRACKS_ENABLED;
2808 }
2809 }
2810 }
2811 }
2812
2813 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002814 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 mActiveTracks.remove(trackToRemove);
2816 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002817 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002818 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002819 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 }
2821 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002822 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 }
2824 }
2825
Eric Laurentde070132010-07-13 04:45:46 -07002826 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 }
2828
Glenn Kastenf6b16782011-12-15 09:51:17 -08002829 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 AudioBufferProvider::Buffer buffer;
2831 size_t frameCount = mFrameCount;
2832 curBuf = (int8_t *)mMixBuffer;
2833 // output audio to hardware
2834 while (frameCount) {
2835 buffer.frameCount = frameCount;
2836 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002837 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 memset(curBuf, 0, frameCount * mFrameSize);
2839 break;
2840 }
2841 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2842 frameCount -= buffer.frameCount;
2843 curBuf += buffer.frameCount * mFrameSize;
2844 activeTrack->releaseBuffer(&buffer);
2845 }
2846 sleepTime = 0;
2847 standbyTime = systemTime() + standbyDelay;
2848 } else {
2849 if (sleepTime == 0) {
2850 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2851 sleepTime = activeSleepTime;
2852 } else {
2853 sleepTime = idleSleepTime;
2854 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002855 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2857 sleepTime = 0;
2858 }
2859 }
2860
2861 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002862 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002863 }
2864 // sleepTime == 0 means we must write to audio hardware
2865 if (sleepTime == 0) {
2866 if (mixerStatus == MIXER_TRACKS_READY) {
2867 applyVolume(leftVol, rightVol, rampVolume);
2868 }
2869 for (size_t i = 0; i < effectChains.size(); i ++) {
2870 effectChains[i]->process_l();
2871 }
Eric Laurentde070132010-07-13 04:45:46 -07002872 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002873
2874 mLastWriteTime = systemTime();
2875 mInWrite = true;
2876 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002877 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2879 mNumWrites++;
2880 mInWrite = false;
2881 mStandby = false;
2882 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002883 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 usleep(sleepTime);
2885 }
2886
2887 // finally let go of removed track, without the lock held
2888 // since we can't guarantee the destructors won't acquire that
2889 // same lock.
2890 trackToRemove.clear();
2891 activeTrack.clear();
2892
2893 // Effect chains will be actually deleted here if they were removed from
2894 // mEffectChains list during mixing or effects processing
2895 effectChains.clear();
2896 }
2897
2898 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002899 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 }
2901
Eric Laurentfeb0db62011-07-22 09:04:31 -07002902 releaseWakeLock();
2903
Steve Block3856b092011-10-20 11:56:00 +01002904 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 return false;
2906}
2907
2908// getTrackName_l() must be called with ThreadBase::mLock held
2909int AudioFlinger::DirectOutputThread::getTrackName_l()
2910{
2911 return 0;
2912}
2913
2914// deleteTrackName_l() must be called with ThreadBase::mLock held
2915void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2916{
2917}
2918
2919// checkForNewParameters_l() must be called with ThreadBase::mLock held
2920bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2921{
2922 bool reconfig = false;
2923
2924 while (!mNewParameters.isEmpty()) {
2925 status_t status = NO_ERROR;
2926 String8 keyValuePair = mNewParameters[0];
2927 AudioParameter param = AudioParameter(keyValuePair);
2928 int value;
2929
2930 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2931 // do not accept frame count changes if tracks are open as the track buffer
2932 // size depends on frame count and correct behavior would not be garantied
2933 // if frame count is changed after track creation
2934 if (!mTracks.isEmpty()) {
2935 status = INVALID_OPERATION;
2936 } else {
2937 reconfig = true;
2938 }
2939 }
2940 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002941 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002942 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002943 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002944 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002945 mStandby = true;
2946 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002947 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002948 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 }
2950 if (status == NO_ERROR && reconfig) {
2951 readOutputParameters();
2952 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2953 }
2954 }
2955
2956 mNewParameters.removeAt(0);
2957
2958 mParamStatus = status;
2959 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002960 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2961 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002962 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002963 }
2964 return reconfig;
2965}
2966
2967uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2968{
2969 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002970 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002971 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 } else {
2973 time = 10000;
2974 }
2975 return time;
2976}
2977
2978uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2979{
2980 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002981 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002982 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983 } else {
2984 time = 10000;
2985 }
2986 return time;
2987}
2988
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002989uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2990{
2991 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002992 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002993 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2994 } else {
2995 time = 10000;
2996 }
2997 return time;
2998}
2999
3000
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001// ----------------------------------------------------------------------------
3002
Glenn Kasten23bb8be2012-01-26 10:38:26 -08003003AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
3004 AudioFlinger::MixerThread* mainThread, int id)
3005 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
3006 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007{
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 addOutputTrack(mainThread);
3009}
3010
3011AudioFlinger::DuplicatingThread::~DuplicatingThread()
3012{
3013 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3014 mOutputTracks[i]->destroy();
3015 }
3016 mOutputTracks.clear();
3017}
3018
3019bool AudioFlinger::DuplicatingThread::threadLoop()
3020{
3021 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08003022 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 nsecs_t standbyTime = systemTime();
3024 size_t mixBufferSize = mFrameCount*mFrameSize;
3025 SortedVector< sp<OutputTrack> > outputTracks;
3026 uint32_t writeFrames = 0;
3027 uint32_t activeSleepTime = activeSleepTimeUs();
3028 uint32_t idleSleepTime = idleSleepTimeUs();
3029 uint32_t sleepTime = idleSleepTime;
3030 Vector< sp<EffectChain> > effectChains;
3031
Eric Laurentfeb0db62011-07-22 09:04:31 -07003032 acquireWakeLock();
3033
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034 while (!exitPending())
3035 {
3036 processConfigEvents();
3037
3038 mixerStatus = MIXER_IDLE;
3039 { // scope for the mLock
3040
3041 Mutex::Autolock _l(mLock);
3042
3043 if (checkForNewParameters_l()) {
3044 mixBufferSize = mFrameCount*mFrameSize;
3045 updateWaitTime();
3046 activeSleepTime = activeSleepTimeUs();
3047 idleSleepTime = idleSleepTimeUs();
3048 }
3049
3050 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3051
3052 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3053 outputTracks.add(mOutputTracks[i]);
3054 }
3055
3056 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003057 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3058 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 if (!mStandby) {
3060 for (size_t i = 0; i < outputTracks.size(); i++) {
3061 outputTracks[i]->stop();
3062 }
3063 mStandby = true;
3064 mBytesWritten = 0;
3065 }
3066
3067 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3068 // we're about to wait, flush the binder command buffer
3069 IPCThreadState::self()->flushCommands();
3070 outputTracks.clear();
3071
3072 if (exitPending()) break;
3073
Eric Laurentfeb0db62011-07-22 09:04:31 -07003074 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003075 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003077 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003078 acquireWakeLock_l();
3079
Eric Laurent27741442012-01-17 19:20:12 -08003080 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003081 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003082 char value[PROPERTY_VALUE_MAX];
3083 property_get("ro.audio.silent", value, "0");
3084 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003085 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 setMasterMute(true);
3087 }
3088 }
3089
3090 standbyTime = systemTime() + kStandbyTimeInNsecs;
3091 sleepTime = idleSleepTime;
3092 continue;
3093 }
3094 }
3095
3096 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3097
3098 // prevent any changes in effect chain list and in each effect chain
3099 // during mixing and effect process as the audio buffers could be deleted
3100 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003101 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102 }
3103
Glenn Kastenf6b16782011-12-15 09:51:17 -08003104 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003105 // mix buffers...
3106 if (outputsReady(outputTracks)) {
3107 mAudioMixer->process();
3108 } else {
3109 memset(mMixBuffer, 0, mixBufferSize);
3110 }
3111 sleepTime = 0;
3112 writeFrames = mFrameCount;
3113 } else {
3114 if (sleepTime == 0) {
3115 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3116 sleepTime = activeSleepTime;
3117 } else {
3118 sleepTime = idleSleepTime;
3119 }
3120 } else if (mBytesWritten != 0) {
3121 // flush remaining overflow buffers in output tracks
3122 for (size_t i = 0; i < outputTracks.size(); i++) {
3123 if (outputTracks[i]->isActive()) {
3124 sleepTime = 0;
3125 writeFrames = 0;
3126 memset(mMixBuffer, 0, mixBufferSize);
3127 break;
3128 }
3129 }
3130 }
3131 }
3132
3133 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003134 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 }
3136 // sleepTime == 0 means we must write to audio hardware
3137 if (sleepTime == 0) {
3138 for (size_t i = 0; i < effectChains.size(); i ++) {
3139 effectChains[i]->process_l();
3140 }
3141 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003142 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143
3144 standbyTime = systemTime() + kStandbyTimeInNsecs;
3145 for (size_t i = 0; i < outputTracks.size(); i++) {
3146 outputTracks[i]->write(mMixBuffer, writeFrames);
3147 }
3148 mStandby = false;
3149 mBytesWritten += mixBufferSize;
3150 } else {
3151 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003152 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 usleep(sleepTime);
3154 }
3155
3156 // finally let go of all our tracks, without the lock held
3157 // since we can't guarantee the destructors won't acquire that
3158 // same lock.
3159 tracksToRemove.clear();
3160 outputTracks.clear();
3161
3162 // Effect chains will be actually deleted here if they were removed from
3163 // mEffectChains list during mixing or effects processing
3164 effectChains.clear();
3165 }
3166
Eric Laurentfeb0db62011-07-22 09:04:31 -07003167 releaseWakeLock();
3168
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 return false;
3170}
3171
3172void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3173{
3174 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3175 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3176 this,
3177 mSampleRate,
3178 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003179 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003180 frameCount);
3181 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003182 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003184 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003185 updateWaitTime();
3186 }
3187}
3188
3189void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3190{
3191 Mutex::Autolock _l(mLock);
3192 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3193 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3194 mOutputTracks[i]->destroy();
3195 mOutputTracks.removeAt(i);
3196 updateWaitTime();
3197 return;
3198 }
3199 }
Steve Block3856b092011-10-20 11:56:00 +01003200 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201}
3202
3203void AudioFlinger::DuplicatingThread::updateWaitTime()
3204{
3205 mWaitTimeMs = UINT_MAX;
3206 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3207 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003208 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3210 if (waitTimeMs < mWaitTimeMs) {
3211 mWaitTimeMs = waitTimeMs;
3212 }
3213 }
3214 }
3215}
3216
3217
3218bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3219{
3220 for (size_t i = 0; i < outputTracks.size(); i++) {
3221 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3222 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003223 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224 return false;
3225 }
3226 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3227 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003228 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003229 return false;
3230 }
3231 }
3232 return true;
3233}
3234
3235uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3236{
3237 return (mWaitTimeMs * 1000) / 2;
3238}
3239
3240// ----------------------------------------------------------------------------
3241
3242// TrackBase constructor must be called with AudioFlinger::mLock held
3243AudioFlinger::ThreadBase::TrackBase::TrackBase(
3244 const wp<ThreadBase>& thread,
3245 const sp<Client>& client,
3246 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003247 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003248 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 int frameCount,
3250 uint32_t flags,
3251 const sp<IMemory>& sharedBuffer,
3252 int sessionId)
3253 : RefBase(),
3254 mThread(thread),
3255 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003256 mCblk(NULL),
3257 // mBuffer
3258 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mFrameCount(0),
3260 mState(IDLE),
3261 mClientTid(-1),
3262 mFormat(format),
3263 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3264 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003265 // mChannelCount
3266 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267{
Steve Block3856b092011-10-20 11:56:00 +01003268 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269
Steve Blockb8a80522011-12-20 16:23:08 +00003270 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003272 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3274 if (sharedBuffer == 0) {
3275 size += bufferSize;
3276 }
3277
3278 if (client != NULL) {
3279 mCblkMemory = client->heap()->allocate(size);
3280 if (mCblkMemory != 0) {
3281 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003282 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 new(mCblk) audio_track_cblk_t();
3284 // clear all buffers
3285 mCblk->frameCount = frameCount;
3286 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003287 mChannelCount = channelCount;
3288 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003289 if (sharedBuffer == 0) {
3290 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3291 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3292 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003293 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294 mCblk->flags = CBLK_UNDERRUN_ON;
3295 } else {
3296 mBuffer = sharedBuffer->pointer();
3297 }
3298 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3299 }
3300 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003301 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 client->heap()->dump("AudioTrack");
3303 return;
3304 }
3305 } else {
3306 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003307 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 new(mCblk) audio_track_cblk_t();
3309 // clear all buffers
3310 mCblk->frameCount = frameCount;
3311 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003312 mChannelCount = channelCount;
3313 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003314 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3315 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3316 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003317 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 mCblk->flags = CBLK_UNDERRUN_ON;
3319 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003320 }
3321}
3322
3323AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3324{
Glenn Kastena0d68332012-01-27 16:47:15 -08003325 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3327 if (mClient == NULL) {
3328 delete mCblk;
3329 }
3330 }
3331 mCblkMemory.clear(); // and free the shared memory
Glenn Kasten7378ca52012-01-20 13:44:40 -08003332 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003333 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003334 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003335 // If the client's reference count drops to zero, the associated destructor
3336 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3337 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 mClient.clear();
3339 }
3340}
3341
3342void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3343{
Glenn Kastene0feee32011-12-13 11:53:26 -08003344 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 mFrameCount = buffer->frameCount;
3346 step();
3347 buffer->frameCount = 0;
3348}
3349
3350bool AudioFlinger::ThreadBase::TrackBase::step() {
3351 bool result;
3352 audio_track_cblk_t* cblk = this->cblk();
3353
3354 result = cblk->stepServer(mFrameCount);
3355 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003356 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003357 mFlags |= STEPSERVER_FAILED;
3358 }
3359 return result;
3360}
3361
3362void AudioFlinger::ThreadBase::TrackBase::reset() {
3363 audio_track_cblk_t* cblk = this->cblk();
3364
3365 cblk->user = 0;
3366 cblk->server = 0;
3367 cblk->userBase = 0;
3368 cblk->serverBase = 0;
3369 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003370 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371}
3372
3373sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3374{
3375 return mCblkMemory;
3376}
3377
3378int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3379 return (int)mCblk->sampleRate;
3380}
3381
3382int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003383 return (const int)mChannelCount;
3384}
3385
3386uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3387 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388}
3389
3390void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3391 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003392 size_t frameSize = cblk->frameSize;
3393 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3394 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395
3396 // Check validity of returned pointer in case the track control block would have been corrupted.
3397 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003398 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003399 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 -07003400 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003402 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003403 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 }
3405
3406 return bufferStart;
3407}
3408
3409// ----------------------------------------------------------------------------
3410
3411// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3412AudioFlinger::PlaybackThread::Track::Track(
3413 const wp<ThreadBase>& thread,
3414 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003415 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003416 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003417 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003418 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 int frameCount,
3420 const sp<IMemory>& sharedBuffer,
3421 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003422 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003423 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3424 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425{
3426 if (mCblk != NULL) {
3427 sp<ThreadBase> baseThread = thread.promote();
3428 if (baseThread != 0) {
3429 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3430 mName = playbackThread->getTrackName_l();
3431 mMainBuffer = playbackThread->mixBuffer();
3432 }
Steve Block3856b092011-10-20 11:56:00 +01003433 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003435 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 mStreamType = streamType;
3438 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3439 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003440 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 }
3442}
3443
3444AudioFlinger::PlaybackThread::Track::~Track()
3445{
Steve Block3856b092011-10-20 11:56:00 +01003446 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 sp<ThreadBase> thread = mThread.promote();
3448 if (thread != 0) {
3449 Mutex::Autolock _l(thread->mLock);
3450 mState = TERMINATED;
3451 }
3452}
3453
3454void AudioFlinger::PlaybackThread::Track::destroy()
3455{
3456 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3457 // by removing it from mTracks vector, so there is a risk that this Tracks's
3458 // desctructor is called. As the destructor needs to lock mLock,
3459 // we must acquire a strong reference on this Track before locking mLock
3460 // here so that the destructor is called only when exiting this function.
3461 // On the other hand, as long as Track::destroy() is only called by
3462 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3463 // this Track with its member mTrack.
3464 sp<Track> keep(this);
3465 { // scope for mLock
3466 sp<ThreadBase> thread = mThread.promote();
3467 if (thread != 0) {
3468 if (!isOutputTrack()) {
3469 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003470 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003471 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003472 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003473
3474 // to track the speaker usage
3475 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003476 }
3477 AudioSystem::releaseOutput(thread->id());
3478 }
3479 Mutex::Autolock _l(thread->mLock);
3480 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3481 playbackThread->destroyTrack_l(this);
3482 }
3483 }
3484}
3485
3486void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3487{
Glenn Kasten83d86532012-01-17 14:39:34 -08003488 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003489 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 -07003490 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003491 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 mStreamType,
3493 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003494 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 mSessionId,
3496 mFrameCount,
3497 mState,
3498 mMute,
3499 mFillingUpStatus,
3500 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003501 vlr & 0xFFFF,
3502 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 mCblk->server,
3504 mCblk->user,
3505 (int)mMainBuffer,
3506 (int)mAuxBuffer);
3507}
3508
3509status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3510{
3511 audio_track_cblk_t* cblk = this->cblk();
3512 uint32_t framesReady;
3513 uint32_t framesReq = buffer->frameCount;
3514
3515 // Check if last stepServer failed, try to step now
3516 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3517 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003518 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3520 }
3521
3522 framesReady = cblk->framesReady();
3523
Glenn Kastenf6b16782011-12-15 09:51:17 -08003524 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 uint32_t s = cblk->server;
3526 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3527
3528 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3529 if (framesReq > framesReady) {
3530 framesReq = framesReady;
3531 }
3532 if (s + framesReq > bufferEnd) {
3533 framesReq = bufferEnd - s;
3534 }
3535
3536 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003537 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538
3539 buffer->frameCount = framesReq;
3540 return NO_ERROR;
3541 }
3542
3543getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003544 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003546 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 return NOT_ENOUGH_DATA;
3548}
3549
3550bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003551 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552
3553 if (mCblk->framesReady() >= mCblk->frameCount ||
3554 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3555 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003556 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557 return true;
3558 }
3559 return false;
3560}
3561
3562status_t AudioFlinger::PlaybackThread::Track::start()
3563{
3564 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003565 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003566 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 sp<ThreadBase> thread = mThread.promote();
3568 if (thread != 0) {
3569 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003570 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 // here the track could be either new, or restarted
3572 // in both cases "unstop" the track
3573 if (mState == PAUSED) {
3574 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003575 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 } else {
3577 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003578 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579 }
3580
3581 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3582 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003583 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003584 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003585 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003587
3588 // to track the speaker usage
3589 if (status == NO_ERROR) {
3590 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592 }
3593 if (status == NO_ERROR) {
3594 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3595 playbackThread->addTrack_l(this);
3596 } else {
3597 mState = state;
3598 }
3599 } else {
3600 status = BAD_VALUE;
3601 }
3602 return status;
3603}
3604
3605void AudioFlinger::PlaybackThread::Track::stop()
3606{
Steve Block3856b092011-10-20 11:56:00 +01003607 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 sp<ThreadBase> thread = mThread.promote();
3609 if (thread != 0) {
3610 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003611 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 if (mState > STOPPED) {
3613 mState = STOPPED;
3614 // If the track is not active (PAUSED and buffers full), flush buffers
3615 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3616 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3617 reset();
3618 }
Steve Block3856b092011-10-20 11:56:00 +01003619 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 }
3621 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3622 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003623 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003624 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003625 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003627
3628 // to track the speaker usage
3629 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 }
3631 }
3632}
3633
3634void AudioFlinger::PlaybackThread::Track::pause()
3635{
Steve Block3856b092011-10-20 11:56:00 +01003636 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 sp<ThreadBase> thread = mThread.promote();
3638 if (thread != 0) {
3639 Mutex::Autolock _l(thread->mLock);
3640 if (mState == ACTIVE || mState == RESUMING) {
3641 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003642 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643 if (!isOutputTrack()) {
3644 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003645 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003646 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003647 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003649
3650 // to track the speaker usage
3651 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003652 }
3653 }
3654 }
3655}
3656
3657void AudioFlinger::PlaybackThread::Track::flush()
3658{
Steve Block3856b092011-10-20 11:56:00 +01003659 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660 sp<ThreadBase> thread = mThread.promote();
3661 if (thread != 0) {
3662 Mutex::Autolock _l(thread->mLock);
3663 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3664 return;
3665 }
3666 // No point remaining in PAUSED state after a flush => go to
3667 // STOPPED state
3668 mState = STOPPED;
3669
Eric Laurent38ccae22011-03-28 18:37:07 -07003670 // do not reset the track if it is still in the process of being stopped or paused.
3671 // this will be done by prepareTracks_l() when the track is stopped.
3672 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3673 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3674 reset();
3675 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676 }
3677}
3678
3679void AudioFlinger::PlaybackThread::Track::reset()
3680{
3681 // Do not reset twice to avoid discarding data written just after a flush and before
3682 // the audioflinger thread detects the track is stopped.
3683 if (!mResetDone) {
3684 TrackBase::reset();
3685 // Force underrun condition to avoid false underrun callback until first data is
3686 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003687 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3688 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003689 mFillingUpStatus = FS_FILLING;
3690 mResetDone = true;
3691 }
3692}
3693
3694void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3695{
3696 mMute = muted;
3697}
3698
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3700{
3701 status_t status = DEAD_OBJECT;
3702 sp<ThreadBase> thread = mThread.promote();
3703 if (thread != 0) {
3704 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3705 status = playbackThread->attachAuxEffect(this, EffectId);
3706 }
3707 return status;
3708}
3709
3710void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3711{
3712 mAuxEffectId = EffectId;
3713 mAuxBuffer = buffer;
3714}
3715
3716// ----------------------------------------------------------------------------
3717
3718// RecordTrack constructor must be called with AudioFlinger::mLock held
3719AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3720 const wp<ThreadBase>& thread,
3721 const sp<Client>& client,
3722 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003723 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003724 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725 int frameCount,
3726 uint32_t flags,
3727 int sessionId)
3728 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003729 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730 mOverflow(false)
3731{
3732 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003733 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003734 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003735 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003736 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003737 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738 } else {
3739 mCblk->frameSize = sizeof(int8_t);
3740 }
3741 }
3742}
3743
3744AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3745{
3746 sp<ThreadBase> thread = mThread.promote();
3747 if (thread != 0) {
3748 AudioSystem::releaseInput(thread->id());
3749 }
3750}
3751
3752status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3753{
3754 audio_track_cblk_t* cblk = this->cblk();
3755 uint32_t framesAvail;
3756 uint32_t framesReq = buffer->frameCount;
3757
3758 // Check if last stepServer failed, try to step now
3759 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3760 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003761 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3763 }
3764
3765 framesAvail = cblk->framesAvailable_l();
3766
Glenn Kastenf6b16782011-12-15 09:51:17 -08003767 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 uint32_t s = cblk->server;
3769 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3770
3771 if (framesReq > framesAvail) {
3772 framesReq = framesAvail;
3773 }
3774 if (s + framesReq > bufferEnd) {
3775 framesReq = bufferEnd - s;
3776 }
3777
3778 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003779 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780
3781 buffer->frameCount = framesReq;
3782 return NO_ERROR;
3783 }
3784
3785getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003786 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003787 buffer->frameCount = 0;
3788 return NOT_ENOUGH_DATA;
3789}
3790
3791status_t AudioFlinger::RecordThread::RecordTrack::start()
3792{
3793 sp<ThreadBase> thread = mThread.promote();
3794 if (thread != 0) {
3795 RecordThread *recordThread = (RecordThread *)thread.get();
3796 return recordThread->start(this);
3797 } else {
3798 return BAD_VALUE;
3799 }
3800}
3801
3802void AudioFlinger::RecordThread::RecordTrack::stop()
3803{
3804 sp<ThreadBase> thread = mThread.promote();
3805 if (thread != 0) {
3806 RecordThread *recordThread = (RecordThread *)thread.get();
3807 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003808 TrackBase::reset();
3809 // Force overerrun condition to avoid false overrun callback until first data is
3810 // read from buffer
3811 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 }
3813}
3814
3815void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3816{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003817 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003818 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003819 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003820 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821 mSessionId,
3822 mFrameCount,
3823 mState,
3824 mCblk->sampleRate,
3825 mCblk->server,
3826 mCblk->user);
3827}
3828
3829
3830// ----------------------------------------------------------------------------
3831
3832AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3833 const wp<ThreadBase>& thread,
3834 DuplicatingThread *sourceThread,
3835 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003836 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003837 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003839 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840 mActive(false), mSourceThread(sourceThread)
3841{
3842
3843 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3844 if (mCblk != NULL) {
3845 mCblk->flags |= CBLK_DIRECTION_OUT;
3846 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847 mOutBuffer.frameCount = 0;
3848 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003849 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003850 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3851 mCblk, mBuffer, mCblk->buffers,
3852 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003854 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003855 }
3856}
3857
3858AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3859{
3860 clearBufferQueue();
3861}
3862
3863status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3864{
3865 status_t status = Track::start();
3866 if (status != NO_ERROR) {
3867 return status;
3868 }
3869
3870 mActive = true;
3871 mRetryCount = 127;
3872 return status;
3873}
3874
3875void AudioFlinger::PlaybackThread::OutputTrack::stop()
3876{
3877 Track::stop();
3878 clearBufferQueue();
3879 mOutBuffer.frameCount = 0;
3880 mActive = false;
3881}
3882
3883bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3884{
3885 Buffer *pInBuffer;
3886 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003887 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003888 bool outputBufferFull = false;
3889 inBuffer.frameCount = frames;
3890 inBuffer.i16 = data;
3891
3892 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3893
3894 if (!mActive && frames != 0) {
3895 start();
3896 sp<ThreadBase> thread = mThread.promote();
3897 if (thread != 0) {
3898 MixerThread *mixerThread = (MixerThread *)thread.get();
3899 if (mCblk->frameCount > frames){
3900 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3901 uint32_t startFrames = (mCblk->frameCount - frames);
3902 pInBuffer = new Buffer;
3903 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3904 pInBuffer->frameCount = startFrames;
3905 pInBuffer->i16 = pInBuffer->mBuffer;
3906 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3907 mBufferQueue.add(pInBuffer);
3908 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003909 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910 }
3911 }
3912 }
3913 }
3914
3915 while (waitTimeLeftMs) {
3916 // First write pending buffers, then new data
3917 if (mBufferQueue.size()) {
3918 pInBuffer = mBufferQueue.itemAt(0);
3919 } else {
3920 pInBuffer = &inBuffer;
3921 }
3922
3923 if (pInBuffer->frameCount == 0) {
3924 break;
3925 }
3926
3927 if (mOutBuffer.frameCount == 0) {
3928 mOutBuffer.frameCount = pInBuffer->frameCount;
3929 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003930 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003931 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003932 outputBufferFull = true;
3933 break;
3934 }
3935 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3936 if (waitTimeLeftMs >= waitTimeMs) {
3937 waitTimeLeftMs -= waitTimeMs;
3938 } else {
3939 waitTimeLeftMs = 0;
3940 }
3941 }
3942
3943 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3944 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3945 mCblk->stepUser(outFrames);
3946 pInBuffer->frameCount -= outFrames;
3947 pInBuffer->i16 += outFrames * channelCount;
3948 mOutBuffer.frameCount -= outFrames;
3949 mOutBuffer.i16 += outFrames * channelCount;
3950
3951 if (pInBuffer->frameCount == 0) {
3952 if (mBufferQueue.size()) {
3953 mBufferQueue.removeAt(0);
3954 delete [] pInBuffer->mBuffer;
3955 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003956 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003957 } else {
3958 break;
3959 }
3960 }
3961 }
3962
3963 // If we could not write all frames, allocate a buffer and queue it for next time.
3964 if (inBuffer.frameCount) {
3965 sp<ThreadBase> thread = mThread.promote();
3966 if (thread != 0 && !thread->standby()) {
3967 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3968 pInBuffer = new Buffer;
3969 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3970 pInBuffer->frameCount = inBuffer.frameCount;
3971 pInBuffer->i16 = pInBuffer->mBuffer;
3972 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3973 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003974 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003976 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 }
3978 }
3979 }
3980
3981 // Calling write() with a 0 length buffer, means that no more data will be written:
3982 // If no more buffers are pending, fill output track buffer to make sure it is started
3983 // by output mixer.
3984 if (frames == 0 && mBufferQueue.size() == 0) {
3985 if (mCblk->user < mCblk->frameCount) {
3986 frames = mCblk->frameCount - mCblk->user;
3987 pInBuffer = new Buffer;
3988 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3989 pInBuffer->frameCount = frames;
3990 pInBuffer->i16 = pInBuffer->mBuffer;
3991 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3992 mBufferQueue.add(pInBuffer);
3993 } else if (mActive) {
3994 stop();
3995 }
3996 }
3997
3998 return outputBufferFull;
3999}
4000
4001status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4002{
4003 int active;
4004 status_t result;
4005 audio_track_cblk_t* cblk = mCblk;
4006 uint32_t framesReq = buffer->frameCount;
4007
Steve Block3856b092011-10-20 11:56:00 +01004008// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009 buffer->frameCount = 0;
4010
4011 uint32_t framesAvail = cblk->framesAvailable();
4012
4013
4014 if (framesAvail == 0) {
4015 Mutex::Autolock _l(cblk->lock);
4016 goto start_loop_here;
4017 while (framesAvail == 0) {
4018 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004019 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01004020 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08004021 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004022 }
4023 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4024 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004025 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026 }
4027 // read the server count again
4028 start_loop_here:
4029 framesAvail = cblk->framesAvailable_l();
4030 }
4031 }
4032
4033// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08004034// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035// }
4036
4037 if (framesReq > framesAvail) {
4038 framesReq = framesAvail;
4039 }
4040
4041 uint32_t u = cblk->user;
4042 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4043
4044 if (u + framesReq > bufferEnd) {
4045 framesReq = bufferEnd - u;
4046 }
4047
4048 buffer->frameCount = framesReq;
4049 buffer->raw = (void *)cblk->buffer(u);
4050 return NO_ERROR;
4051}
4052
4053
4054void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4055{
4056 size_t size = mBufferQueue.size();
4057 Buffer *pBuffer;
4058
4059 for (size_t i = 0; i < size; i++) {
4060 pBuffer = mBufferQueue.itemAt(i);
4061 delete [] pBuffer->mBuffer;
4062 delete pBuffer;
4063 }
4064 mBufferQueue.clear();
4065}
4066
4067// ----------------------------------------------------------------------------
4068
4069AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4070 : RefBase(),
4071 mAudioFlinger(audioFlinger),
4072 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4073 mPid(pid)
4074{
4075 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4076}
4077
4078// Client destructor must be called with AudioFlinger::mLock held
4079AudioFlinger::Client::~Client()
4080{
4081 mAudioFlinger->removeClient_l(mPid);
4082}
4083
Glenn Kasten435dbe62012-01-30 10:15:48 -08004084sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085{
4086 return mMemoryDealer;
4087}
4088
4089// ----------------------------------------------------------------------------
4090
4091AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4092 const sp<IAudioFlingerClient>& client,
4093 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004094 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095{
4096}
4097
4098AudioFlinger::NotificationClient::~NotificationClient()
4099{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100}
4101
4102void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4103{
4104 sp<NotificationClient> keep(this);
4105 {
4106 mAudioFlinger->removeNotificationClient(mPid);
4107 }
4108}
4109
4110// ----------------------------------------------------------------------------
4111
4112AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4113 : BnAudioTrack(),
4114 mTrack(track)
4115{
4116}
4117
4118AudioFlinger::TrackHandle::~TrackHandle() {
4119 // just stop the track on deletion, associated resources
4120 // will be freed from the main thread once all pending buffers have
4121 // been played. Unless it's not in the active track list, in which
4122 // case we free everything now...
4123 mTrack->destroy();
4124}
4125
Glenn Kasten90716c52012-01-26 13:40:12 -08004126sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4127 return mTrack->getCblk();
4128}
4129
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130status_t AudioFlinger::TrackHandle::start() {
4131 return mTrack->start();
4132}
4133
4134void AudioFlinger::TrackHandle::stop() {
4135 mTrack->stop();
4136}
4137
4138void AudioFlinger::TrackHandle::flush() {
4139 mTrack->flush();
4140}
4141
4142void AudioFlinger::TrackHandle::mute(bool e) {
4143 mTrack->mute(e);
4144}
4145
4146void AudioFlinger::TrackHandle::pause() {
4147 mTrack->pause();
4148}
4149
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4151{
4152 return mTrack->attachAuxEffect(EffectId);
4153}
4154
4155status_t AudioFlinger::TrackHandle::onTransact(
4156 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4157{
4158 return BnAudioTrack::onTransact(code, data, reply, flags);
4159}
4160
4161// ----------------------------------------------------------------------------
4162
4163sp<IAudioRecord> AudioFlinger::openRecord(
4164 pid_t pid,
4165 int input,
4166 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004167 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004168 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169 int frameCount,
4170 uint32_t flags,
4171 int *sessionId,
4172 status_t *status)
4173{
4174 sp<RecordThread::RecordTrack> recordTrack;
4175 sp<RecordHandle> recordHandle;
4176 sp<Client> client;
4177 wp<Client> wclient;
4178 status_t lStatus;
4179 RecordThread *thread;
4180 size_t inFrameCount;
4181 int lSessionId;
4182
4183 // check calling permissions
4184 if (!recordingAllowed()) {
4185 lStatus = PERMISSION_DENIED;
4186 goto Exit;
4187 }
4188
4189 // add client to list
4190 { // scope for mLock
4191 Mutex::Autolock _l(mLock);
4192 thread = checkRecordThread_l(input);
4193 if (thread == NULL) {
4194 lStatus = BAD_VALUE;
4195 goto Exit;
4196 }
4197
4198 wclient = mClients.valueFor(pid);
4199 if (wclient != NULL) {
4200 client = wclient.promote();
4201 } else {
4202 client = new Client(this, pid);
4203 mClients.add(pid, client);
4204 }
4205
4206 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004207 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004208 lSessionId = *sessionId;
4209 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004210 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 if (sessionId != NULL) {
4212 *sessionId = lSessionId;
4213 }
4214 }
4215 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004216 recordTrack = thread->createRecordTrack_l(client,
4217 sampleRate,
4218 format,
4219 channelMask,
4220 frameCount,
4221 flags,
4222 lSessionId,
4223 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004225 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4227 // destructor is called by the TrackBase destructor with mLock held
4228 client.clear();
4229 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 goto Exit;
4231 }
4232
4233 // return to handle to client
4234 recordHandle = new RecordHandle(recordTrack);
4235 lStatus = NO_ERROR;
4236
4237Exit:
4238 if (status) {
4239 *status = lStatus;
4240 }
4241 return recordHandle;
4242}
4243
4244// ----------------------------------------------------------------------------
4245
4246AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4247 : BnAudioRecord(),
4248 mRecordTrack(recordTrack)
4249{
4250}
4251
4252AudioFlinger::RecordHandle::~RecordHandle() {
4253 stop();
4254}
4255
Glenn Kasten90716c52012-01-26 13:40:12 -08004256sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4257 return mRecordTrack->getCblk();
4258}
4259
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004261 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 return mRecordTrack->start();
4263}
4264
4265void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004266 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 mRecordTrack->stop();
4268}
4269
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270status_t AudioFlinger::RecordHandle::onTransact(
4271 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4272{
4273 return BnAudioRecord::onTransact(code, data, reply, flags);
4274}
4275
4276// ----------------------------------------------------------------------------
4277
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004278AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4279 AudioStreamIn *input,
4280 uint32_t sampleRate,
4281 uint32_t channels,
4282 int id,
4283 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004284 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004285 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4286 // mRsmpInIndex and mInputBytes set by readInputParameters()
4287 mReqChannelCount(popcount(channels)),
4288 mReqSampleRate(sampleRate)
4289 // mBytesRead is only meaningful while active, and so is cleared in start()
4290 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004292 snprintf(mName, kNameLength, "AudioIn_%d", id);
4293
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 readInputParameters();
4295}
4296
4297
4298AudioFlinger::RecordThread::~RecordThread()
4299{
4300 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004301 delete mResampler;
4302 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303}
4304
4305void AudioFlinger::RecordThread::onFirstRef()
4306{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004307 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308}
4309
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004310status_t AudioFlinger::RecordThread::readyToRun()
4311{
4312 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004313 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004314 return status;
4315}
4316
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317bool AudioFlinger::RecordThread::threadLoop()
4318{
4319 AudioBufferProvider::Buffer buffer;
4320 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004321 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322
Eric Laurent44d98482010-09-30 16:12:31 -07004323 nsecs_t lastWarning = 0;
4324
Eric Laurentfeb0db62011-07-22 09:04:31 -07004325 acquireWakeLock();
4326
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327 // start recording
4328 while (!exitPending()) {
4329
4330 processConfigEvents();
4331
4332 { // scope for mLock
4333 Mutex::Autolock _l(mLock);
4334 checkForNewParameters_l();
4335 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4336 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004337 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 mStandby = true;
4339 }
4340
4341 if (exitPending()) break;
4342
Eric Laurentfeb0db62011-07-22 09:04:31 -07004343 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004344 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345 // go to sleep
4346 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004347 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004348 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 continue;
4350 }
4351 if (mActiveTrack != 0) {
4352 if (mActiveTrack->mState == TrackBase::PAUSING) {
4353 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004354 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 mStandby = true;
4356 }
4357 mActiveTrack.clear();
4358 mStartStopCond.broadcast();
4359 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4360 if (mReqChannelCount != mActiveTrack->channelCount()) {
4361 mActiveTrack.clear();
4362 mStartStopCond.broadcast();
4363 } else if (mBytesRead != 0) {
4364 // record start succeeds only if first read from audio input
4365 // succeeds
4366 if (mBytesRead > 0) {
4367 mActiveTrack->mState = TrackBase::ACTIVE;
4368 } else {
4369 mActiveTrack.clear();
4370 }
4371 mStartStopCond.broadcast();
4372 }
4373 mStandby = false;
4374 }
4375 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004376 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 }
4378
4379 if (mActiveTrack != 0) {
4380 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4381 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004382 unlockEffectChains(effectChains);
4383 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 continue;
4385 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004386 for (size_t i = 0; i < effectChains.size(); i ++) {
4387 effectChains[i]->process_l();
4388 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004389
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004391 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004393 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004394 // no resampling
4395 while (framesOut) {
4396 size_t framesIn = mFrameCount - mRsmpInIndex;
4397 if (framesIn) {
4398 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4399 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4400 if (framesIn > framesOut)
4401 framesIn = framesOut;
4402 mRsmpInIndex += framesIn;
4403 framesOut -= framesIn;
4404 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004405 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004406 memcpy(dst, src, framesIn * mFrameSize);
4407 } else {
4408 int16_t *src16 = (int16_t *)src;
4409 int16_t *dst16 = (int16_t *)dst;
4410 if (mChannelCount == 1) {
4411 while (framesIn--) {
4412 *dst16++ = *src16;
4413 *dst16++ = *src16++;
4414 }
4415 } else {
4416 while (framesIn--) {
4417 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4418 src16 += 2;
4419 }
4420 }
4421 }
4422 }
4423 if (framesOut && mFrameCount == mRsmpInIndex) {
4424 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004425 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004426 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004427 framesOut = 0;
4428 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004429 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 mRsmpInIndex = 0;
4431 }
4432 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004433 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4435 // Force input into standby so that it tries to
4436 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004437 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004438 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 }
4440 mRsmpInIndex = mFrameCount;
4441 framesOut = 0;
4442 buffer.frameCount = 0;
4443 }
4444 }
4445 }
4446 } else {
4447 // resampling
4448
4449 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4450 // alter output frame count as if we were expecting stereo samples
4451 if (mChannelCount == 1 && mReqChannelCount == 1) {
4452 framesOut >>= 1;
4453 }
4454 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4455 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4456 // are 32 bit aligned which should be always true.
4457 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004458 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004459 // the resampler always outputs stereo samples: do post stereo to mono conversion
4460 int16_t *src = (int16_t *)mRsmpOutBuffer;
4461 int16_t *dst = buffer.i16;
4462 while (framesOut--) {
4463 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4464 src += 2;
4465 }
4466 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004467 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 }
4469
4470 }
4471 mActiveTrack->releaseBuffer(&buffer);
4472 mActiveTrack->overflow();
4473 }
4474 // client isn't retrieving buffers fast enough
4475 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004476 if (!mActiveTrack->setOverflow()) {
4477 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004478 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004479 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004480 lastWarning = now;
4481 }
4482 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 // Release the processor for a while before asking for a new buffer.
4484 // This will give the application more chance to read from the buffer and
4485 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004486 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 }
4488 }
Eric Laurentec437d82011-07-26 20:54:46 -07004489 // enable changes in effect chain
4490 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004491 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492 }
4493
4494 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004495 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 }
4497 mActiveTrack.clear();
4498
4499 mStartStopCond.broadcast();
4500
Eric Laurentfeb0db62011-07-22 09:04:31 -07004501 releaseWakeLock();
4502
Steve Block3856b092011-10-20 11:56:00 +01004503 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004504 return false;
4505}
4506
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004507
4508sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4509 const sp<AudioFlinger::Client>& client,
4510 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004511 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004512 int channelMask,
4513 int frameCount,
4514 uint32_t flags,
4515 int sessionId,
4516 status_t *status)
4517{
4518 sp<RecordTrack> track;
4519 status_t lStatus;
4520
4521 lStatus = initCheck();
4522 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004523 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004524 goto Exit;
4525 }
4526
4527 { // scope for mLock
4528 Mutex::Autolock _l(mLock);
4529
4530 track = new RecordTrack(this, client, sampleRate,
4531 format, channelMask, frameCount, flags, sessionId);
4532
Glenn Kasten7378ca52012-01-20 13:44:40 -08004533 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004534 lStatus = NO_MEMORY;
4535 goto Exit;
4536 }
4537
4538 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004539 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4540 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004541 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004542 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4543 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004544 }
4545 lStatus = NO_ERROR;
4546
4547Exit:
4548 if (status) {
4549 *status = lStatus;
4550 }
4551 return track;
4552}
4553
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4555{
Steve Block3856b092011-10-20 11:56:00 +01004556 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004557 sp <ThreadBase> strongMe = this;
4558 status_t status = NO_ERROR;
4559 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004560 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 if (mActiveTrack != 0) {
4562 if (recordTrack != mActiveTrack.get()) {
4563 status = -EBUSY;
4564 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4565 mActiveTrack->mState = TrackBase::ACTIVE;
4566 }
4567 return status;
4568 }
4569
4570 recordTrack->mState = TrackBase::IDLE;
4571 mActiveTrack = recordTrack;
4572 mLock.unlock();
4573 status_t status = AudioSystem::startInput(mId);
4574 mLock.lock();
4575 if (status != NO_ERROR) {
4576 mActiveTrack.clear();
4577 return status;
4578 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004579 mRsmpInIndex = mFrameCount;
4580 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004581 if (mResampler != NULL) {
4582 mResampler->reset();
4583 }
4584 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004586 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 mWaitWorkCV.signal();
4588 // do not wait for mStartStopCond if exiting
4589 if (mExiting) {
4590 mActiveTrack.clear();
4591 status = INVALID_OPERATION;
4592 goto startError;
4593 }
4594 mStartStopCond.wait(mLock);
4595 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004596 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 status = BAD_VALUE;
4598 goto startError;
4599 }
Steve Block3856b092011-10-20 11:56:00 +01004600 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 return status;
4602 }
4603startError:
4604 AudioSystem::stopInput(mId);
4605 return status;
4606}
4607
4608void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004609 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 sp <ThreadBase> strongMe = this;
4611 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004612 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4614 mActiveTrack->mState = TrackBase::PAUSING;
4615 // do not wait for mStartStopCond if exiting
4616 if (mExiting) {
4617 return;
4618 }
4619 mStartStopCond.wait(mLock);
4620 // if we have been restarted, recordTrack == mActiveTrack.get() here
4621 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4622 mLock.unlock();
4623 AudioSystem::stopInput(mId);
4624 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004625 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 }
4627 }
4628 }
4629}
4630
4631status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4632{
4633 const size_t SIZE = 256;
4634 char buffer[SIZE];
4635 String8 result;
4636 pid_t pid = 0;
4637
4638 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4639 result.append(buffer);
4640
4641 if (mActiveTrack != 0) {
4642 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004643 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004644 mActiveTrack->dump(buffer, SIZE);
4645 result.append(buffer);
4646
4647 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4648 result.append(buffer);
4649 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4650 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004651 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652 result.append(buffer);
4653 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4654 result.append(buffer);
4655 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4656 result.append(buffer);
4657
4658
4659 } else {
4660 result.append("No record client\n");
4661 }
4662 write(fd, result.string(), result.size());
4663
4664 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004665 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004666
4667 return NO_ERROR;
4668}
4669
4670status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4671{
4672 size_t framesReq = buffer->frameCount;
4673 size_t framesReady = mFrameCount - mRsmpInIndex;
4674 int channelCount;
4675
4676 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004677 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004678 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004679 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4681 // Force input into standby so that it tries to
4682 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004683 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004684 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004686 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004687 buffer->frameCount = 0;
4688 return NOT_ENOUGH_DATA;
4689 }
4690 mRsmpInIndex = 0;
4691 framesReady = mFrameCount;
4692 }
4693
4694 if (framesReq > framesReady) {
4695 framesReq = framesReady;
4696 }
4697
4698 if (mChannelCount == 1 && mReqChannelCount == 2) {
4699 channelCount = 1;
4700 } else {
4701 channelCount = 2;
4702 }
4703 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4704 buffer->frameCount = framesReq;
4705 return NO_ERROR;
4706}
4707
4708void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4709{
4710 mRsmpInIndex += buffer->frameCount;
4711 buffer->frameCount = 0;
4712}
4713
4714bool AudioFlinger::RecordThread::checkForNewParameters_l()
4715{
4716 bool reconfig = false;
4717
4718 while (!mNewParameters.isEmpty()) {
4719 status_t status = NO_ERROR;
4720 String8 keyValuePair = mNewParameters[0];
4721 AudioParameter param = AudioParameter(keyValuePair);
4722 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004723 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 int reqSamplingRate = mReqSampleRate;
4725 int reqChannelCount = mReqChannelCount;
4726
4727 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4728 reqSamplingRate = value;
4729 reconfig = true;
4730 }
4731 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004732 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004733 reconfig = true;
4734 }
4735 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004736 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004737 reconfig = true;
4738 }
4739 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4740 // do not accept frame count changes if tracks are open as the track buffer
4741 // size depends on frame count and correct behavior would not be garantied
4742 // if frame count is changed after track creation
4743 if (mActiveTrack != 0) {
4744 status = INVALID_OPERATION;
4745 } else {
4746 reconfig = true;
4747 }
4748 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004749 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4750 // forward device change to effects that have requested to be
4751 // aware of attached audio device.
4752 for (size_t i = 0; i < mEffectChains.size(); i++) {
4753 mEffectChains[i]->setDevice_l(value);
4754 }
4755 // store input device and output device but do not forward output device to audio HAL.
4756 // Note that status is ignored by the caller for output device
4757 // (see AudioFlinger::setParameters()
4758 if (value & AUDIO_DEVICE_OUT_ALL) {
4759 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4760 status = BAD_VALUE;
4761 } else {
4762 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004763 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4764 if (mTrack != NULL) {
4765 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004766 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004767 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4768 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4769 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004770 }
4771 mDevice |= (uint32_t)value;
4772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004774 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004775 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004776 mInput->stream->common.standby(&mInput->stream->common);
4777 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004778 }
4779 if (reconfig) {
4780 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004781 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004782 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004783 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4784 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004785 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004786 status = NO_ERROR;
4787 }
4788 if (status == NO_ERROR) {
4789 readInputParameters();
4790 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4791 }
4792 }
4793 }
4794
4795 mNewParameters.removeAt(0);
4796
4797 mParamStatus = status;
4798 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004799 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4800 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004801 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004802 }
4803 return reconfig;
4804}
4805
4806String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4807{
Dima Zavinfce7a472011-04-19 22:30:36 -07004808 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004809 String8 out_s8 = String8();
4810
4811 Mutex::Autolock _l(mLock);
4812 if (initCheck() != NO_ERROR) {
4813 return out_s8;
4814 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004815
Dima Zavin799a70e2011-04-18 16:57:27 -07004816 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004817 out_s8 = String8(s);
4818 free(s);
4819 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004820}
4821
4822void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4823 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004824 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004825
4826 switch (event) {
4827 case AudioSystem::INPUT_OPENED:
4828 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004829 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004830 desc.samplingRate = mSampleRate;
4831 desc.format = mFormat;
4832 desc.frameCount = mFrameCount;
4833 desc.latency = 0;
4834 param2 = &desc;
4835 break;
4836
4837 case AudioSystem::INPUT_CLOSED:
4838 default:
4839 break;
4840 }
4841 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4842}
4843
4844void AudioFlinger::RecordThread::readInputParameters()
4845{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004846 delete mRsmpInBuffer;
4847 // mRsmpInBuffer is always assigned a new[] below
4848 delete mRsmpOutBuffer;
4849 mRsmpOutBuffer = NULL;
4850 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004851 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852
Dima Zavin799a70e2011-04-18 16:57:27 -07004853 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004854 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4855 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004856 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004857 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004858 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004859 mFrameCount = mInputBytes / mFrameSize;
4860 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4861
4862 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4863 {
4864 int channelCount;
4865 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4866 // stereo to mono post process as the resampler always outputs stereo.
4867 if (mChannelCount == 1 && mReqChannelCount == 2) {
4868 channelCount = 1;
4869 } else {
4870 channelCount = 2;
4871 }
4872 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4873 mResampler->setSampleRate(mSampleRate);
4874 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4875 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4876
4877 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4878 if (mChannelCount == 1 && mReqChannelCount == 1) {
4879 mFrameCount >>= 1;
4880 }
4881
4882 }
4883 mRsmpInIndex = mFrameCount;
4884}
4885
4886unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4887{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004888 Mutex::Autolock _l(mLock);
4889 if (initCheck() != NO_ERROR) {
4890 return 0;
4891 }
4892
Dima Zavin799a70e2011-04-18 16:57:27 -07004893 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894}
4895
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004896uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4897{
4898 Mutex::Autolock _l(mLock);
4899 uint32_t result = 0;
4900 if (getEffectChain_l(sessionId) != 0) {
4901 result = EFFECT_SESSION;
4902 }
4903
4904 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4905 result |= TRACK_SESSION;
4906 }
4907
4908 return result;
4909}
4910
Eric Laurent59bd0da2011-08-01 09:52:20 -07004911AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4912{
4913 Mutex::Autolock _l(mLock);
4914 return mTrack;
4915}
4916
Glenn Kastenaed850d2012-01-26 09:46:34 -08004917AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004918{
4919 Mutex::Autolock _l(mLock);
4920 return mInput;
4921}
4922
4923AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4924{
4925 Mutex::Autolock _l(mLock);
4926 AudioStreamIn *input = mInput;
4927 mInput = NULL;
4928 return input;
4929}
4930
4931// this method must always be called either with ThreadBase mLock held or inside the thread loop
4932audio_stream_t* AudioFlinger::RecordThread::stream()
4933{
4934 if (mInput == NULL) {
4935 return NULL;
4936 }
4937 return &mInput->stream->common;
4938}
4939
4940
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941// ----------------------------------------------------------------------------
4942
4943int AudioFlinger::openOutput(uint32_t *pDevices,
4944 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004945 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004946 uint32_t *pChannels,
4947 uint32_t *pLatencyMs,
4948 uint32_t flags)
4949{
4950 status_t status;
4951 PlaybackThread *thread = NULL;
4952 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4953 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004954 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 uint32_t channels = pChannels ? *pChannels : 0;
4956 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004957 audio_stream_out_t *outStream;
4958 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959
Steve Block3856b092011-10-20 11:56:00 +01004960 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961 pDevices ? *pDevices : 0,
4962 samplingRate,
4963 format,
4964 channels,
4965 flags);
4966
4967 if (pDevices == NULL || *pDevices == 0) {
4968 return 0;
4969 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004970
Mathias Agopian65ab4712010-07-14 17:59:35 -07004971 Mutex::Autolock _l(mLock);
4972
Dima Zavin799a70e2011-04-18 16:57:27 -07004973 outHwDev = findSuitableHwDev_l(*pDevices);
4974 if (outHwDev == NULL)
4975 return 0;
4976
Glenn Kasten58f30212012-01-12 12:27:51 -08004977 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004978 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004979 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004980 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 samplingRate,
4982 format,
4983 channels,
4984 status);
4985
4986 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004987 if (outStream != NULL) {
4988 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004989 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004990
Dima Zavinfce7a472011-04-19 22:30:36 -07004991 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4992 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4993 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004994 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004995 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 } else {
4997 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004998 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999 }
5000 mPlaybackThreads.add(id, thread);
5001
Glenn Kastena0d68332012-01-27 16:47:15 -08005002 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
5003 if (pFormat != NULL) *pFormat = format;
5004 if (pChannels != NULL) *pChannels = channels;
5005 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006
5007 // notify client processes of the new output creation
5008 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5009 return id;
5010 }
5011
5012 return 0;
5013}
5014
5015int AudioFlinger::openDuplicateOutput(int output1, int output2)
5016{
5017 Mutex::Autolock _l(mLock);
5018 MixerThread *thread1 = checkMixerThread_l(output1);
5019 MixerThread *thread2 = checkMixerThread_l(output2);
5020
5021 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005022 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 return 0;
5024 }
5025
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005026 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5028 thread->addOutputTrack(thread2);
5029 mPlaybackThreads.add(id, thread);
5030 // notify client processes of the new output creation
5031 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5032 return id;
5033}
5034
5035status_t AudioFlinger::closeOutput(int output)
5036{
5037 // keep strong reference on the playback thread so that
5038 // it is not destroyed while exit() is executed
5039 sp <PlaybackThread> thread;
5040 {
5041 Mutex::Autolock _l(mLock);
5042 thread = checkPlaybackThread_l(output);
5043 if (thread == NULL) {
5044 return BAD_VALUE;
5045 }
5046
Steve Block3856b092011-10-20 11:56:00 +01005047 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005049 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005051 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5053 dupThread->removeOutputTrack((MixerThread *)thread.get());
5054 }
5055 }
5056 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005057 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5059 mPlaybackThreads.removeItem(output);
5060 }
5061 thread->exit();
5062
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005063 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005064 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005065 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005066 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005067 out->hwDev->close_output_stream(out->hwDev, out->stream);
5068 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 }
5070 return NO_ERROR;
5071}
5072
5073status_t AudioFlinger::suspendOutput(int output)
5074{
5075 Mutex::Autolock _l(mLock);
5076 PlaybackThread *thread = checkPlaybackThread_l(output);
5077
5078 if (thread == NULL) {
5079 return BAD_VALUE;
5080 }
5081
Steve Block3856b092011-10-20 11:56:00 +01005082 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 thread->suspend();
5084
5085 return NO_ERROR;
5086}
5087
5088status_t AudioFlinger::restoreOutput(int output)
5089{
5090 Mutex::Autolock _l(mLock);
5091 PlaybackThread *thread = checkPlaybackThread_l(output);
5092
5093 if (thread == NULL) {
5094 return BAD_VALUE;
5095 }
5096
Steve Block3856b092011-10-20 11:56:00 +01005097 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098
5099 thread->restore();
5100
5101 return NO_ERROR;
5102}
5103
5104int AudioFlinger::openInput(uint32_t *pDevices,
5105 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005106 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005107 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005108 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109{
5110 status_t status;
5111 RecordThread *thread = NULL;
5112 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005113 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 uint32_t channels = pChannels ? *pChannels : 0;
5115 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005116 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005118 audio_stream_in_t *inStream;
5119 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005120
5121 if (pDevices == NULL || *pDevices == 0) {
5122 return 0;
5123 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005124
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 Mutex::Autolock _l(mLock);
5126
Dima Zavin799a70e2011-04-18 16:57:27 -07005127 inHwDev = findSuitableHwDev_l(*pDevices);
5128 if (inHwDev == NULL)
5129 return 0;
5130
Glenn Kasten58f30212012-01-12 12:27:51 -08005131 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005132 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005133 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005134 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005135 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005136 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005137 samplingRate,
5138 format,
5139 channels,
5140 acoustics,
5141 status);
5142
5143 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5144 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5145 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005146 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005147 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005149 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005150 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005151 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005152 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005153 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005154 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 }
5156
Dima Zavin799a70e2011-04-18 16:57:27 -07005157 if (inStream != NULL) {
5158 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5159
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005160 int id = nextUniqueId();
5161 // Start record thread
5162 // RecorThread require both input and output device indication to forward to audio
5163 // pre processing modules
5164 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5165 thread = new RecordThread(this,
5166 input,
5167 reqSamplingRate,
5168 reqChannels,
5169 id,
5170 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005171 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005172 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005173 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5174 if (pFormat != NULL) *pFormat = format;
5175 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176
Dima Zavin799a70e2011-04-18 16:57:27 -07005177 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178
5179 // notify client processes of the new input creation
5180 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5181 return id;
5182 }
5183
5184 return 0;
5185}
5186
5187status_t AudioFlinger::closeInput(int input)
5188{
5189 // keep strong reference on the record thread so that
5190 // it is not destroyed while exit() is executed
5191 sp <RecordThread> thread;
5192 {
5193 Mutex::Autolock _l(mLock);
5194 thread = checkRecordThread_l(input);
5195 if (thread == NULL) {
5196 return BAD_VALUE;
5197 }
5198
Steve Block3856b092011-10-20 11:56:00 +01005199 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005200 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5202 mRecordThreads.removeItem(input);
5203 }
5204 thread->exit();
5205
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005206 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005207 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005208 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005209 in->hwDev->close_input_stream(in->hwDev, in->stream);
5210 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211
5212 return NO_ERROR;
5213}
5214
Glenn Kastenfff6d712012-01-12 16:38:12 -08005215status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216{
5217 Mutex::Autolock _l(mLock);
5218 MixerThread *dstThread = checkMixerThread_l(output);
5219 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005220 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005221 return BAD_VALUE;
5222 }
5223
Steve Block3856b092011-10-20 11:56:00 +01005224 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5226
Eric Laurent9f6530f2011-08-30 10:18:54 -07005227 dstThread->setStreamValid(stream, true);
5228
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5230 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5231 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005232 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005233 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005234 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005235 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236 }
Eric Laurentde070132010-07-13 04:45:46 -07005237 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005238
5239 return NO_ERROR;
5240}
5241
5242
5243int AudioFlinger::newAudioSessionId()
5244{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005245 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005246}
5247
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005248void AudioFlinger::acquireAudioSessionId(int audioSession)
5249{
5250 Mutex::Autolock _l(mLock);
5251 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005252 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005253 int num = mAudioSessionRefs.size();
5254 for (int i = 0; i< num; i++) {
5255 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5256 if (ref->sessionid == audioSession && ref->pid == caller) {
5257 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005258 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005259 return;
5260 }
5261 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005262 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5263 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005264}
5265
5266void AudioFlinger::releaseAudioSessionId(int audioSession)
5267{
5268 Mutex::Autolock _l(mLock);
5269 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005270 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005271 int num = mAudioSessionRefs.size();
5272 for (int i = 0; i< num; i++) {
5273 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5274 if (ref->sessionid == audioSession && ref->pid == caller) {
5275 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005276 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005277 if (ref->cnt == 0) {
5278 mAudioSessionRefs.removeAt(i);
5279 delete ref;
5280 purgeStaleEffects_l();
5281 }
5282 return;
5283 }
5284 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005285 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005286}
5287
5288void AudioFlinger::purgeStaleEffects_l() {
5289
Steve Block3856b092011-10-20 11:56:00 +01005290 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005291
5292 Vector< sp<EffectChain> > chains;
5293
5294 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5295 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5296 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5297 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005298 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5299 chains.push(ec);
5300 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005301 }
5302 }
5303 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5304 sp<RecordThread> t = mRecordThreads.valueAt(i);
5305 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5306 sp<EffectChain> ec = t->mEffectChains[j];
5307 chains.push(ec);
5308 }
5309 }
5310
5311 for (size_t i = 0; i < chains.size(); i++) {
5312 sp<EffectChain> ec = chains[i];
5313 int sessionid = ec->sessionId();
5314 sp<ThreadBase> t = ec->mThread.promote();
5315 if (t == 0) {
5316 continue;
5317 }
5318 size_t numsessionrefs = mAudioSessionRefs.size();
5319 bool found = false;
5320 for (size_t k = 0; k < numsessionrefs; k++) {
5321 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5322 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005323 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005324 sessionid, ref->pid, ref->cnt);
5325 found = true;
5326 break;
5327 }
5328 }
5329 if (!found) {
5330 // remove all effects from the chain
5331 while (ec->mEffects.size()) {
5332 sp<EffectModule> effect = ec->mEffects[0];
5333 effect->unPin();
5334 Mutex::Autolock _l (t->mLock);
5335 t->removeEffect_l(effect);
5336 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5337 sp<EffectHandle> handle = effect->mHandles[j].promote();
5338 if (handle != 0) {
5339 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005340 if (handle->mHasControl && handle->mEnabled) {
5341 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5342 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005343 }
5344 }
5345 AudioSystem::unregisterEffect(effect->id());
5346 }
5347 }
5348 }
5349 return;
5350}
5351
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5353AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5354{
5355 PlaybackThread *thread = NULL;
5356 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5357 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5358 }
5359 return thread;
5360}
5361
5362// checkMixerThread_l() must be called with AudioFlinger::mLock held
5363AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5364{
5365 PlaybackThread *thread = checkPlaybackThread_l(output);
5366 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005367 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 thread = NULL;
5369 }
5370 }
5371 return (MixerThread *)thread;
5372}
5373
5374// checkRecordThread_l() must be called with AudioFlinger::mLock held
5375AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5376{
5377 RecordThread *thread = NULL;
5378 if (mRecordThreads.indexOfKey(input) >= 0) {
5379 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5380 }
5381 return thread;
5382}
5383
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005384uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005386 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005387}
5388
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005389AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5390{
5391 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5392 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005393 AudioStreamOut *output = thread->getOutput();
5394 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005395 return thread;
5396 }
5397 }
5398 return NULL;
5399}
5400
5401uint32_t AudioFlinger::primaryOutputDevice_l()
5402{
5403 PlaybackThread *thread = primaryPlaybackThread_l();
5404
5405 if (thread == NULL) {
5406 return 0;
5407 }
5408
5409 return thread->device();
5410}
5411
5412
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413// ----------------------------------------------------------------------------
5414// Effect management
5415// ----------------------------------------------------------------------------
5416
5417
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5419{
5420 Mutex::Autolock _l(mLock);
5421 return EffectQueryNumberEffects(numEffects);
5422}
5423
5424status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5425{
5426 Mutex::Autolock _l(mLock);
5427 return EffectQueryEffect(index, descriptor);
5428}
5429
5430status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5431{
5432 Mutex::Autolock _l(mLock);
5433 return EffectGetDescriptor(pUuid, descriptor);
5434}
5435
5436
Mathias Agopian65ab4712010-07-14 17:59:35 -07005437sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5438 effect_descriptor_t *pDesc,
5439 const sp<IEffectClient>& effectClient,
5440 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005441 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 int sessionId,
5443 status_t *status,
5444 int *id,
5445 int *enabled)
5446{
5447 status_t lStatus = NO_ERROR;
5448 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 effect_descriptor_t desc;
5450 sp<Client> client;
5451 wp<Client> wclient;
5452
Steve Block3856b092011-10-20 11:56:00 +01005453 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005454 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455
5456 if (pDesc == NULL) {
5457 lStatus = BAD_VALUE;
5458 goto Exit;
5459 }
5460
Eric Laurent84e9a102010-09-23 16:10:16 -07005461 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005462 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005463 lStatus = PERMISSION_DENIED;
5464 goto Exit;
5465 }
5466
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005468 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005469 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005470 lStatus = PERMISSION_DENIED;
5471 goto Exit;
5472 }
5473
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005474 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005475 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005476 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005477 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005478 lStatus = BAD_VALUE;
5479 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005480 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005481 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005482 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005483 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005484 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005485 }
5486 }
5487
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 {
5489 Mutex::Autolock _l(mLock);
5490
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491
5492 if (!EffectIsNullUuid(&pDesc->uuid)) {
5493 // if uuid is specified, request effect descriptor
5494 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5495 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005496 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005497 goto Exit;
5498 }
5499 } else {
5500 // if uuid is not specified, look for an available implementation
5501 // of the required type in effect factory
5502 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005503 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005504 lStatus = BAD_VALUE;
5505 goto Exit;
5506 }
5507 uint32_t numEffects = 0;
5508 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005509 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 bool found = false;
5511
5512 lStatus = EffectQueryNumberEffects(&numEffects);
5513 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005514 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 goto Exit;
5516 }
5517 for (uint32_t i = 0; i < numEffects; i++) {
5518 lStatus = EffectQueryEffect(i, &desc);
5519 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005520 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521 continue;
5522 }
5523 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5524 // If matching type found save effect descriptor. If the session is
5525 // 0 and the effect is not auxiliary, continue enumeration in case
5526 // an auxiliary version of this effect type is available
5527 found = true;
5528 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005529 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5531 break;
5532 }
5533 }
5534 }
5535 if (!found) {
5536 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005537 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005538 goto Exit;
5539 }
5540 // For same effect type, chose auxiliary version over insert version if
5541 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005542 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5544 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5545 }
5546 }
5547
5548 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005549 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5551 lStatus = INVALID_OPERATION;
5552 goto Exit;
5553 }
5554
Eric Laurent59255e42011-07-27 19:49:51 -07005555 // check recording permission for visualizer
5556 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5557 !recordingAllowed()) {
5558 lStatus = PERMISSION_DENIED;
5559 goto Exit;
5560 }
5561
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562 // return effect descriptor
5563 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5564
5565 // If output is not specified try to find a matching audio session ID in one of the
5566 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005567 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5568 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005569 // Note: io is never 0 when creating an effect on an input
5570 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005571 // look for the thread where the specified audio session is present
5572 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5573 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005574 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005575 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005578 if (io == 0) {
5579 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5580 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5581 io = mRecordThreads.keyAt(i);
5582 break;
5583 }
5584 }
5585 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005586 // If no output thread contains the requested session ID, default to
5587 // first output. The effect chain will be moved to the correct output
5588 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005589 if (io == 0 && mPlaybackThreads.size()) {
5590 io = mPlaybackThreads.keyAt(0);
5591 }
Steve Block3856b092011-10-20 11:56:00 +01005592 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005593 }
5594 ThreadBase *thread = checkRecordThread_l(io);
5595 if (thread == NULL) {
5596 thread = checkPlaybackThread_l(io);
5597 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005598 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005599 lStatus = BAD_VALUE;
5600 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005603
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 wclient = mClients.valueFor(pid);
5605
5606 if (wclient != NULL) {
5607 client = wclient.promote();
5608 } else {
5609 client = new Client(this, pid);
5610 mClients.add(pid, client);
5611 }
5612
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005613 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005614 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5615 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616 if (handle != 0 && id != NULL) {
5617 *id = handle->id();
5618 }
5619 }
5620
5621Exit:
5622 if(status) {
5623 *status = lStatus;
5624 }
5625 return handle;
5626}
5627
Eric Laurent59255e42011-07-27 19:49:51 -07005628status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005629{
Steve Block3856b092011-10-20 11:56:00 +01005630 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005631 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005632 Mutex::Autolock _l(mLock);
5633 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005634 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005635 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636 }
Eric Laurentde070132010-07-13 04:45:46 -07005637 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5638 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005639 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005640 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 }
Eric Laurentde070132010-07-13 04:45:46 -07005642 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5643 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005644 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005645 return BAD_VALUE;
5646 }
5647
5648 Mutex::Autolock _dl(dstThread->mLock);
5649 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005650 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005651
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 return NO_ERROR;
5653}
5654
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005655// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005656status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005657 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005658 AudioFlinger::PlaybackThread *dstThread,
5659 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005660{
Steve Block3856b092011-10-20 11:56:00 +01005661 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005662 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005663
Eric Laurent59255e42011-07-27 19:49:51 -07005664 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005665 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005666 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005667 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005668 return INVALID_OPERATION;
5669 }
5670
Eric Laurent39e94f82010-07-28 01:32:47 -07005671 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005672 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005673 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005674 // removed.
5675 srcThread->removeEffectChain_l(chain);
5676
5677 // transfer all effects one by one so that new effect chain is created on new thread with
5678 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005679 int dstOutput = dstThread->id();
5680 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005681 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005682 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5683 while (effect != 0) {
5684 srcThread->removeEffect_l(effect);
5685 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005686 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5687 if (effect->state() == EffectModule::ACTIVE ||
5688 effect->state() == EffectModule::STOPPING) {
5689 effect->start();
5690 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005691 // if the move request is not received from audio policy manager, the effect must be
5692 // re-registered with the new strategy and output
5693 if (dstChain == 0) {
5694 dstChain = effect->chain().promote();
5695 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005696 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005697 srcThread->addEffect_l(effect);
5698 return NO_INIT;
5699 }
5700 strategy = dstChain->strategy();
5701 }
5702 if (reRegister) {
5703 AudioSystem::unregisterEffect(effect->id());
5704 AudioSystem::registerEffect(&effect->desc(),
5705 dstOutput,
5706 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005707 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005708 effect->id());
5709 }
Eric Laurentde070132010-07-13 04:45:46 -07005710 effect = chain->getEffectFromId_l(0);
5711 }
5712
5713 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714}
5715
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005716
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005718sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 const sp<AudioFlinger::Client>& client,
5720 const sp<IEffectClient>& effectClient,
5721 int32_t priority,
5722 int sessionId,
5723 effect_descriptor_t *desc,
5724 int *enabled,
5725 status_t *status
5726 )
5727{
5728 sp<EffectModule> effect;
5729 sp<EffectHandle> handle;
5730 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005732 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733 bool effectCreated = false;
5734 bool effectRegistered = false;
5735
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005736 lStatus = initCheck();
5737 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005738 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 goto Exit;
5740 }
5741
5742 // Do not allow effects with session ID 0 on direct output or duplicating threads
5743 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005744 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005745 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005746 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747 lStatus = BAD_VALUE;
5748 goto Exit;
5749 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005750 // Only Pre processor effects are allowed on input threads and only on input threads
5751 if ((mType == RECORD &&
5752 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5753 (mType != RECORD &&
5754 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005755 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005756 desc->name, desc->flags, mType);
5757 lStatus = BAD_VALUE;
5758 goto Exit;
5759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760
Steve Block3856b092011-10-20 11:56:00 +01005761 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762
5763 { // scope for mLock
5764 Mutex::Autolock _l(mLock);
5765
5766 // check for existing effect chain with the requested audio session
5767 chain = getEffectChain_l(sessionId);
5768 if (chain == 0) {
5769 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005770 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005771 chain = new EffectChain(this, sessionId);
5772 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005773 chain->setStrategy(getStrategyForSession_l(sessionId));
5774 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005775 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005776 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 }
5778
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005779 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780
5781 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005782 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005784 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005785 if (lStatus != NO_ERROR) {
5786 goto Exit;
5787 }
5788 effectRegistered = true;
5789 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005790 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791 lStatus = effect->status();
5792 if (lStatus != NO_ERROR) {
5793 goto Exit;
5794 }
Eric Laurentcab11242010-07-15 12:50:15 -07005795 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796 if (lStatus != NO_ERROR) {
5797 goto Exit;
5798 }
5799 effectCreated = true;
5800
5801 effect->setDevice(mDevice);
5802 effect->setMode(mAudioFlinger->getMode());
5803 }
5804 // create effect handle and connect it to effect module
5805 handle = new EffectHandle(effect, client, effectClient, priority);
5806 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005807 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005808 *enabled = (int)effect->isEnabled();
5809 }
5810 }
5811
5812Exit:
5813 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005814 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005816 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817 }
5818 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005819 AudioSystem::unregisterEffect(effect->id());
5820 }
5821 if (chainCreated) {
5822 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823 }
5824 handle.clear();
5825 }
5826
5827 if(status) {
5828 *status = lStatus;
5829 }
5830 return handle;
5831}
5832
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005833sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5834{
5835 sp<EffectModule> effect;
5836
5837 sp<EffectChain> chain = getEffectChain_l(sessionId);
5838 if (chain != 0) {
5839 effect = chain->getEffectFromId_l(effectId);
5840 }
5841 return effect;
5842}
5843
Eric Laurentde070132010-07-13 04:45:46 -07005844// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5845// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005846status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005847{
5848 // check for existing effect chain with the requested audio session
5849 int sessionId = effect->sessionId();
5850 sp<EffectChain> chain = getEffectChain_l(sessionId);
5851 bool chainCreated = false;
5852
5853 if (chain == 0) {
5854 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005855 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005856 chain = new EffectChain(this, sessionId);
5857 addEffectChain_l(chain);
5858 chain->setStrategy(getStrategyForSession_l(sessionId));
5859 chainCreated = true;
5860 }
Steve Block3856b092011-10-20 11:56:00 +01005861 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005862
5863 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005864 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005865 this, effect->desc().name, chain.get());
5866 return BAD_VALUE;
5867 }
5868
5869 status_t status = chain->addEffect_l(effect);
5870 if (status != NO_ERROR) {
5871 if (chainCreated) {
5872 removeEffectChain_l(chain);
5873 }
5874 return status;
5875 }
5876
5877 effect->setDevice(mDevice);
5878 effect->setMode(mAudioFlinger->getMode());
5879 return NO_ERROR;
5880}
5881
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005882void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005883
Steve Block3856b092011-10-20 11:56:00 +01005884 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005885 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005886 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5887 detachAuxEffect_l(effect->id());
5888 }
5889
5890 sp<EffectChain> chain = effect->chain().promote();
5891 if (chain != 0) {
5892 // remove effect chain if removing last effect
5893 if (chain->removeEffect_l(effect) == 0) {
5894 removeEffectChain_l(chain);
5895 }
5896 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005897 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005898 }
5899}
5900
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005901void AudioFlinger::ThreadBase::lockEffectChains_l(
5902 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5903{
5904 effectChains = mEffectChains;
5905 for (size_t i = 0; i < mEffectChains.size(); i++) {
5906 mEffectChains[i]->lock();
5907 }
5908}
5909
5910void AudioFlinger::ThreadBase::unlockEffectChains(
5911 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5912{
5913 for (size_t i = 0; i < effectChains.size(); i++) {
5914 effectChains[i]->unlock();
5915 }
5916}
5917
5918sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5919{
5920 Mutex::Autolock _l(mLock);
5921 return getEffectChain_l(sessionId);
5922}
5923
5924sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5925{
5926 sp<EffectChain> chain;
5927
5928 size_t size = mEffectChains.size();
5929 for (size_t i = 0; i < size; i++) {
5930 if (mEffectChains[i]->sessionId() == sessionId) {
5931 chain = mEffectChains[i];
5932 break;
5933 }
5934 }
5935 return chain;
5936}
5937
Glenn Kastenf78aee72012-01-04 11:00:47 -08005938void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005939{
5940 Mutex::Autolock _l(mLock);
5941 size_t size = mEffectChains.size();
5942 for (size_t i = 0; i < size; i++) {
5943 mEffectChains[i]->setMode_l(mode);
5944 }
5945}
5946
5947void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005948 const wp<EffectHandle>& handle,
5949 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005950
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005952 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005953 // delete the effect module if removing last handle on it
5954 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005955 if (!effect->isPinned() || unpiniflast) {
5956 removeEffect_l(effect);
5957 AudioSystem::unregisterEffect(effect->id());
5958 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 }
5960}
5961
5962status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5963{
5964 int session = chain->sessionId();
5965 int16_t *buffer = mMixBuffer;
5966 bool ownsBuffer = false;
5967
Steve Block3856b092011-10-20 11:56:00 +01005968 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 if (session > 0) {
5970 // Only one effect chain can be present in direct output thread and it uses
5971 // the mix buffer as input
5972 if (mType != DIRECT) {
5973 size_t numSamples = mFrameCount * mChannelCount;
5974 buffer = new int16_t[numSamples];
5975 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005976 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977 ownsBuffer = true;
5978 }
5979
5980 // Attach all tracks with same session ID to this chain.
5981 for (size_t i = 0; i < mTracks.size(); ++i) {
5982 sp<Track> track = mTracks[i];
5983 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005984 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005986 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 }
5988 }
5989
5990 // indicate all active tracks in the chain
5991 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5992 sp<Track> track = mActiveTracks[i].promote();
5993 if (track == 0) continue;
5994 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005995 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005996 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997 }
5998 }
5999 }
6000
6001 chain->setInBuffer(buffer, ownsBuffer);
6002 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006003 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006004 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006005 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6006 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006008 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6009 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006010 // Effect chain for other sessions are inserted at beginning of effect
6011 // chains list to be processed before output mix effects. Relative order between other
6012 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 size_t size = mEffectChains.size();
6014 size_t i = 0;
6015 for (i = 0; i < size; i++) {
6016 if (mEffectChains[i]->sessionId() < session) break;
6017 }
6018 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006019 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020
6021 return NO_ERROR;
6022}
6023
6024size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6025{
6026 int session = chain->sessionId();
6027
Steve Block3856b092011-10-20 11:56:00 +01006028 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029
6030 for (size_t i = 0; i < mEffectChains.size(); i++) {
6031 if (chain == mEffectChains[i]) {
6032 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006033 // detach all active tracks from the chain
6034 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6035 sp<Track> track = mActiveTracks[i].promote();
6036 if (track == 0) continue;
6037 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006038 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006039 chain.get(), session);
6040 chain->decActiveTrackCnt();
6041 }
6042 }
6043
Mathias Agopian65ab4712010-07-14 17:59:35 -07006044 // detach all tracks with same session ID from this chain
6045 for (size_t i = 0; i < mTracks.size(); ++i) {
6046 sp<Track> track = mTracks[i];
6047 if (session == track->sessionId()) {
6048 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006049 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006050 }
6051 }
Eric Laurentde070132010-07-13 04:45:46 -07006052 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 }
6054 }
6055 return mEffectChains.size();
6056}
6057
Eric Laurentde070132010-07-13 04:45:46 -07006058status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6059 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060{
6061 Mutex::Autolock _l(mLock);
6062 return attachAuxEffect_l(track, EffectId);
6063}
6064
Eric Laurentde070132010-07-13 04:45:46 -07006065status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6066 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067{
6068 status_t status = NO_ERROR;
6069
6070 if (EffectId == 0) {
6071 track->setAuxBuffer(0, NULL);
6072 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006073 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6074 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 if (effect != 0) {
6076 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6077 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6078 } else {
6079 status = INVALID_OPERATION;
6080 }
6081 } else {
6082 status = BAD_VALUE;
6083 }
6084 }
6085 return status;
6086}
6087
6088void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6089{
6090 for (size_t i = 0; i < mTracks.size(); ++i) {
6091 sp<Track> track = mTracks[i];
6092 if (track->auxEffectId() == effectId) {
6093 attachAuxEffect_l(track, 0);
6094 }
6095 }
6096}
6097
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006098status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6099{
6100 // only one chain per input thread
6101 if (mEffectChains.size() != 0) {
6102 return INVALID_OPERATION;
6103 }
Steve Block3856b092011-10-20 11:56:00 +01006104 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006105
6106 chain->setInBuffer(NULL);
6107 chain->setOutBuffer(NULL);
6108
Eric Laurent59255e42011-07-27 19:49:51 -07006109 checkSuspendOnAddEffectChain_l(chain);
6110
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006111 mEffectChains.add(chain);
6112
6113 return NO_ERROR;
6114}
6115
6116size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6117{
Steve Block3856b092011-10-20 11:56:00 +01006118 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006119 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006120 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6121 chain.get(), mEffectChains.size(), this);
6122 if (mEffectChains.size() == 1) {
6123 mEffectChains.removeAt(0);
6124 }
6125 return 0;
6126}
6127
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128// ----------------------------------------------------------------------------
6129// EffectModule implementation
6130// ----------------------------------------------------------------------------
6131
6132#undef LOG_TAG
6133#define LOG_TAG "AudioFlinger::EffectModule"
6134
6135AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6136 const wp<AudioFlinger::EffectChain>& chain,
6137 effect_descriptor_t *desc,
6138 int id,
6139 int sessionId)
6140 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006141 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142{
Steve Block3856b092011-10-20 11:56:00 +01006143 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144 int lStatus;
6145 sp<ThreadBase> thread = mThread.promote();
6146 if (thread == 0) {
6147 return;
6148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149
6150 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6151
6152 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006153 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154
6155 if (mStatus != NO_ERROR) {
6156 return;
6157 }
6158 lStatus = init();
6159 if (lStatus < 0) {
6160 mStatus = lStatus;
6161 goto Error;
6162 }
6163
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006164 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6165 mPinned = true;
6166 }
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 return;
6169Error:
6170 EffectRelease(mEffectInterface);
6171 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006172 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173}
6174
6175AudioFlinger::EffectModule::~EffectModule()
6176{
Steve Block3856b092011-10-20 11:56:00 +01006177 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006179 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6180 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6181 sp<ThreadBase> thread = mThread.promote();
6182 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006183 audio_stream_t *stream = thread->stream();
6184 if (stream != NULL) {
6185 stream->remove_audio_effect(stream, mEffectInterface);
6186 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006187 }
6188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006189 // release effect engine
6190 EffectRelease(mEffectInterface);
6191 }
6192}
6193
Glenn Kasten435dbe62012-01-30 10:15:48 -08006194status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195{
6196 status_t status;
6197
6198 Mutex::Autolock _l(mLock);
6199 // First handle in mHandles has highest priority and controls the effect module
6200 int priority = handle->priority();
6201 size_t size = mHandles.size();
6202 sp<EffectHandle> h;
6203 size_t i;
6204 for (i = 0; i < size; i++) {
6205 h = mHandles[i].promote();
6206 if (h == 0) continue;
6207 if (h->priority() <= priority) break;
6208 }
6209 // if inserted in first place, move effect control from previous owner to this handle
6210 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006211 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006213 enabled = h->enabled();
6214 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 }
Eric Laurent59255e42011-07-27 19:49:51 -07006216 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 status = NO_ERROR;
6218 } else {
6219 status = ALREADY_EXISTS;
6220 }
Steve Block3856b092011-10-20 11:56:00 +01006221 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222 mHandles.insertAt(handle, i);
6223 return status;
6224}
6225
6226size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6227{
6228 Mutex::Autolock _l(mLock);
6229 size_t size = mHandles.size();
6230 size_t i;
6231 for (i = 0; i < size; i++) {
6232 if (mHandles[i] == handle) break;
6233 }
6234 if (i == size) {
6235 return size;
6236 }
Steve Block3856b092011-10-20 11:56:00 +01006237 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006238
6239 bool enabled = false;
6240 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006241 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006242 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006243 enabled = hdl->enabled();
6244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 mHandles.removeAt(i);
6246 size = mHandles.size();
6247 // if removed from first place, move effect control from this handle to next in line
6248 if (i == 0 && size != 0) {
6249 sp<EffectHandle> h = mHandles[0].promote();
6250 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006251 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006252 }
6253 }
6254
Eric Laurentec437d82011-07-26 20:54:46 -07006255 // Prevent calls to process() and other functions on effect interface from now on.
6256 // The effect engine will be released by the destructor when the last strong reference on
6257 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006258 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006259 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006260 }
6261
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 return size;
6263}
6264
Eric Laurent59255e42011-07-27 19:49:51 -07006265sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6266{
6267 Mutex::Autolock _l(mLock);
6268 sp<EffectHandle> handle;
6269 if (mHandles.size() != 0) {
6270 handle = mHandles[0].promote();
6271 }
6272 return handle;
6273}
6274
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006275void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276{
Steve Block3856b092011-10-20 11:56:00 +01006277 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 // keep a strong reference on this EffectModule to avoid calling the
6279 // destructor before we exit
6280 sp<EffectModule> keep(this);
6281 {
6282 sp<ThreadBase> thread = mThread.promote();
6283 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006284 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006285 }
6286 }
6287}
6288
6289void AudioFlinger::EffectModule::updateState() {
6290 Mutex::Autolock _l(mLock);
6291
6292 switch (mState) {
6293 case RESTART:
6294 reset_l();
6295 // FALL THROUGH
6296
6297 case STARTING:
6298 // clear auxiliary effect input buffer for next accumulation
6299 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6300 memset(mConfig.inputCfg.buffer.raw,
6301 0,
6302 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6303 }
6304 start_l();
6305 mState = ACTIVE;
6306 break;
6307 case STOPPING:
6308 stop_l();
6309 mDisableWaitCnt = mMaxDisableWaitCnt;
6310 mState = STOPPED;
6311 break;
6312 case STOPPED:
6313 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6314 // turn off sequence.
6315 if (--mDisableWaitCnt == 0) {
6316 reset_l();
6317 mState = IDLE;
6318 }
6319 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006320 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006321 break;
6322 }
6323}
6324
6325void AudioFlinger::EffectModule::process()
6326{
6327 Mutex::Autolock _l(mLock);
6328
Eric Laurentec437d82011-07-26 20:54:46 -07006329 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 mConfig.inputCfg.buffer.raw == NULL ||
6331 mConfig.outputCfg.buffer.raw == NULL) {
6332 return;
6333 }
6334
Eric Laurent8f45bd72010-08-31 13:50:07 -07006335 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006336 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6337 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006338 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006340 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 }
6342
6343 // do the actual processing in the effect engine
6344 int ret = (*mEffectInterface)->process(mEffectInterface,
6345 &mConfig.inputCfg.buffer,
6346 &mConfig.outputCfg.buffer);
6347
6348 // force transition to IDLE state when engine is ready
6349 if (mState == STOPPED && ret == -ENODATA) {
6350 mDisableWaitCnt = 1;
6351 }
6352
6353 // clear auxiliary effect input buffer for next accumulation
6354 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006355 memset(mConfig.inputCfg.buffer.raw, 0,
6356 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 }
6358 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006359 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6360 // If an insert effect is idle and input buffer is different from output buffer,
6361 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006362 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006363 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006364 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6365 int16_t *in = mConfig.inputCfg.buffer.s16;
6366 int16_t *out = mConfig.outputCfg.buffer.s16;
6367 for (size_t i = 0; i < frameCnt; i++) {
6368 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 }
6371 }
6372}
6373
6374void AudioFlinger::EffectModule::reset_l()
6375{
6376 if (mEffectInterface == NULL) {
6377 return;
6378 }
6379 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6380}
6381
6382status_t AudioFlinger::EffectModule::configure()
6383{
6384 uint32_t channels;
6385 if (mEffectInterface == NULL) {
6386 return NO_INIT;
6387 }
6388
6389 sp<ThreadBase> thread = mThread.promote();
6390 if (thread == 0) {
6391 return DEAD_OBJECT;
6392 }
6393
6394 // TODO: handle configuration of effects replacing track process
6395 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006396 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006398 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006399 }
6400
6401 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006402 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006403 } else {
6404 mConfig.inputCfg.channels = channels;
6405 }
6406 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006407 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6408 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409 mConfig.inputCfg.samplingRate = thread->sampleRate();
6410 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6411 mConfig.inputCfg.bufferProvider.cookie = NULL;
6412 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6413 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6414 mConfig.outputCfg.bufferProvider.cookie = NULL;
6415 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6416 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6417 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6418 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006419 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006420 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421 // - in other sessions:
6422 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6423 // other effect: overwrites output buffer: input buffer == output buffer
6424 // Auxiliary effect:
6425 // accumulates in output buffer: input buffer != output buffer
6426 // Therefore: accumulate <=> input buffer != output buffer
6427 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6428 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6429 } else {
6430 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6431 }
6432 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6433 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6434 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6435 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6436
Steve Block3856b092011-10-20 11:56:00 +01006437 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006438 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6439
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006441 uint32_t size = sizeof(int);
6442 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006443 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006444 sizeof(effect_config_t),
6445 &mConfig,
6446 &size,
6447 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 if (status == 0) {
6449 status = cmdStatus;
6450 }
6451
6452 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6453 (1000 * mConfig.outputCfg.buffer.frameCount);
6454
6455 return status;
6456}
6457
6458status_t AudioFlinger::EffectModule::init()
6459{
6460 Mutex::Autolock _l(mLock);
6461 if (mEffectInterface == NULL) {
6462 return NO_INIT;
6463 }
6464 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006465 uint32_t size = sizeof(status_t);
6466 status_t status = (*mEffectInterface)->command(mEffectInterface,
6467 EFFECT_CMD_INIT,
6468 0,
6469 NULL,
6470 &size,
6471 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006472 if (status == 0) {
6473 status = cmdStatus;
6474 }
6475 return status;
6476}
6477
Eric Laurentec35a142011-10-05 17:42:25 -07006478status_t AudioFlinger::EffectModule::start()
6479{
6480 Mutex::Autolock _l(mLock);
6481 return start_l();
6482}
6483
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484status_t AudioFlinger::EffectModule::start_l()
6485{
6486 if (mEffectInterface == NULL) {
6487 return NO_INIT;
6488 }
6489 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006490 uint32_t size = sizeof(status_t);
6491 status_t status = (*mEffectInterface)->command(mEffectInterface,
6492 EFFECT_CMD_ENABLE,
6493 0,
6494 NULL,
6495 &size,
6496 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497 if (status == 0) {
6498 status = cmdStatus;
6499 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006500 if (status == 0 &&
6501 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6502 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6503 sp<ThreadBase> thread = mThread.promote();
6504 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006505 audio_stream_t *stream = thread->stream();
6506 if (stream != NULL) {
6507 stream->add_audio_effect(stream, mEffectInterface);
6508 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006509 }
6510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 return status;
6512}
6513
Eric Laurentec437d82011-07-26 20:54:46 -07006514status_t AudioFlinger::EffectModule::stop()
6515{
6516 Mutex::Autolock _l(mLock);
6517 return stop_l();
6518}
6519
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520status_t AudioFlinger::EffectModule::stop_l()
6521{
6522 if (mEffectInterface == NULL) {
6523 return NO_INIT;
6524 }
6525 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006526 uint32_t size = sizeof(status_t);
6527 status_t status = (*mEffectInterface)->command(mEffectInterface,
6528 EFFECT_CMD_DISABLE,
6529 0,
6530 NULL,
6531 &size,
6532 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533 if (status == 0) {
6534 status = cmdStatus;
6535 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006536 if (status == 0 &&
6537 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6538 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6539 sp<ThreadBase> thread = mThread.promote();
6540 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006541 audio_stream_t *stream = thread->stream();
6542 if (stream != NULL) {
6543 stream->remove_audio_effect(stream, mEffectInterface);
6544 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006545 }
6546 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 return status;
6548}
6549
Eric Laurent25f43952010-07-28 05:40:18 -07006550status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6551 uint32_t cmdSize,
6552 void *pCmdData,
6553 uint32_t *replySize,
6554 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006555{
6556 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006557// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006558
Eric Laurentec437d82011-07-26 20:54:46 -07006559 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560 return NO_INIT;
6561 }
Eric Laurent25f43952010-07-28 05:40:18 -07006562 status_t status = (*mEffectInterface)->command(mEffectInterface,
6563 cmdCode,
6564 cmdSize,
6565 pCmdData,
6566 replySize,
6567 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006569 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570 for (size_t i = 1; i < mHandles.size(); i++) {
6571 sp<EffectHandle> h = mHandles[i].promote();
6572 if (h != 0) {
6573 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6574 }
6575 }
6576 }
6577 return status;
6578}
6579
6580status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6581{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006582
Mathias Agopian65ab4712010-07-14 17:59:35 -07006583 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006584 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585
6586 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006587 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6588 if (enabled && status != NO_ERROR) {
6589 return status;
6590 }
6591
Mathias Agopian65ab4712010-07-14 17:59:35 -07006592 switch (mState) {
6593 // going from disabled to enabled
6594 case IDLE:
6595 mState = STARTING;
6596 break;
6597 case STOPPED:
6598 mState = RESTART;
6599 break;
6600 case STOPPING:
6601 mState = ACTIVE;
6602 break;
6603
6604 // going from enabled to disabled
6605 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006606 mState = STOPPED;
6607 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 case STARTING:
6609 mState = IDLE;
6610 break;
6611 case ACTIVE:
6612 mState = STOPPING;
6613 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006614 case DESTROYED:
6615 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 }
6617 for (size_t i = 1; i < mHandles.size(); i++) {
6618 sp<EffectHandle> h = mHandles[i].promote();
6619 if (h != 0) {
6620 h->setEnabled(enabled);
6621 }
6622 }
6623 }
6624 return NO_ERROR;
6625}
6626
6627bool AudioFlinger::EffectModule::isEnabled()
6628{
6629 switch (mState) {
6630 case RESTART:
6631 case STARTING:
6632 case ACTIVE:
6633 return true;
6634 case IDLE:
6635 case STOPPING:
6636 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006637 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 default:
6639 return false;
6640 }
6641}
6642
Eric Laurent8f45bd72010-08-31 13:50:07 -07006643bool AudioFlinger::EffectModule::isProcessEnabled()
6644{
6645 switch (mState) {
6646 case RESTART:
6647 case ACTIVE:
6648 case STOPPING:
6649 case STOPPED:
6650 return true;
6651 case IDLE:
6652 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006653 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006654 default:
6655 return false;
6656 }
6657}
6658
Mathias Agopian65ab4712010-07-14 17:59:35 -07006659status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6660{
6661 Mutex::Autolock _l(mLock);
6662 status_t status = NO_ERROR;
6663
6664 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6665 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006666 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006667 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6668 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 status_t cmdStatus;
6670 uint32_t volume[2];
6671 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006672 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006673 volume[0] = *left;
6674 volume[1] = *right;
6675 if (controller) {
6676 pVolume = volume;
6677 }
Eric Laurent25f43952010-07-28 05:40:18 -07006678 status = (*mEffectInterface)->command(mEffectInterface,
6679 EFFECT_CMD_SET_VOLUME,
6680 size,
6681 volume,
6682 &size,
6683 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6685 *left = volume[0];
6686 *right = volume[1];
6687 }
6688 }
6689 return status;
6690}
6691
6692status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6693{
6694 Mutex::Autolock _l(mLock);
6695 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006696 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6697 // audio pre processing modules on RecordThread can receive both output and
6698 // input device indication in the same call
6699 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6700 if (dev) {
6701 status_t cmdStatus;
6702 uint32_t size = sizeof(status_t);
6703
6704 status = (*mEffectInterface)->command(mEffectInterface,
6705 EFFECT_CMD_SET_DEVICE,
6706 sizeof(uint32_t),
6707 &dev,
6708 &size,
6709 &cmdStatus);
6710 if (status == NO_ERROR) {
6711 status = cmdStatus;
6712 }
6713 }
6714 dev = device & AUDIO_DEVICE_IN_ALL;
6715 if (dev) {
6716 status_t cmdStatus;
6717 uint32_t size = sizeof(status_t);
6718
6719 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6720 EFFECT_CMD_SET_INPUT_DEVICE,
6721 sizeof(uint32_t),
6722 &dev,
6723 &size,
6724 &cmdStatus);
6725 if (status2 == NO_ERROR) {
6726 status2 = cmdStatus;
6727 }
6728 if (status == NO_ERROR) {
6729 status = status2;
6730 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006731 }
6732 }
6733 return status;
6734}
6735
Glenn Kastenf78aee72012-01-04 11:00:47 -08006736status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737{
6738 Mutex::Autolock _l(mLock);
6739 status_t status = NO_ERROR;
6740 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006741 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006742 uint32_t size = sizeof(status_t);
6743 status = (*mEffectInterface)->command(mEffectInterface,
6744 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006745 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006746 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006747 &size,
6748 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749 if (status == NO_ERROR) {
6750 status = cmdStatus;
6751 }
6752 }
6753 return status;
6754}
6755
Eric Laurent59255e42011-07-27 19:49:51 -07006756void AudioFlinger::EffectModule::setSuspended(bool suspended)
6757{
6758 Mutex::Autolock _l(mLock);
6759 mSuspended = suspended;
6760}
Glenn Kastena3a85482012-01-04 11:01:11 -08006761
6762bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006763{
6764 Mutex::Autolock _l(mLock);
6765 return mSuspended;
6766}
6767
Mathias Agopian65ab4712010-07-14 17:59:35 -07006768status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6769{
6770 const size_t SIZE = 256;
6771 char buffer[SIZE];
6772 String8 result;
6773
6774 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6775 result.append(buffer);
6776
6777 bool locked = tryLock(mLock);
6778 // failed to lock - AudioFlinger is probably deadlocked
6779 if (!locked) {
6780 result.append("\t\tCould not lock Fx mutex:\n");
6781 }
6782
6783 result.append("\t\tSession Status State Engine:\n");
6784 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6785 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6786 result.append(buffer);
6787
6788 result.append("\t\tDescriptor:\n");
6789 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6790 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6791 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6792 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6793 result.append(buffer);
6794 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6795 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6796 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6797 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6798 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006799 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800 mDescriptor.apiVersion,
6801 mDescriptor.flags);
6802 result.append(buffer);
6803 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6804 mDescriptor.name);
6805 result.append(buffer);
6806 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6807 mDescriptor.implementor);
6808 result.append(buffer);
6809
6810 result.append("\t\t- Input configuration:\n");
6811 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6812 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6813 (uint32_t)mConfig.inputCfg.buffer.raw,
6814 mConfig.inputCfg.buffer.frameCount,
6815 mConfig.inputCfg.samplingRate,
6816 mConfig.inputCfg.channels,
6817 mConfig.inputCfg.format);
6818 result.append(buffer);
6819
6820 result.append("\t\t- Output configuration:\n");
6821 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6822 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6823 (uint32_t)mConfig.outputCfg.buffer.raw,
6824 mConfig.outputCfg.buffer.frameCount,
6825 mConfig.outputCfg.samplingRate,
6826 mConfig.outputCfg.channels,
6827 mConfig.outputCfg.format);
6828 result.append(buffer);
6829
6830 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6831 result.append(buffer);
6832 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6833 for (size_t i = 0; i < mHandles.size(); ++i) {
6834 sp<EffectHandle> handle = mHandles[i].promote();
6835 if (handle != 0) {
6836 handle->dump(buffer, SIZE);
6837 result.append(buffer);
6838 }
6839 }
6840
6841 result.append("\n");
6842
6843 write(fd, result.string(), result.length());
6844
6845 if (locked) {
6846 mLock.unlock();
6847 }
6848
6849 return NO_ERROR;
6850}
6851
6852// ----------------------------------------------------------------------------
6853// EffectHandle implementation
6854// ----------------------------------------------------------------------------
6855
6856#undef LOG_TAG
6857#define LOG_TAG "AudioFlinger::EffectHandle"
6858
6859AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6860 const sp<AudioFlinger::Client>& client,
6861 const sp<IEffectClient>& effectClient,
6862 int32_t priority)
6863 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006864 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006865 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866{
Steve Block3856b092011-10-20 11:56:00 +01006867 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006869 if (client == 0) {
6870 return;
6871 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006872 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6873 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6874 if (mCblkMemory != 0) {
6875 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6876
Glenn Kastena0d68332012-01-27 16:47:15 -08006877 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 new(mCblk) effect_param_cblk_t();
6879 mBuffer = (uint8_t *)mCblk + bufOffset;
6880 }
6881 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006882 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883 return;
6884 }
6885}
6886
6887AudioFlinger::EffectHandle::~EffectHandle()
6888{
Steve Block3856b092011-10-20 11:56:00 +01006889 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006890 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006891 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892}
6893
6894status_t AudioFlinger::EffectHandle::enable()
6895{
Steve Block3856b092011-10-20 11:56:00 +01006896 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 if (!mHasControl) return INVALID_OPERATION;
6898 if (mEffect == 0) return DEAD_OBJECT;
6899
Eric Laurentdb7c0792011-08-10 10:37:50 -07006900 if (mEnabled) {
6901 return NO_ERROR;
6902 }
6903
Eric Laurent59255e42011-07-27 19:49:51 -07006904 mEnabled = true;
6905
6906 sp<ThreadBase> thread = mEffect->thread().promote();
6907 if (thread != 0) {
6908 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6909 }
6910
6911 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6912 if (mEffect->suspended()) {
6913 return NO_ERROR;
6914 }
6915
Eric Laurentdb7c0792011-08-10 10:37:50 -07006916 status_t status = mEffect->setEnabled(true);
6917 if (status != NO_ERROR) {
6918 if (thread != 0) {
6919 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6920 }
6921 mEnabled = false;
6922 }
6923 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924}
6925
6926status_t AudioFlinger::EffectHandle::disable()
6927{
Steve Block3856b092011-10-20 11:56:00 +01006928 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006930 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931
Eric Laurentdb7c0792011-08-10 10:37:50 -07006932 if (!mEnabled) {
6933 return NO_ERROR;
6934 }
Eric Laurent59255e42011-07-27 19:49:51 -07006935 mEnabled = false;
6936
6937 if (mEffect->suspended()) {
6938 return NO_ERROR;
6939 }
6940
6941 status_t status = mEffect->setEnabled(false);
6942
6943 sp<ThreadBase> thread = mEffect->thread().promote();
6944 if (thread != 0) {
6945 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6946 }
6947
6948 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949}
6950
6951void AudioFlinger::EffectHandle::disconnect()
6952{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006953 disconnect(true);
6954}
6955
6956void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6957{
Steve Block3856b092011-10-20 11:56:00 +01006958 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 if (mEffect == 0) {
6960 return;
6961 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006962 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006963
Eric Laurenta85a74a2011-10-19 11:44:54 -07006964 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006965 sp<ThreadBase> thread = mEffect->thread().promote();
6966 if (thread != 0) {
6967 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6968 }
Eric Laurent59255e42011-07-27 19:49:51 -07006969 }
6970
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 // release sp on module => module destructor can be called now
6972 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006974 if (mCblk != NULL) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006975 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6976 }
6977 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6979 mClient.clear();
6980 }
6981}
6982
Eric Laurent25f43952010-07-28 05:40:18 -07006983status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6984 uint32_t cmdSize,
6985 void *pCmdData,
6986 uint32_t *replySize,
6987 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988{
Steve Block3856b092011-10-20 11:56:00 +01006989// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006990// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991
6992 // only get parameter command is permitted for applications not controlling the effect
6993 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6994 return INVALID_OPERATION;
6995 }
6996 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006997 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
6999 // handle commands that are not forwarded transparently to effect engine
7000 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7001 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7002 // no risk to block the whole media server process or mixer threads is we are stuck here
7003 Mutex::Autolock _l(mCblk->lock);
7004 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7005 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7006 mCblk->serverIndex = 0;
7007 mCblk->clientIndex = 0;
7008 return BAD_VALUE;
7009 }
7010 status_t status = NO_ERROR;
7011 while (mCblk->serverIndex < mCblk->clientIndex) {
7012 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007013 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007014 int *p = (int *)(mBuffer + mCblk->serverIndex);
7015 int size = *p++;
7016 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007017 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 break;
7019 }
7020 effect_param_t *param = (effect_param_t *)p;
7021 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007022 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007023 mCblk->serverIndex += size;
7024 continue;
7025 }
Eric Laurent25f43952010-07-28 05:40:18 -07007026 uint32_t psize = sizeof(effect_param_t) +
7027 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7028 param->vsize;
7029 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7030 psize,
7031 p,
7032 &rsize,
7033 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007034 // stop at first error encountered
7035 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007037 *(int *)pReplyData = reply;
7038 break;
7039 } else if (reply != NO_ERROR) {
7040 *(int *)pReplyData = reply;
7041 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042 }
7043 mCblk->serverIndex += size;
7044 }
7045 mCblk->serverIndex = 0;
7046 mCblk->clientIndex = 0;
7047 return status;
7048 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007049 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 return enable();
7051 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007052 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 return disable();
7054 }
7055
7056 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7057}
7058
7059sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7060 return mCblkMemory;
7061}
7062
Eric Laurent59255e42011-07-27 19:49:51 -07007063void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007064{
Steve Block3856b092011-10-20 11:56:00 +01007065 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066
7067 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007068 mEnabled = enabled;
7069
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070 if (signal && mEffectClient != 0) {
7071 mEffectClient->controlStatusChanged(hasControl);
7072 }
7073}
7074
Eric Laurent25f43952010-07-28 05:40:18 -07007075void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7076 uint32_t cmdSize,
7077 void *pCmdData,
7078 uint32_t replySize,
7079 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080{
7081 if (mEffectClient != 0) {
7082 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7083 }
7084}
7085
7086
7087
7088void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7089{
7090 if (mEffectClient != 0) {
7091 mEffectClient->enableStatusChanged(enabled);
7092 }
7093}
7094
7095status_t AudioFlinger::EffectHandle::onTransact(
7096 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7097{
7098 return BnEffect::onTransact(code, data, reply, flags);
7099}
7100
7101
7102void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7103{
Glenn Kastena0d68332012-01-27 16:47:15 -08007104 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105
7106 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007107 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108 mPriority,
7109 mHasControl,
7110 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007111 mCblk ? mCblk->clientIndex : 0,
7112 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113 );
7114
7115 if (locked) {
7116 mCblk->lock.unlock();
7117 }
7118}
7119
7120#undef LOG_TAG
7121#define LOG_TAG "AudioFlinger::EffectChain"
7122
7123AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7124 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007125 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007126 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7127 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128{
Dima Zavinfce7a472011-04-19 22:30:36 -07007129 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007130 sp<ThreadBase> thread = mThread.promote();
7131 if (thread == 0) {
7132 return;
7133 }
7134 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7135 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007136}
7137
7138AudioFlinger::EffectChain::~EffectChain()
7139{
7140 if (mOwnInBuffer) {
7141 delete mInBuffer;
7142 }
7143
7144}
7145
Eric Laurent59255e42011-07-27 19:49:51 -07007146// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007147sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148{
7149 sp<EffectModule> effect;
7150 size_t size = mEffects.size();
7151
7152 for (size_t i = 0; i < size; i++) {
7153 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7154 effect = mEffects[i];
7155 break;
7156 }
7157 }
7158 return effect;
7159}
7160
Eric Laurent59255e42011-07-27 19:49:51 -07007161// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007162sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163{
7164 sp<EffectModule> effect;
7165 size_t size = mEffects.size();
7166
7167 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007168 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7169 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170 effect = mEffects[i];
7171 break;
7172 }
7173 }
7174 return effect;
7175}
7176
Eric Laurent59255e42011-07-27 19:49:51 -07007177// getEffectFromType_l() must be called with ThreadBase::mLock held
7178sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7179 const effect_uuid_t *type)
7180{
7181 sp<EffectModule> effect;
7182 size_t size = mEffects.size();
7183
7184 for (size_t i = 0; i < size; i++) {
7185 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7186 effect = mEffects[i];
7187 break;
7188 }
7189 }
7190 return effect;
7191}
7192
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193// Must be called with EffectChain::mLock locked
7194void AudioFlinger::EffectChain::process_l()
7195{
Eric Laurentdac69112010-09-28 14:09:57 -07007196 sp<ThreadBase> thread = mThread.promote();
7197 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007198 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007199 return;
7200 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007201 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7202 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007203 // always process effects unless no more tracks are on the session and the effect tail
7204 // has been rendered
7205 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007206 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007207 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007208
Eric Laurent544fe9b2011-11-11 15:42:52 -08007209 if (!tracksOnSession && mTailBufferCount == 0) {
7210 doProcess = false;
7211 }
7212
7213 if (activeTrackCnt() == 0) {
7214 // if no track is active and the effect tail has not been rendered,
7215 // the input buffer must be cleared here as the mixer process will not do it
7216 if (tracksOnSession || mTailBufferCount > 0) {
7217 size_t numSamples = thread->frameCount() * thread->channelCount();
7218 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7219 if (mTailBufferCount > 0) {
7220 mTailBufferCount--;
7221 }
7222 }
7223 }
Eric Laurentdac69112010-09-28 14:09:57 -07007224 }
7225
Mathias Agopian65ab4712010-07-14 17:59:35 -07007226 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007227 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007228 for (size_t i = 0; i < size; i++) {
7229 mEffects[i]->process();
7230 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231 }
7232 for (size_t i = 0; i < size; i++) {
7233 mEffects[i]->updateState();
7234 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235}
7236
Eric Laurentcab11242010-07-15 12:50:15 -07007237// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007238status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007239{
7240 effect_descriptor_t desc = effect->desc();
7241 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7242
7243 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007244 effect->setChain(this);
7245 sp<ThreadBase> thread = mThread.promote();
7246 if (thread == 0) {
7247 return NO_INIT;
7248 }
7249 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007250
7251 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7252 // Auxiliary effects are inserted at the beginning of mEffects vector as
7253 // they are processed first and accumulated in chain input buffer
7254 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007255
Mathias Agopian65ab4712010-07-14 17:59:35 -07007256 // the input buffer for auxiliary effect contains mono samples in
7257 // 32 bit format. This is to avoid saturation in AudoMixer
7258 // accumulation stage. Saturation is done in EffectModule::process() before
7259 // calling the process in effect engine
7260 size_t numSamples = thread->frameCount();
7261 int32_t *buffer = new int32_t[numSamples];
7262 memset(buffer, 0, numSamples * sizeof(int32_t));
7263 effect->setInBuffer((int16_t *)buffer);
7264 // auxiliary effects output samples to chain input buffer for further processing
7265 // by insert effects
7266 effect->setOutBuffer(mInBuffer);
7267 } else {
7268 // Insert effects are inserted at the end of mEffects vector as they are processed
7269 // after track and auxiliary effects.
7270 // Insert effect order as a function of indicated preference:
7271 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7272 // another effect is present
7273 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7274 // last effect claiming first position
7275 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7276 // first effect claiming last position
7277 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7278 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7279 // already present
7280
7281 int size = (int)mEffects.size();
7282 int idx_insert = size;
7283 int idx_insert_first = -1;
7284 int idx_insert_last = -1;
7285
7286 for (int i = 0; i < size; i++) {
7287 effect_descriptor_t d = mEffects[i]->desc();
7288 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7289 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7290 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7291 // check invalid effect chaining combinations
7292 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7293 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007294 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 return INVALID_OPERATION;
7296 }
7297 // remember position of first insert effect and by default
7298 // select this as insert position for new effect
7299 if (idx_insert == size) {
7300 idx_insert = i;
7301 }
7302 // remember position of last insert effect claiming
7303 // first position
7304 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7305 idx_insert_first = i;
7306 }
7307 // remember position of first insert effect claiming
7308 // last position
7309 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7310 idx_insert_last == -1) {
7311 idx_insert_last = i;
7312 }
7313 }
7314 }
7315
7316 // modify idx_insert from first position if needed
7317 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7318 if (idx_insert_last != -1) {
7319 idx_insert = idx_insert_last;
7320 } else {
7321 idx_insert = size;
7322 }
7323 } else {
7324 if (idx_insert_first != -1) {
7325 idx_insert = idx_insert_first + 1;
7326 }
7327 }
7328
7329 // always read samples from chain input buffer
7330 effect->setInBuffer(mInBuffer);
7331
7332 // if last effect in the chain, output samples to chain
7333 // output buffer, otherwise to chain input buffer
7334 if (idx_insert == size) {
7335 if (idx_insert != 0) {
7336 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7337 mEffects[idx_insert-1]->configure();
7338 }
7339 effect->setOutBuffer(mOutBuffer);
7340 } else {
7341 effect->setOutBuffer(mInBuffer);
7342 }
7343 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007344
Steve Block3856b092011-10-20 11:56:00 +01007345 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 }
7347 effect->configure();
7348 return NO_ERROR;
7349}
7350
Eric Laurentcab11242010-07-15 12:50:15 -07007351// removeEffect_l() must be called with PlaybackThread::mLock held
7352size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353{
7354 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007355 int size = (int)mEffects.size();
7356 int i;
7357 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7358
7359 for (i = 0; i < size; i++) {
7360 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007361 // calling stop here will remove pre-processing effect from the audio HAL.
7362 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7363 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007364 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7365 mEffects[i]->state() == EffectModule::STOPPING) {
7366 mEffects[i]->stop();
7367 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7369 delete[] effect->inBuffer();
7370 } else {
7371 if (i == size - 1 && i != 0) {
7372 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7373 mEffects[i - 1]->configure();
7374 }
7375 }
7376 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007377 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007378 break;
7379 }
7380 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381
7382 return mEffects.size();
7383}
7384
Eric Laurentcab11242010-07-15 12:50:15 -07007385// setDevice_l() must be called with PlaybackThread::mLock held
7386void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387{
7388 size_t size = mEffects.size();
7389 for (size_t i = 0; i < size; i++) {
7390 mEffects[i]->setDevice(device);
7391 }
7392}
7393
Eric Laurentcab11242010-07-15 12:50:15 -07007394// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007395void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396{
7397 size_t size = mEffects.size();
7398 for (size_t i = 0; i < size; i++) {
7399 mEffects[i]->setMode(mode);
7400 }
7401}
7402
Eric Laurentcab11242010-07-15 12:50:15 -07007403// setVolume_l() must be called with PlaybackThread::mLock held
7404bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405{
7406 uint32_t newLeft = *left;
7407 uint32_t newRight = *right;
7408 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007409 int ctrlIdx = -1;
7410 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411
Eric Laurentcab11242010-07-15 12:50:15 -07007412 // first update volume controller
7413 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007414 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007415 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7416 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007417 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007418 break;
7419 }
7420 }
7421
7422 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007423 if (hasControl) {
7424 *left = mNewLeftVolume;
7425 *right = mNewRightVolume;
7426 }
7427 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007428 }
7429
7430 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007431 mLeftVolume = newLeft;
7432 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007433
7434 // second get volume update from volume controller
7435 if (ctrlIdx >= 0) {
7436 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007437 mNewLeftVolume = newLeft;
7438 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007439 }
7440 // then indicate volume to all other effects in chain.
7441 // Pass altered volume to effects before volume controller
7442 // and requested volume to effects after controller
7443 uint32_t lVol = newLeft;
7444 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007445
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007447 if ((int)i == ctrlIdx) continue;
7448 // this also works for ctrlIdx == -1 when there is no volume controller
7449 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007450 lVol = *left;
7451 rVol = *right;
7452 }
7453 mEffects[i]->setVolume(&lVol, &rVol, false);
7454 }
7455 *left = newLeft;
7456 *right = newRight;
7457
7458 return hasControl;
7459}
7460
Mathias Agopian65ab4712010-07-14 17:59:35 -07007461status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7462{
7463 const size_t SIZE = 256;
7464 char buffer[SIZE];
7465 String8 result;
7466
7467 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7468 result.append(buffer);
7469
7470 bool locked = tryLock(mLock);
7471 // failed to lock - AudioFlinger is probably deadlocked
7472 if (!locked) {
7473 result.append("\tCould not lock mutex:\n");
7474 }
7475
Eric Laurentcab11242010-07-15 12:50:15 -07007476 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7477 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007478 mEffects.size(),
7479 (uint32_t)mInBuffer,
7480 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007481 mActiveTrackCnt);
7482 result.append(buffer);
7483 write(fd, result.string(), result.size());
7484
7485 for (size_t i = 0; i < mEffects.size(); ++i) {
7486 sp<EffectModule> effect = mEffects[i];
7487 if (effect != 0) {
7488 effect->dump(fd, args);
7489 }
7490 }
7491
7492 if (locked) {
7493 mLock.unlock();
7494 }
7495
7496 return NO_ERROR;
7497}
7498
Eric Laurent59255e42011-07-27 19:49:51 -07007499// must be called with ThreadBase::mLock held
7500void AudioFlinger::EffectChain::setEffectSuspended_l(
7501 const effect_uuid_t *type, bool suspend)
7502{
7503 sp<SuspendedEffectDesc> desc;
7504 // use effect type UUID timelow as key as there is no real risk of identical
7505 // timeLow fields among effect type UUIDs.
7506 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7507 if (suspend) {
7508 if (index >= 0) {
7509 desc = mSuspendedEffects.valueAt(index);
7510 } else {
7511 desc = new SuspendedEffectDesc();
7512 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7513 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007514 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007515 }
7516 if (desc->mRefCount++ == 0) {
7517 sp<EffectModule> effect = getEffectIfEnabled(type);
7518 if (effect != 0) {
7519 desc->mEffect = effect;
7520 effect->setSuspended(true);
7521 effect->setEnabled(false);
7522 }
7523 }
7524 } else {
7525 if (index < 0) {
7526 return;
7527 }
7528 desc = mSuspendedEffects.valueAt(index);
7529 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007530 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007531 desc->mRefCount = 1;
7532 }
7533 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007534 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007535 if (desc->mEffect != 0) {
7536 sp<EffectModule> effect = desc->mEffect.promote();
7537 if (effect != 0) {
7538 effect->setSuspended(false);
7539 sp<EffectHandle> handle = effect->controlHandle();
7540 if (handle != 0) {
7541 effect->setEnabled(handle->enabled());
7542 }
7543 }
7544 desc->mEffect.clear();
7545 }
7546 mSuspendedEffects.removeItemsAt(index);
7547 }
7548 }
7549}
7550
7551// must be called with ThreadBase::mLock held
7552void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7553{
7554 sp<SuspendedEffectDesc> desc;
7555
7556 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7557 if (suspend) {
7558 if (index >= 0) {
7559 desc = mSuspendedEffects.valueAt(index);
7560 } else {
7561 desc = new SuspendedEffectDesc();
7562 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007563 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007564 }
7565 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007566 Vector< sp<EffectModule> > effects;
7567 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007568 for (size_t i = 0; i < effects.size(); i++) {
7569 setEffectSuspended_l(&effects[i]->desc().type, true);
7570 }
7571 }
7572 } else {
7573 if (index < 0) {
7574 return;
7575 }
7576 desc = mSuspendedEffects.valueAt(index);
7577 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007578 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007579 desc->mRefCount = 1;
7580 }
7581 if (--desc->mRefCount == 0) {
7582 Vector<const effect_uuid_t *> types;
7583 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7584 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7585 continue;
7586 }
7587 types.add(&mSuspendedEffects.valueAt(i)->mType);
7588 }
7589 for (size_t i = 0; i < types.size(); i++) {
7590 setEffectSuspended_l(types[i], false);
7591 }
Steve Block3856b092011-10-20 11:56:00 +01007592 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007593 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7594 }
7595 }
7596}
7597
Eric Laurent6bffdb82011-09-23 08:40:41 -07007598
7599// The volume effect is used for automated tests only
7600#ifndef OPENSL_ES_H_
7601static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7602 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7603const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7604#endif //OPENSL_ES_H_
7605
Eric Laurentdb7c0792011-08-10 10:37:50 -07007606bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7607{
7608 // auxiliary effects and visualizer are never suspended on output mix
7609 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7610 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007611 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7612 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007613 return false;
7614 }
7615 return true;
7616}
7617
Glenn Kastend0539712012-01-30 12:56:03 -08007618void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007619{
Glenn Kastend0539712012-01-30 12:56:03 -08007620 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007621 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007622 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7623 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007624 }
Eric Laurent59255e42011-07-27 19:49:51 -07007625 }
Eric Laurent59255e42011-07-27 19:49:51 -07007626}
7627
7628sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7629 const effect_uuid_t *type)
7630{
7631 sp<EffectModule> effect;
7632 effect = getEffectFromType_l(type);
7633 if (effect != 0 && !effect->isEnabled()) {
7634 effect.clear();
7635 }
7636 return effect;
7637}
7638
7639void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7640 bool enabled)
7641{
7642 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7643 if (enabled) {
7644 if (index < 0) {
7645 // if the effect is not suspend check if all effects are suspended
7646 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7647 if (index < 0) {
7648 return;
7649 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007650 if (!isEffectEligibleForSuspend(effect->desc())) {
7651 return;
7652 }
Eric Laurent59255e42011-07-27 19:49:51 -07007653 setEffectSuspended_l(&effect->desc().type, enabled);
7654 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007655 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007656 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007657 return;
7658 }
Eric Laurent59255e42011-07-27 19:49:51 -07007659 }
Steve Block3856b092011-10-20 11:56:00 +01007660 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007661 effect->desc().type.timeLow);
7662 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7663 // if effect is requested to suspended but was not yet enabled, supend it now.
7664 if (desc->mEffect == 0) {
7665 desc->mEffect = effect;
7666 effect->setEnabled(false);
7667 effect->setSuspended(true);
7668 }
7669 } else {
7670 if (index < 0) {
7671 return;
7672 }
Steve Block3856b092011-10-20 11:56:00 +01007673 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007674 effect->desc().type.timeLow);
7675 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7676 desc->mEffect.clear();
7677 effect->setSuspended(false);
7678 }
7679}
7680
Mathias Agopian65ab4712010-07-14 17:59:35 -07007681#undef LOG_TAG
7682#define LOG_TAG "AudioFlinger"
7683
7684// ----------------------------------------------------------------------------
7685
7686status_t AudioFlinger::onTransact(
7687 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7688{
7689 return BnAudioFlinger::onTransact(code, data, reply, flags);
7690}
7691
Mathias Agopian65ab4712010-07-14 17:59:35 -07007692}; // namespace android