blob: fb163d13ffc8b026890f7dd552f1abef345bdb06 [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"
Glenn Kasten44deb052012-02-05 18:09:08 -080051#include "ServiceUtilities.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070052
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
Mathias Agopian65ab4712010-07-14 17:59:35 -070064// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
Eric Laurentde070132010-07-13 04:45:46 -070066
Mathias Agopian65ab4712010-07-14 17:59:35 -070067namespace android {
68
Glenn Kastenec1d6b52011-12-12 09:04:45 -080069static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
70static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
73static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080074static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070075
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
80// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
84
85static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080086static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Glenn Kasten7dede872011-12-13 11:04:14 -080088// don't warn about blocked writes or record buffer overflows more often than this
89static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Eric Laurent7c7f10b2011-06-17 21:29:58 -070091// RecordThread loop sleep time upon application overrun or audio HAL read error
92static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
Glenn Kasten7dede872011-12-13 11:04:14 -080094// maximum time to wait for setParameters to complete
95static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070096
Eric Laurent7cafbb32011-11-22 18:50:29 -080097// minimum sleep time for the mixer thread loop when tracks are active but in underrun
98static const uint32_t kMinThreadSleepTimeUs = 5000;
99// maximum divider applied to the active sleep time in the mixer thread loop
100static const uint32_t kMaxThreadSleepTimeShift = 2;
101
102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103// ----------------------------------------------------------------------------
104
Gloria Wang9ee159b2011-02-24 14:51:45 -0800105// To collect the amplifier usage
106static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800107 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
108 if (service == NULL) {
109 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800110 return;
111 }
112
113 service->addBatteryData(params);
114}
115
Dima Zavin799a70e2011-04-18 16:57:27 -0700116static int load_audio_interface(const char *if_name, const hw_module_t **mod,
117 audio_hw_device_t **dev)
118{
119 int rc;
120
121 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
122 if (rc)
123 goto out;
124
125 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000126 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700127 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
128 if (rc)
129 goto out;
130
131 return 0;
132
133out:
134 *mod = NULL;
135 *dev = NULL;
136 return rc;
137}
138
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800139static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 "primary",
141 "a2dp",
142 "usb",
143};
144#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
148AudioFlinger::AudioFlinger()
149 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800150 mPrimaryHardwareDev(NULL),
151 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
152 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
153 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700154 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700156}
157
158void AudioFlinger::onFirstRef()
159{
Dima Zavin799a70e2011-04-18 16:57:27 -0700160 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700161
Eric Laurent93575202011-01-18 18:39:02 -0800162 Mutex::Autolock _l(mLock);
163
Dima Zavin799a70e2011-04-18 16:57:27 -0700164 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
167 const hw_module_t *mod;
168 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
171 if (rc)
172 continue;
173
Steve Blockdf64d152012-01-04 20:05:49 +0000174 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 mod->name, mod->id);
176 mAudioHwDevs.push(dev);
177
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800178 if (mPrimaryHardwareDev == NULL) {
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000180 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700181 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 }
183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700184
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800185 if (mPrimaryHardwareDev == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000186 ALOGE("Primary audio interface not found");
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800187 // proceed, all later accesses to mPrimaryHardwareDev verify it's safe with initCheck()
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 }
189
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800190 // Currently (mPrimaryHardwareDev == NULL) == (mAudioHwDevs.size() == 0), but the way the
191 // primary HW dev is selected can change so these conditions might not always be equivalent.
192 // When that happens, re-visit all the code that assumes this.
193
194 AutoMutex lock(mHardwareLock);
195
Dima Zavin799a70e2011-04-18 16:57:27 -0700196 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
197 audio_hw_device_t *dev = mAudioHwDevs[i];
198
199 mHardwareStatus = AUDIO_HW_INIT;
200 rc = dev->init_check(dev);
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800201 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 if (rc == 0) {
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800203 mMode = AUDIO_MODE_NORMAL; // assigned multiple times with same value
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 mHardwareStatus = AUDIO_HW_SET_MODE;
205 dev->set_mode(dev, mMode);
206 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
207 dev->set_master_volume(dev, 1.0f);
208 mHardwareStatus = AUDIO_HW_IDLE;
209 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211}
212
213AudioFlinger::~AudioFlinger()
214{
Dima Zavin799a70e2011-04-18 16:57:27 -0700215
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216 while (!mRecordThreads.isEmpty()) {
217 // closeInput() will remove first entry from mRecordThreads
218 closeInput(mRecordThreads.keyAt(0));
219 }
220 while (!mPlaybackThreads.isEmpty()) {
221 // closeOutput() will remove first entry from mPlaybackThreads
222 closeOutput(mPlaybackThreads.keyAt(0));
223 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700224
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800225 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
226 // no mHardwareLock needed, as there are no other references to this
227 audio_hw_device_close(mAudioHwDevs[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700228 }
229}
230
Dima Zavin799a70e2011-04-18 16:57:27 -0700231audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
232{
233 /* first matching HW device is returned */
234 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
235 audio_hw_device_t *dev = mAudioHwDevs[i];
236 if ((dev->get_supported_devices(dev) & devices) == devices)
237 return dev;
238 }
239 return NULL;
240}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700241
242status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
243{
244 const size_t SIZE = 256;
245 char buffer[SIZE];
246 String8 result;
247
248 result.append("Clients:\n");
249 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800250 sp<Client> client = mClients.valueAt(i).promote();
251 if (client != 0) {
252 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
253 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700254 }
255 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700256
257 result.append("Global session refs:\n");
258 result.append(" session pid cnt\n");
259 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
260 AudioSessionRef *r = mAudioSessionRefs[i];
261 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
262 result.append(buffer);
263 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700264 write(fd, result.string(), result.size());
265 return NO_ERROR;
266}
267
268
269status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
270{
271 const size_t SIZE = 256;
272 char buffer[SIZE];
273 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800274 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700275
276 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
277 result.append(buffer);
278 write(fd, result.string(), result.size());
279 return NO_ERROR;
280}
281
282status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 snprintf(buffer, SIZE, "Permission Denial: "
288 "can't dump AudioFlinger from pid=%d, uid=%d\n",
289 IPCThreadState::self()->getCallingPid(),
290 IPCThreadState::self()->getCallingUid());
291 result.append(buffer);
292 write(fd, result.string(), result.size());
293 return NO_ERROR;
294}
295
296static bool tryLock(Mutex& mutex)
297{
298 bool locked = false;
299 for (int i = 0; i < kDumpLockRetries; ++i) {
300 if (mutex.tryLock() == NO_ERROR) {
301 locked = true;
302 break;
303 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800304 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700305 }
306 return locked;
307}
308
309status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
310{
Glenn Kasten44deb052012-02-05 18:09:08 -0800311 if (!dumpAllowed()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700312 dumpPermissionDenial(fd, args);
313 } else {
314 // get state of hardware lock
315 bool hardwareLocked = tryLock(mHardwareLock);
316 if (!hardwareLocked) {
317 String8 result(kHardwareLockedString);
318 write(fd, result.string(), result.size());
319 } else {
320 mHardwareLock.unlock();
321 }
322
323 bool locked = tryLock(mLock);
324
325 // failed to lock - AudioFlinger is probably deadlocked
326 if (!locked) {
327 String8 result(kDeadlockedString);
328 write(fd, result.string(), result.size());
329 }
330
331 dumpClients(fd, args);
332 dumpInternals(fd, args);
333
334 // dump playback threads
335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
336 mPlaybackThreads.valueAt(i)->dump(fd, args);
337 }
338
339 // dump record threads
340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
341 mRecordThreads.valueAt(i)->dump(fd, args);
342 }
343
Dima Zavin799a70e2011-04-18 16:57:27 -0700344 // dump all hardware devs
345 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
346 audio_hw_device_t *dev = mAudioHwDevs[i];
347 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348 }
349 if (locked) mLock.unlock();
350 }
351 return NO_ERROR;
352}
353
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800354sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
355{
356 // If pid is already in the mClients wp<> map, then use that entry
357 // (for which promote() is always != 0), otherwise create a new entry and Client.
358 sp<Client> client = mClients.valueFor(pid).promote();
359 if (client == 0) {
360 client = new Client(this, pid);
361 mClients.add(pid, client);
362 }
363
364 return client;
365}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366
367// IAudioFlinger interface
368
369
370sp<IAudioTrack> AudioFlinger::createTrack(
371 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800372 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800374 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700375 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700376 int frameCount,
377 uint32_t flags,
378 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800379 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 int *sessionId,
381 status_t *status)
382{
383 sp<PlaybackThread::Track> track;
384 sp<TrackHandle> trackHandle;
385 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700386 status_t lStatus;
387 int lSessionId;
388
Glenn Kasten263709e2012-01-06 08:40:01 -0800389 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
390 // but if someone uses binder directly they could bypass that and cause us to crash
391 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000392 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700393 lStatus = BAD_VALUE;
394 goto Exit;
395 }
396
397 {
398 Mutex::Autolock _l(mLock);
399 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700400 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000402 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800407 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700408
Steve Block3856b092011-10-20 11:56:00 +0100409 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700410 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700411 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700412 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
413 if (mPlaybackThreads.keyAt(i) != output) {
414 // prevent same audio session on different output threads
415 uint32_t sessions = t->hasAudioSession(*sessionId);
416 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000417 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700418 lStatus = BAD_VALUE;
419 goto Exit;
420 }
421 // check if an effect with same session ID is waiting for a track to be created
422 if (sessions & PlaybackThread::EFFECT_SESSION) {
423 effectThread = t.get();
424 }
Eric Laurentde070132010-07-13 04:45:46 -0700425 }
426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427 lSessionId = *sessionId;
428 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700429 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700430 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 if (sessionId != NULL) {
432 *sessionId = lSessionId;
433 }
434 }
Steve Block3856b092011-10-20 11:56:00 +0100435 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700436
437 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700438 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700439
440 // move effect chain to this output thread if an effect on same session was waiting
441 // for a track to be created
442 if (lStatus == NO_ERROR && effectThread != NULL) {
443 Mutex::Autolock _dl(thread->mLock);
444 Mutex::Autolock _sl(effectThread->mLock);
445 moveEffectChain_l(lSessionId, effectThread, thread, true);
446 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700447 }
448 if (lStatus == NO_ERROR) {
449 trackHandle = new TrackHandle(track);
450 } else {
451 // remove local strong reference to Client before deleting the Track so that the Client
452 // destructor is called by the TrackBase destructor with mLock held
453 client.clear();
454 track.clear();
455 }
456
457Exit:
458 if(status) {
459 *status = lStatus;
460 }
461 return trackHandle;
462}
463
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800464uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465{
466 Mutex::Autolock _l(mLock);
467 PlaybackThread *thread = checkPlaybackThread_l(output);
468 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000469 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700470 return 0;
471 }
472 return thread->sampleRate();
473}
474
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800475int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476{
477 Mutex::Autolock _l(mLock);
478 PlaybackThread *thread = checkPlaybackThread_l(output);
479 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000480 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481 return 0;
482 }
483 return thread->channelCount();
484}
485
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800486audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700487{
488 Mutex::Autolock _l(mLock);
489 PlaybackThread *thread = checkPlaybackThread_l(output);
490 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000491 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800492 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493 }
494 return thread->format();
495}
496
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800497size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700498{
499 Mutex::Autolock _l(mLock);
500 PlaybackThread *thread = checkPlaybackThread_l(output);
501 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000502 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700503 return 0;
504 }
505 return thread->frameCount();
506}
507
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800508uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700509{
510 Mutex::Autolock _l(mLock);
511 PlaybackThread *thread = checkPlaybackThread_l(output);
512 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000513 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700514 return 0;
515 }
516 return thread->latency();
517}
518
519status_t AudioFlinger::setMasterVolume(float value)
520{
Eric Laurenta1884f92011-08-23 08:25:03 -0700521 status_t ret = initCheck();
522 if (ret != NO_ERROR) {
523 return ret;
524 }
525
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526 // check calling permissions
527 if (!settingsAllowed()) {
528 return PERMISSION_DENIED;
529 }
530
531 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800532 { // scope for the lock
533 AutoMutex lock(mHardwareLock);
534 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700535 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800536 value = 1.0f;
537 }
538 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540
Eric Laurent93575202011-01-18 18:39:02 -0800541 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 mMasterVolume = value;
543 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
544 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
545
546 return NO_ERROR;
547}
548
Glenn Kastenf78aee72012-01-04 11:00:47 -0800549status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700550{
Eric Laurenta1884f92011-08-23 08:25:03 -0700551 status_t ret = initCheck();
552 if (ret != NO_ERROR) {
553 return ret;
554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555
556 // check calling permissions
557 if (!settingsAllowed()) {
558 return PERMISSION_DENIED;
559 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800560 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000561 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 return BAD_VALUE;
563 }
564
565 { // scope for the lock
566 AutoMutex lock(mHardwareLock);
567 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700568 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569 mHardwareStatus = AUDIO_HW_IDLE;
570 }
571
572 if (NO_ERROR == ret) {
573 Mutex::Autolock _l(mLock);
574 mMode = mode;
575 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
576 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 }
578
579 return ret;
580}
581
582status_t AudioFlinger::setMicMute(bool state)
583{
Eric Laurenta1884f92011-08-23 08:25:03 -0700584 status_t ret = initCheck();
585 if (ret != NO_ERROR) {
586 return ret;
587 }
588
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 // check calling permissions
590 if (!settingsAllowed()) {
591 return PERMISSION_DENIED;
592 }
593
594 AutoMutex lock(mHardwareLock);
595 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700596 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 mHardwareStatus = AUDIO_HW_IDLE;
598 return ret;
599}
600
601bool AudioFlinger::getMicMute() const
602{
Eric Laurenta1884f92011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return false;
606 }
607
Dima Zavinfce7a472011-04-19 22:30:36 -0700608 bool state = AUDIO_MODE_INVALID;
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800609 AutoMutex lock(mHardwareLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700611 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700612 mHardwareStatus = AUDIO_HW_IDLE;
613 return state;
614}
615
616status_t AudioFlinger::setMasterMute(bool muted)
617{
618 // check calling permissions
619 if (!settingsAllowed()) {
620 return PERMISSION_DENIED;
621 }
622
Eric Laurent93575202011-01-18 18:39:02 -0800623 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 mMasterMute = muted;
625 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
626 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
627
628 return NO_ERROR;
629}
630
631float AudioFlinger::masterVolume() const
632{
Glenn Kasten98067102011-12-13 11:47:54 -0800633 Mutex::Autolock _l(mLock);
634 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635}
636
637bool AudioFlinger::masterMute() const
638{
Glenn Kasten98067102011-12-13 11:47:54 -0800639 Mutex::Autolock _l(mLock);
640 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641}
642
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800643status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
644 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645{
646 // check calling permissions
647 if (!settingsAllowed()) {
648 return PERMISSION_DENIED;
649 }
650
Glenn Kasten263709e2012-01-06 08:40:01 -0800651 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000652 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 return BAD_VALUE;
654 }
655
656 AutoMutex lock(mLock);
657 PlaybackThread *thread = NULL;
658 if (output) {
659 thread = checkPlaybackThread_l(output);
660 if (thread == NULL) {
661 return BAD_VALUE;
662 }
663 }
664
665 mStreamTypes[stream].volume = value;
666
667 if (thread == NULL) {
668 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
669 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
670 }
671 } else {
672 thread->setStreamVolume(stream, value);
673 }
674
675 return NO_ERROR;
676}
677
Glenn Kastenfff6d712012-01-12 16:38:12 -0800678status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679{
680 // check calling permissions
681 if (!settingsAllowed()) {
682 return PERMISSION_DENIED;
683 }
684
Glenn Kasten263709e2012-01-06 08:40:01 -0800685 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700686 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000687 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 return BAD_VALUE;
689 }
690
Eric Laurent93575202011-01-18 18:39:02 -0800691 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 mStreamTypes[stream].mute = muted;
693 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
694 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
695
696 return NO_ERROR;
697}
698
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800699float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700{
Glenn Kasten263709e2012-01-06 08:40:01 -0800701 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return 0.0f;
703 }
704
705 AutoMutex lock(mLock);
706 float volume;
707 if (output) {
708 PlaybackThread *thread = checkPlaybackThread_l(output);
709 if (thread == NULL) {
710 return 0.0f;
711 }
712 volume = thread->streamVolume(stream);
713 } else {
714 volume = mStreamTypes[stream].volume;
715 }
716
717 return volume;
718}
719
Glenn Kastenfff6d712012-01-12 16:38:12 -0800720bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721{
Glenn Kasten263709e2012-01-06 08:40:01 -0800722 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 return true;
724 }
725
726 return mStreamTypes[stream].mute;
727}
728
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800729status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730{
731 status_t result;
732
Glenn Kasten23d82a92012-02-03 11:10:00 -0800733 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700734 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
735 // check calling permissions
736 if (!settingsAllowed()) {
737 return PERMISSION_DENIED;
738 }
739
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 // ioHandle == 0 means the parameters are global to the audio hardware interface
741 if (ioHandle == 0) {
742 AutoMutex lock(mHardwareLock);
743 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700744 status_t final_result = NO_ERROR;
745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 audio_hw_device_t *dev = mAudioHwDevs[i];
747 result = dev->set_parameters(dev, keyValuePairs.string());
748 final_result = result ?: final_result;
749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700751 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
752 AudioParameter param = AudioParameter(keyValuePairs);
753 String8 value;
754 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
755 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700756 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
757 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700758 for (size_t i = 0; i < mRecordThreads.size(); i++) {
759 sp<RecordThread> thread = mRecordThreads.valueAt(i);
760 RecordThread::RecordTrack *track = thread->track();
761 if (track != NULL) {
762 audio_devices_t device = (audio_devices_t)(
763 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700764 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 thread->setEffectSuspended(FX_IID_AEC,
766 suspend,
767 track->sessionId());
768 thread->setEffectSuspended(FX_IID_NS,
769 suspend,
770 track->sessionId());
771 }
772 }
Eric Laurentbee53372011-08-29 12:42:48 -0700773 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700774 }
775 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700776 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777 }
778
779 // hold a strong ref on thread in case closeOutput() or closeInput() is called
780 // and the thread is exited once the lock is released
781 sp<ThreadBase> thread;
782 {
783 Mutex::Autolock _l(mLock);
784 thread = checkPlaybackThread_l(ioHandle);
785 if (thread == NULL) {
786 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800787 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700788 // indicate output device change to all input threads for pre processing
789 AudioParameter param = AudioParameter(keyValuePairs);
790 int value;
791 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
792 for (size_t i = 0; i < mRecordThreads.size(); i++) {
793 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
794 }
795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
797 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800798 if (thread != 0) {
799 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 }
801 return BAD_VALUE;
802}
803
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800804String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800806// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700807// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
808
809 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700810 String8 out_s8;
811
Dima Zavin799a70e2011-04-18 16:57:27 -0700812 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
813 audio_hw_device_t *dev = mAudioHwDevs[i];
814 char *s = dev->get_parameters(dev, keys.string());
815 out_s8 += String8(s);
816 free(s);
817 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700818 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 }
820
821 Mutex::Autolock _l(mLock);
822
823 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
824 if (playbackThread != NULL) {
825 return playbackThread->getParameters(keys);
826 }
827 RecordThread *recordThread = checkRecordThread_l(ioHandle);
828 if (recordThread != NULL) {
829 return recordThread->getParameters(keys);
830 }
831 return String8("");
832}
833
Glenn Kastenf587ba52012-01-26 16:25:10 -0800834size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700835{
Eric Laurenta1884f92011-08-23 08:25:03 -0700836 status_t ret = initCheck();
837 if (ret != NO_ERROR) {
838 return 0;
839 }
840
Glenn Kasten2b213bc2012-02-02 14:05:20 -0800841 AutoMutex lock(mHardwareLock);
842 mHardwareStatus = AUDIO_HW_GET_INPUT_BUFFER_SIZE;
843 size_t size = mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
844 mHardwareStatus = AUDIO_HW_IDLE;
845 return size;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700846}
847
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800848unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849{
850 if (ioHandle == 0) {
851 return 0;
852 }
853
854 Mutex::Autolock _l(mLock);
855
856 RecordThread *recordThread = checkRecordThread_l(ioHandle);
857 if (recordThread != NULL) {
858 return recordThread->getInputFramesLost();
859 }
860 return 0;
861}
862
863status_t AudioFlinger::setVoiceVolume(float value)
864{
Eric Laurenta1884f92011-08-23 08:25:03 -0700865 status_t ret = initCheck();
866 if (ret != NO_ERROR) {
867 return ret;
868 }
869
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 // check calling permissions
871 if (!settingsAllowed()) {
872 return PERMISSION_DENIED;
873 }
874
875 AutoMutex lock(mHardwareLock);
876 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700877 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700878 mHardwareStatus = AUDIO_HW_IDLE;
879
880 return ret;
881}
882
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800883status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
884 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885{
886 status_t status;
887
888 Mutex::Autolock _l(mLock);
889
890 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
891 if (playbackThread != NULL) {
892 return playbackThread->getRenderPosition(halFrames, dspFrames);
893 }
894
895 return BAD_VALUE;
896}
897
898void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
899{
900
901 Mutex::Autolock _l(mLock);
902
Glenn Kastenbb001922012-02-03 11:10:26 -0800903 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700904 if (mNotificationClients.indexOfKey(pid) < 0) {
905 sp<NotificationClient> notificationClient = new NotificationClient(this,
906 client,
907 pid);
Steve Block3856b092011-10-20 11:56:00 +0100908 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700909
910 mNotificationClients.add(pid, notificationClient);
911
912 sp<IBinder> binder = client->asBinder();
913 binder->linkToDeath(notificationClient);
914
915 // the config change is always sent from playback or record threads to avoid deadlock
916 // with AudioSystem::gLock
917 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
918 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
919 }
920
921 for (size_t i = 0; i < mRecordThreads.size(); i++) {
922 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
923 }
924 }
925}
926
927void AudioFlinger::removeNotificationClient(pid_t pid)
928{
929 Mutex::Autolock _l(mLock);
930
931 int index = mNotificationClients.indexOfKey(pid);
932 if (index >= 0) {
933 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100934 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935 mNotificationClients.removeItem(pid);
936 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700937
Steve Block3856b092011-10-20 11:56:00 +0100938 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700939 int num = mAudioSessionRefs.size();
940 bool removed = false;
941 for (int i = 0; i< num; i++) {
942 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100943 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700944 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100945 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700946 mAudioSessionRefs.removeAt(i);
947 delete ref;
948 removed = true;
949 i--;
950 num--;
951 }
952 }
953 if (removed) {
954 purgeStaleEffects_l();
955 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700956}
957
958// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800959void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960{
961 size_t size = mNotificationClients.size();
962 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800963 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
964 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965 }
966}
967
968// removeClient_l() must be called with AudioFlinger::mLock held
969void AudioFlinger::removeClient_l(pid_t pid)
970{
Steve Block3856b092011-10-20 11:56:00 +0100971 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700972 mClients.removeItem(pid);
973}
974
975
976// ----------------------------------------------------------------------------
977
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800978AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
979 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800981 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800982 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
983 // mChannelMask
984 mChannelCount(0),
985 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
986 mParamStatus(NO_ERROR),
Glenn Kastenb28686f2012-01-06 08:39:38 -0800987 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800988 mDevice(device),
989 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -0700990{
991}
992
993AudioFlinger::ThreadBase::~ThreadBase()
994{
995 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700996 // do not lock the mutex in destructor
997 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700998 if (mPowerManager != 0) {
999 sp<IBinder> binder = mPowerManager->asBinder();
1000 binder->unlinkToDeath(mDeathRecipient);
1001 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001002}
1003
1004void AudioFlinger::ThreadBase::exit()
1005{
Steve Block3856b092011-10-20 11:56:00 +01001006 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001008 // This lock prevents the following race in thread (uniprocessor for illustration):
1009 // if (!exitPending()) {
1010 // // context switch from here to exit()
1011 // // exit() calls requestExit(), what exitPending() observes
1012 // // exit() calls signal(), which is dropped since no waiters
1013 // // context switch back from exit() to here
1014 // mWaitWorkCV.wait(...);
1015 // // now thread is hung
1016 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001017 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001018 requestExit();
1019 mWaitWorkCV.signal();
1020 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001021 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1022 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001023 requestExitAndWait();
1024}
1025
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1027{
1028 status_t status;
1029
Steve Block3856b092011-10-20 11:56:00 +01001030 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001031 Mutex::Autolock _l(mLock);
1032
1033 mNewParameters.add(keyValuePairs);
1034 mWaitWorkCV.signal();
1035 // wait condition with timeout in case the thread loop has exited
1036 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001037 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001038 status = mParamStatus;
1039 mWaitWorkCV.signal();
1040 } else {
1041 status = TIMED_OUT;
1042 }
1043 return status;
1044}
1045
1046void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1047{
1048 Mutex::Autolock _l(mLock);
1049 sendConfigEvent_l(event, param);
1050}
1051
1052// sendConfigEvent_l() must be called with ThreadBase::mLock held
1053void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1054{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001055 ConfigEvent configEvent;
1056 configEvent.mEvent = event;
1057 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001059 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001060 mWaitWorkCV.signal();
1061}
1062
1063void AudioFlinger::ThreadBase::processConfigEvents()
1064{
1065 mLock.lock();
1066 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001067 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001068 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069 mConfigEvents.removeAt(0);
1070 // release mLock before locking AudioFlinger mLock: lock order is always
1071 // AudioFlinger then ThreadBase to avoid cross deadlock
1072 mLock.unlock();
1073 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001074 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mLock.lock();
1077 }
1078 mLock.unlock();
1079}
1080
1081status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1082{
1083 const size_t SIZE = 256;
1084 char buffer[SIZE];
1085 String8 result;
1086
1087 bool locked = tryLock(mLock);
1088 if (!locked) {
1089 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1090 write(fd, buffer, strlen(buffer));
1091 }
1092
1093 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1094 result.append(buffer);
1095 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1096 result.append(buffer);
1097 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1098 result.append(buffer);
1099 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1100 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001101 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1102 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1104 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001105 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001106 result.append(buffer);
1107
1108 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1109 result.append(buffer);
1110 result.append(" Index Command");
1111 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1112 snprintf(buffer, SIZE, "\n %02d ", i);
1113 result.append(buffer);
1114 result.append(mNewParameters[i]);
1115 }
1116
1117 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1118 result.append(buffer);
1119 snprintf(buffer, SIZE, " Index event param\n");
1120 result.append(buffer);
1121 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001122 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 result.append(buffer);
1124 }
1125 result.append("\n");
1126
1127 write(fd, result.string(), result.size());
1128
1129 if (locked) {
1130 mLock.unlock();
1131 }
1132 return NO_ERROR;
1133}
1134
Eric Laurent1d2bff02011-07-24 17:49:51 -07001135status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1136{
1137 const size_t SIZE = 256;
1138 char buffer[SIZE];
1139 String8 result;
1140
1141 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1142 write(fd, buffer, strlen(buffer));
1143
1144 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1145 sp<EffectChain> chain = mEffectChains[i];
1146 if (chain != 0) {
1147 chain->dump(fd, args);
1148 }
1149 }
1150 return NO_ERROR;
1151}
1152
Eric Laurentfeb0db62011-07-22 09:04:31 -07001153void AudioFlinger::ThreadBase::acquireWakeLock()
1154{
1155 Mutex::Autolock _l(mLock);
1156 acquireWakeLock_l();
1157}
1158
1159void AudioFlinger::ThreadBase::acquireWakeLock_l()
1160{
1161 if (mPowerManager == 0) {
1162 // use checkService() to avoid blocking if power service is not up yet
1163 sp<IBinder> binder =
1164 defaultServiceManager()->checkService(String16("power"));
1165 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001166 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001167 } else {
1168 mPowerManager = interface_cast<IPowerManager>(binder);
1169 binder->linkToDeath(mDeathRecipient);
1170 }
1171 }
1172 if (mPowerManager != 0) {
1173 sp<IBinder> binder = new BBinder();
1174 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1175 binder,
1176 String16(mName));
1177 if (status == NO_ERROR) {
1178 mWakeLockToken = binder;
1179 }
Steve Block3856b092011-10-20 11:56:00 +01001180 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001181 }
1182}
1183
1184void AudioFlinger::ThreadBase::releaseWakeLock()
1185{
1186 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001187 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001188}
1189
1190void AudioFlinger::ThreadBase::releaseWakeLock_l()
1191{
1192 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001193 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001194 if (mPowerManager != 0) {
1195 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1196 }
1197 mWakeLockToken.clear();
1198 }
1199}
1200
1201void AudioFlinger::ThreadBase::clearPowerManager()
1202{
1203 Mutex::Autolock _l(mLock);
1204 releaseWakeLock_l();
1205 mPowerManager.clear();
1206}
1207
1208void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1209{
1210 sp<ThreadBase> thread = mThread.promote();
1211 if (thread != 0) {
1212 thread->clearPowerManager();
1213 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001214 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001215}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001216
Eric Laurent59255e42011-07-27 19:49:51 -07001217void AudioFlinger::ThreadBase::setEffectSuspended(
1218 const effect_uuid_t *type, bool suspend, int sessionId)
1219{
1220 Mutex::Autolock _l(mLock);
1221 setEffectSuspended_l(type, suspend, sessionId);
1222}
1223
1224void AudioFlinger::ThreadBase::setEffectSuspended_l(
1225 const effect_uuid_t *type, bool suspend, int sessionId)
1226{
Glenn Kasten090f0192012-01-30 13:00:02 -08001227 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001228 if (chain != 0) {
1229 if (type != NULL) {
1230 chain->setEffectSuspended_l(type, suspend);
1231 } else {
1232 chain->setEffectSuspendedAll_l(suspend);
1233 }
1234 }
1235
1236 updateSuspendedSessions_l(type, suspend, sessionId);
1237}
1238
1239void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1240{
1241 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1242 if (index < 0) {
1243 return;
1244 }
1245
1246 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1247 mSuspendedSessions.editValueAt(index);
1248
1249 for (size_t i = 0; i < sessionEffects.size(); i++) {
1250 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1251 for (int j = 0; j < desc->mRefCount; j++) {
1252 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1253 chain->setEffectSuspendedAll_l(true);
1254 } else {
Steve Block3856b092011-10-20 11:56:00 +01001255 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001256 desc->mType.timeLow);
1257 chain->setEffectSuspended_l(&desc->mType, true);
1258 }
1259 }
1260 }
1261}
1262
Eric Laurent59255e42011-07-27 19:49:51 -07001263void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1264 bool suspend,
1265 int sessionId)
1266{
1267 int index = mSuspendedSessions.indexOfKey(sessionId);
1268
1269 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1270
1271 if (suspend) {
1272 if (index >= 0) {
1273 sessionEffects = mSuspendedSessions.editValueAt(index);
1274 } else {
1275 mSuspendedSessions.add(sessionId, sessionEffects);
1276 }
1277 } else {
1278 if (index < 0) {
1279 return;
1280 }
1281 sessionEffects = mSuspendedSessions.editValueAt(index);
1282 }
1283
1284
1285 int key = EffectChain::kKeyForSuspendAll;
1286 if (type != NULL) {
1287 key = type->timeLow;
1288 }
1289 index = sessionEffects.indexOfKey(key);
1290
1291 sp <SuspendedSessionDesc> desc;
1292 if (suspend) {
1293 if (index >= 0) {
1294 desc = sessionEffects.valueAt(index);
1295 } else {
1296 desc = new SuspendedSessionDesc();
1297 if (type != NULL) {
1298 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1299 }
1300 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001301 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001302 }
1303 desc->mRefCount++;
1304 } else {
1305 if (index < 0) {
1306 return;
1307 }
1308 desc = sessionEffects.valueAt(index);
1309 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001310 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001311 sessionEffects.removeItemsAt(index);
1312 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001313 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001314 sessionId);
1315 mSuspendedSessions.removeItem(sessionId);
1316 }
1317 }
1318 }
1319 if (!sessionEffects.isEmpty()) {
1320 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1321 }
1322}
1323
1324void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1325 bool enabled,
1326 int sessionId)
1327{
1328 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001329 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1330}
Eric Laurent59255e42011-07-27 19:49:51 -07001331
Eric Laurenta85a74a2011-10-19 11:44:54 -07001332void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1333 bool enabled,
1334 int sessionId)
1335{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001336 if (mType != RECORD) {
1337 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1338 // another session. This gives the priority to well behaved effect control panels
1339 // and applications not using global effects.
1340 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1341 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1342 }
1343 }
Eric Laurent59255e42011-07-27 19:49:51 -07001344
1345 sp<EffectChain> chain = getEffectChain_l(sessionId);
1346 if (chain != 0) {
1347 chain->checkSuspendOnEffectEnabled(effect, enabled);
1348 }
1349}
1350
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351// ----------------------------------------------------------------------------
1352
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001353AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1354 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001355 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001356 uint32_t device,
1357 type_t type)
1358 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001359 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1360 // Assumes constructor is called by AudioFlinger with it's mLock held,
1361 // but it would be safer to explicitly pass initial masterMute as parameter
1362 mMasterMute(audioFlinger->masterMute_l()),
1363 // mStreamTypes[] initialized in constructor body
1364 mOutput(output),
1365 // Assumes constructor is called by AudioFlinger with it's mLock held,
1366 // but it would be safer to explicitly pass initial masterVolume as parameter
1367 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001368 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001370 snprintf(mName, kNameLength, "AudioOut_%d", id);
1371
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372 readOutputParameters();
1373
Glenn Kasten263709e2012-01-06 08:40:01 -08001374 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001375 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1376 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1377 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1379 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001380 // initialized by stream_type_t default constructor
1381 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382 }
1383}
1384
1385AudioFlinger::PlaybackThread::~PlaybackThread()
1386{
1387 delete [] mMixBuffer;
1388}
1389
1390status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1391{
1392 dumpInternals(fd, args);
1393 dumpTracks(fd, args);
1394 dumpEffectChains(fd, args);
1395 return NO_ERROR;
1396}
1397
1398status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1399{
1400 const size_t SIZE = 256;
1401 char buffer[SIZE];
1402 String8 result;
1403
1404 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1405 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001406 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 -07001407 for (size_t i = 0; i < mTracks.size(); ++i) {
1408 sp<Track> track = mTracks[i];
1409 if (track != 0) {
1410 track->dump(buffer, SIZE);
1411 result.append(buffer);
1412 }
1413 }
1414
1415 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1416 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001417 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 -07001418 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001419 sp<Track> track = mActiveTracks[i].promote();
1420 if (track != 0) {
1421 track->dump(buffer, SIZE);
1422 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 }
1424 }
1425 write(fd, result.string(), result.size());
1426 return NO_ERROR;
1427}
1428
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1430{
1431 const size_t SIZE = 256;
1432 char buffer[SIZE];
1433 String8 result;
1434
1435 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1436 result.append(buffer);
1437 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1438 result.append(buffer);
1439 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1440 result.append(buffer);
1441 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1442 result.append(buffer);
1443 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1444 result.append(buffer);
1445 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1448 result.append(buffer);
1449 write(fd, result.string(), result.size());
1450
1451 dumpBase(fd, args);
1452
1453 return NO_ERROR;
1454}
1455
1456// Thread virtuals
1457status_t AudioFlinger::PlaybackThread::readyToRun()
1458{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001459 status_t status = initCheck();
1460 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001461 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001462 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001463 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001465 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001466}
1467
1468void AudioFlinger::PlaybackThread::onFirstRef()
1469{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001470 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
1473// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1474sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1475 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001476 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001478 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001479 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480 int frameCount,
1481 const sp<IMemory>& sharedBuffer,
1482 int sessionId,
1483 status_t *status)
1484{
1485 sp<Track> track;
1486 status_t lStatus;
1487
1488 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001489 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1490 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001491 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001492 "for output %p with format %d",
1493 sampleRate, format, channelMask, mOutput, mFormat);
1494 lStatus = BAD_VALUE;
1495 goto Exit;
1496 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 }
1498 } else {
1499 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1500 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001501 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 lStatus = BAD_VALUE;
1503 goto Exit;
1504 }
1505 }
1506
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001507 lStatus = initCheck();
1508 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001509 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 goto Exit;
1511 }
1512
1513 { // scope for mLock
1514 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001515
1516 // all tracks in same audio session must share the same routing strategy otherwise
1517 // conflicts will happen when tracks are moved from one output to another by audio policy
1518 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001519 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001520 for (size_t i = 0; i < mTracks.size(); ++i) {
1521 sp<Track> t = mTracks[i];
1522 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001523 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001524 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001525 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001526 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001527 lStatus = BAD_VALUE;
1528 goto Exit;
1529 }
1530 }
1531 }
1532
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001534 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 if (track->getCblk() == NULL || track->name() < 0) {
1536 lStatus = NO_MEMORY;
1537 goto Exit;
1538 }
1539 mTracks.add(track);
1540
1541 sp<EffectChain> chain = getEffectChain_l(sessionId);
1542 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001543 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001545 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001546 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001548
1549 // invalidate track immediately if the stream type was moved to another thread since
1550 // createTrack() was called by the client process.
1551 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001552 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001553 this, streamType);
1554 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 }
1557 lStatus = NO_ERROR;
1558
1559Exit:
1560 if(status) {
1561 *status = lStatus;
1562 }
1563 return track;
1564}
1565
1566uint32_t AudioFlinger::PlaybackThread::latency() const
1567{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001568 Mutex::Autolock _l(mLock);
1569 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001570 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001571 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 return 0;
1573 }
1574}
1575
1576status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1577{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 mMasterVolume = value;
1579 return NO_ERROR;
1580}
1581
1582status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1583{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 mMasterMute = muted;
1585 return NO_ERROR;
1586}
1587
Glenn Kastenfff6d712012-01-12 16:38:12 -08001588status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 mStreamTypes[stream].volume = value;
1591 return NO_ERROR;
1592}
1593
Glenn Kastenfff6d712012-01-12 16:38:12 -08001594status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 mStreamTypes[stream].mute = muted;
1597 return NO_ERROR;
1598}
1599
Glenn Kastenfff6d712012-01-12 16:38:12 -08001600float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601{
1602 return mStreamTypes[stream].volume;
1603}
1604
Glenn Kastenfff6d712012-01-12 16:38:12 -08001605bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606{
1607 return mStreamTypes[stream].mute;
1608}
1609
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610// addTrack_l() must be called with ThreadBase::mLock held
1611status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1612{
1613 status_t status = ALREADY_EXISTS;
1614
1615 // set retry count for buffer fill
1616 track->mRetryCount = kMaxTrackStartupRetries;
1617 if (mActiveTracks.indexOf(track) < 0) {
1618 // the track is newly added, make sure it fills up all its
1619 // buffers before playing. This is to ensure the client will
1620 // effectively get the latency it requested.
1621 track->mFillingUpStatus = Track::FS_FILLING;
1622 track->mResetDone = false;
1623 mActiveTracks.add(track);
1624 if (track->mainBuffer() != mMixBuffer) {
1625 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1626 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001627 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001628 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629 }
1630 }
1631
1632 status = NO_ERROR;
1633 }
1634
Steve Block3856b092011-10-20 11:56:00 +01001635 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001636 mWaitWorkCV.broadcast();
1637
1638 return status;
1639}
1640
1641// destroyTrack_l() must be called with ThreadBase::mLock held
1642void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1643{
1644 track->mState = TrackBase::TERMINATED;
1645 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001646 removeTrack_l(track);
1647 }
1648}
1649
1650void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1651{
1652 mTracks.remove(track);
1653 deleteTrackName_l(track->name());
1654 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1655 if (chain != 0) {
1656 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 }
1658}
1659
1660String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1661{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001662 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001663 char *s;
1664
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001665 Mutex::Autolock _l(mLock);
1666 if (initCheck() != NO_ERROR) {
1667 return out_s8;
1668 }
1669
Dima Zavin799a70e2011-04-18 16:57:27 -07001670 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001671 out_s8 = String8(s);
1672 free(s);
1673 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674}
1675
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001676// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001677void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1678 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001679 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001680
Steve Block3856b092011-10-20 11:56:00 +01001681 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682
1683 switch (event) {
1684 case AudioSystem::OUTPUT_OPENED:
1685 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001686 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687 desc.samplingRate = mSampleRate;
1688 desc.format = mFormat;
1689 desc.frameCount = mFrameCount;
1690 desc.latency = latency();
1691 param2 = &desc;
1692 break;
1693
1694 case AudioSystem::STREAM_CONFIG_CHANGED:
1695 param2 = &param;
1696 case AudioSystem::OUTPUT_CLOSED:
1697 default:
1698 break;
1699 }
1700 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1701}
1702
1703void AudioFlinger::PlaybackThread::readOutputParameters()
1704{
Dima Zavin799a70e2011-04-18 16:57:27 -07001705 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001706 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1707 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001708 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001709 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001710 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711
1712 // FIXME - Current mixer implementation only supports stereo output: Always
1713 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001714 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 mMixBuffer = new int16_t[mFrameCount * 2];
1716 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1717
Eric Laurentde070132010-07-13 04:45:46 -07001718 // force reconfiguration of effect chains and engines to take new buffer size and audio
1719 // parameters into account
1720 // Note that mLock is not held when readOutputParameters() is called from the constructor
1721 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1722 // matter.
1723 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1724 Vector< sp<EffectChain> > effectChains = mEffectChains;
1725 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001726 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001727 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001728}
1729
1730status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1731{
Glenn Kastena0d68332012-01-27 16:47:15 -08001732 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733 return BAD_VALUE;
1734 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001735 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001736 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737 return INVALID_OPERATION;
1738 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001739 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740
Dima Zavin799a70e2011-04-18 16:57:27 -07001741 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742}
1743
Eric Laurent39e94f82010-07-28 01:32:47 -07001744uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745{
1746 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001747 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001749 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 }
1751
1752 for (size_t i = 0; i < mTracks.size(); ++i) {
1753 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001754 if (sessionId == track->sessionId() &&
1755 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001756 result |= TRACK_SESSION;
1757 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 }
1759 }
1760
Eric Laurent39e94f82010-07-28 01:32:47 -07001761 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762}
1763
Eric Laurentde070132010-07-13 04:45:46 -07001764uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1765{
Dima Zavinfce7a472011-04-19 22:30:36 -07001766 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001767 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001768 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1769 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001770 }
1771 for (size_t i = 0; i < mTracks.size(); i++) {
1772 sp<Track> track = mTracks[i];
1773 if (sessionId == track->sessionId() &&
1774 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001775 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001776 }
1777 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001778 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001779}
1780
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781
Glenn Kastenaed850d2012-01-26 09:46:34 -08001782AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001783{
1784 Mutex::Autolock _l(mLock);
1785 return mOutput;
1786}
1787
1788AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1789{
1790 Mutex::Autolock _l(mLock);
1791 AudioStreamOut *output = mOutput;
1792 mOutput = NULL;
1793 return output;
1794}
1795
1796// this method must always be called either with ThreadBase mLock held or inside the thread loop
1797audio_stream_t* AudioFlinger::PlaybackThread::stream()
1798{
1799 if (mOutput == NULL) {
1800 return NULL;
1801 }
1802 return &mOutput->stream->common;
1803}
1804
Eric Laurent162b40b2011-12-05 09:47:19 -08001805uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1806{
1807 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1808 // decoding and transfer time. So sleeping for half of the latency would likely cause
1809 // underruns
1810 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1811 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1812 } else {
1813 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1814 }
1815}
1816
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817// ----------------------------------------------------------------------------
1818
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001819AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001820 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001821 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001822 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1823 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001824{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 // FIXME - Current mixer implementation only supports stereo output
1826 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001827 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828 }
1829}
1830
1831AudioFlinger::MixerThread::~MixerThread()
1832{
1833 delete mAudioMixer;
1834}
1835
1836bool AudioFlinger::MixerThread::threadLoop()
1837{
1838 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001839 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840 nsecs_t standbyTime = systemTime();
1841 size_t mixBufferSize = mFrameCount * mFrameSize;
1842 // FIXME: Relaxed timing because of a certain device that can't meet latency
1843 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001844 // increase threshold again due to low power audio mode. The way this warning threshold is
1845 // calculated and its usefulness should be reconsidered anyway.
1846 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847 nsecs_t lastWarning = 0;
1848 bool longStandbyExit = false;
1849 uint32_t activeSleepTime = activeSleepTimeUs();
1850 uint32_t idleSleepTime = idleSleepTimeUs();
1851 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001852 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001854#ifdef DEBUG_CPU_USAGE
1855 ThreadCpuUsage cpu;
1856 const CentralTendencyStatistics& stats = cpu.statistics();
1857#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858
Eric Laurentfeb0db62011-07-22 09:04:31 -07001859 acquireWakeLock();
1860
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 while (!exitPending())
1862 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001863#ifdef DEBUG_CPU_USAGE
1864 cpu.sampleAndEnable();
1865 unsigned n = stats.n();
1866 // cpu.elapsed() is expensive, so don't call it every loop
1867 if ((n & 127) == 1) {
1868 long long elapsed = cpu.elapsed();
1869 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1870 double perLoop = elapsed / (double) n;
1871 double perLoop100 = perLoop * 0.01;
1872 double mean = stats.mean();
1873 double stddev = stats.stddev();
1874 double minimum = stats.minimum();
1875 double maximum = stats.maximum();
1876 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001877 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 -07001878 elapsed * .000000001, n, perLoop * .000001,
1879 mean * .001,
1880 stddev * .001,
1881 minimum * .001,
1882 maximum * .001,
1883 mean / perLoop100,
1884 stddev / perLoop100,
1885 minimum / perLoop100,
1886 maximum / perLoop100);
1887 }
1888 }
1889#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890 processConfigEvents();
1891
1892 mixerStatus = MIXER_IDLE;
1893 { // scope for mLock
1894
1895 Mutex::Autolock _l(mLock);
1896
1897 if (checkForNewParameters_l()) {
1898 mixBufferSize = mFrameCount * mFrameSize;
1899 // FIXME: Relaxed timing because of a certain device that can't meet latency
1900 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001901 // increase threshold again due to low power audio mode. The way this warning
1902 // threshold is calculated and its usefulness should be reconsidered anyway.
1903 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 activeSleepTime = activeSleepTimeUs();
1905 idleSleepTime = idleSleepTimeUs();
1906 }
1907
1908 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1909
1910 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001911 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1912 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08001914 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001915 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001916 mStandby = true;
1917 mBytesWritten = 0;
1918 }
1919
1920 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1921 // we're about to wait, flush the binder command buffer
1922 IPCThreadState::self()->flushCommands();
1923
1924 if (exitPending()) break;
1925
Eric Laurentfeb0db62011-07-22 09:04:31 -07001926 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08001928 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001929 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08001930 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001931 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932
Eric Laurent27741442012-01-17 19:20:12 -08001933 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001934 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 char value[PROPERTY_VALUE_MAX];
1936 property_get("ro.audio.silent", value, "0");
1937 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001938 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 setMasterMute(true);
1940 }
1941 }
1942
1943 standbyTime = systemTime() + kStandbyTimeInNsecs;
1944 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001945 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 continue;
1947 }
1948 }
1949
1950 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1951
1952 // prevent any changes in effect chain list and in each effect chain
1953 // during mixing and effect process as the audio buffers could be deleted
1954 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001955 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001956 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001957
Glenn Kastenf6b16782011-12-15 09:51:17 -08001958 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 // mix buffers...
1960 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001961 // increase sleep time progressively when application underrun condition clears.
1962 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1963 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1964 // such that we would underrun the audio HAL.
1965 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001966 sleepTimeShift--;
1967 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001968 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001969 standbyTime = systemTime() + kStandbyTimeInNsecs;
1970 //TODO: delay standby when effects have a tail
1971 } else {
1972 // If no tracks are ready, sleep once for the duration of an output
1973 // buffer size, then write 0s to the output
1974 if (sleepTime == 0) {
1975 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001976 sleepTime = activeSleepTime >> sleepTimeShift;
1977 if (sleepTime < kMinThreadSleepTimeUs) {
1978 sleepTime = kMinThreadSleepTimeUs;
1979 }
1980 // reduce sleep time in case of consecutive application underruns to avoid
1981 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1982 // duration we would end up writing less data than needed by the audio HAL if
1983 // the condition persists.
1984 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1985 sleepTimeShift++;
1986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 } else {
1988 sleepTime = idleSleepTime;
1989 }
1990 } else if (mBytesWritten != 0 ||
1991 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1992 memset (mMixBuffer, 0, mixBufferSize);
1993 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01001994 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995 }
1996 // TODO add standby time extension fct of effect tail
1997 }
1998
1999 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002000 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 }
2002 // sleepTime == 0 means we must write to audio hardware
2003 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002004 for (size_t i = 0; i < effectChains.size(); i ++) {
2005 effectChains[i]->process_l();
2006 }
2007 // enable changes in effect chain
2008 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 mLastWriteTime = systemTime();
2010 mInWrite = true;
2011 mBytesWritten += mixBufferSize;
2012
Dima Zavin799a70e2011-04-18 16:57:27 -07002013 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2015 mNumWrites++;
2016 mInWrite = false;
2017 nsecs_t now = systemTime();
2018 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002019 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002021 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002022 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 ns2ms(delta), mNumDelayedWrites, this);
2024 lastWarning = now;
2025 }
2026 if (mStandby) {
2027 longStandbyExit = true;
2028 }
2029 }
2030 mStandby = false;
2031 } else {
2032 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002033 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 usleep(sleepTime);
2035 }
2036
2037 // finally let go of all our tracks, without the lock held
2038 // since we can't guarantee the destructors won't acquire that
2039 // same lock.
2040 tracksToRemove.clear();
2041
2042 // Effect chains will be actually deleted here if they were removed from
2043 // mEffectChains list during mixing or effects processing
2044 effectChains.clear();
2045 }
2046
2047 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002048 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 }
2050
Eric Laurentfeb0db62011-07-22 09:04:31 -07002051 releaseWakeLock();
2052
Steve Block3856b092011-10-20 11:56:00 +01002053 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 return false;
2055}
2056
2057// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002058AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2059 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060{
2061
Glenn Kasten29c23c32012-01-26 13:37:52 -08002062 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 // find out which tracks need to be processed
2064 size_t count = activeTracks.size();
2065 size_t mixedTracks = 0;
2066 size_t tracksWithEffect = 0;
2067
2068 float masterVolume = mMasterVolume;
2069 bool masterMute = mMasterMute;
2070
Eric Laurent571d49c2010-08-11 05:20:11 -07002071 if (masterMute) {
2072 masterVolume = 0;
2073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002075 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002076 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002077 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002078 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002079 masterVolume = (float)((v + (1 << 23)) >> 24);
2080 chain.clear();
2081 }
2082
2083 for (size_t i=0 ; i<count ; i++) {
2084 sp<Track> t = activeTracks[i].promote();
2085 if (t == 0) continue;
2086
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002087 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 Track* const track = t.get();
2089 audio_track_cblk_t* cblk = track->cblk();
2090
2091 // The first time a track is added we wait
2092 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002093 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002094 // make sure that we have enough frames to mix one full buffer.
2095 // enforce this condition only once to enable draining the buffer in case the client
2096 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002097 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002098 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002099 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002100 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002101 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002102 if (t->sampleRate() == (int)mSampleRate) {
2103 minFrames = mFrameCount;
2104 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002105 // +1 for rounding and +1 for additional sample needed for interpolation
2106 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2107 // add frames already consumed but not yet released by the resampler
2108 // because cblk->framesReady() will include these frames
2109 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2110 // the minimum track buffer size is normally twice the number of frames necessary
2111 // to fill one buffer and the resampler should not leave more than one buffer worth
2112 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002113 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002114 }
2115 }
2116 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 !track->isPaused() && !track->isTerminated())
2118 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002119 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120
2121 mixedTracks++;
2122
2123 // track->mainBuffer() != mMixBuffer means there is an effect chain
2124 // connected to the track
2125 chain.clear();
2126 if (track->mainBuffer() != mMixBuffer) {
2127 chain = getEffectChain_l(track->sessionId());
2128 // Delegate volume control to effect in track effect chain if needed
2129 if (chain != 0) {
2130 tracksWithEffect++;
2131 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002132 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002133 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 }
2135 }
2136
2137
2138 int param = AudioMixer::VOLUME;
2139 if (track->mFillingUpStatus == Track::FS_FILLED) {
2140 // no ramp for the first volume setting
2141 track->mFillingUpStatus = Track::FS_ACTIVE;
2142 if (track->mState == TrackBase::RESUMING) {
2143 track->mState = TrackBase::ACTIVE;
2144 param = AudioMixer::RAMP_VOLUME;
2145 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002146 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147 } else if (cblk->server != 0) {
2148 // If the track is stopped before the first frame was mixed,
2149 // do not apply ramp
2150 param = AudioMixer::RAMP_VOLUME;
2151 }
2152
2153 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002154 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002155 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002156 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002157 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002158 if (track->isPausing()) {
2159 track->setPaused();
2160 }
2161 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002162
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002164 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002166 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002167 vl = vlr & 0xFFFF;
2168 vr = vlr >> 16;
2169 // track volumes come from shared memory, so can't be trusted and must be clamped
2170 if (vl > MAX_GAIN_INT) {
2171 ALOGV("Track left volume out of range: %04X", vl);
2172 vl = MAX_GAIN_INT;
2173 }
2174 if (vr > MAX_GAIN_INT) {
2175 ALOGV("Track right volume out of range: %04X", vr);
2176 vr = MAX_GAIN_INT;
2177 }
2178 // now apply the master volume and stream type volume
2179 vl = (uint32_t)(v * vl) << 12;
2180 vr = (uint32_t)(v * vr) << 12;
2181 // assuming master volume and stream type volume each go up to 1.0,
2182 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183
Glenn Kasten05632a52012-01-03 14:22:33 -08002184 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2185 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002186 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002187 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002188 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002189 }
2190 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002192 // Delegate volume control to effect in track effect chain if needed
2193 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2194 // Do not ramp volume if volume is controlled by effect
2195 param = AudioMixer::VOLUME;
2196 track->mHasVolumeController = true;
2197 } else {
2198 // force no volume ramp when volume controller was just disabled or removed
2199 // from effect chain to avoid volume spike
2200 if (track->mHasVolumeController) {
2201 param = AudioMixer::VOLUME;
2202 }
2203 track->mHasVolumeController = false;
2204 }
2205
2206 // Convert volumes from 8.24 to 4.12 format
2207 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002208 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002209 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2210 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2211 left = int16_t(v_clamped);
2212 v_clamped = (vr + (1 << 11)) >> 12;
2213 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2214 right = int16_t(v_clamped);
2215
2216 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2217 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002220 mAudioMixer->setBufferProvider(name, track);
2221 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002222
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002223 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2224 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2225 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002227 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 AudioMixer::TRACK,
2229 AudioMixer::FORMAT, (void *)track->format());
2230 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002231 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002233 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002235 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236 AudioMixer::RESAMPLE,
2237 AudioMixer::SAMPLE_RATE,
2238 (void *)(cblk->sampleRate));
2239 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002240 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 AudioMixer::TRACK,
2242 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2243 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002244 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 AudioMixer::TRACK,
2246 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2247
2248 // reset retry count
2249 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002250 // If one track is ready, set the mixer ready if:
2251 // - the mixer was not ready during previous round OR
2252 // - no other track is not ready
2253 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2254 mixerStatus != MIXER_TRACKS_ENABLED) {
2255 mixerStatus = MIXER_TRACKS_READY;
2256 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002258 //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 -07002259 if (track->isStopped()) {
2260 track->reset();
2261 }
2262 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2263 // We have consumed all the buffers of this track.
2264 // Remove it from the list of active tracks.
2265 tracksToRemove->add(track);
2266 } else {
2267 // No buffers for this track. Give it a few chances to
2268 // fill a buffer, then remove it from active list.
2269 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002270 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002272 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002273 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002274 // If one track is not ready, mark the mixer also not ready if:
2275 // - the mixer was ready during previous round OR
2276 // - no other track is ready
2277 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2278 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 mixerStatus = MIXER_TRACKS_ENABLED;
2280 }
2281 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002282 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002283 }
2284 }
2285
2286 // remove all the tracks that need to be...
2287 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002288 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002289 for (size_t i=0 ; i<count ; i++) {
2290 const sp<Track>& track = tracksToRemove->itemAt(i);
2291 mActiveTracks.remove(track);
2292 if (track->mainBuffer() != mMixBuffer) {
2293 chain = getEffectChain_l(track->sessionId());
2294 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002295 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002296 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 }
2298 }
2299 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002300 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 }
2302 }
2303 }
2304
2305 // mix buffer must be cleared if all tracks are connected to an
2306 // effect chain as in this case the mixer will not write to
2307 // mix buffer and track effects will accumulate into it
2308 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2309 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2310 }
2311
Eric Laurent27741442012-01-17 19:20:12 -08002312 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002313 return mixerStatus;
2314}
2315
Glenn Kastenfff6d712012-01-12 16:38:12 -08002316void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317{
Steve Block3856b092011-10-20 11:56:00 +01002318 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002319 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002321
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 size_t size = mTracks.size();
2323 for (size_t i = 0; i < size; i++) {
2324 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002325 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002326 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 }
2329 }
2330}
2331
Glenn Kastenfff6d712012-01-12 16:38:12 -08002332void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002333{
Steve Block3856b092011-10-20 11:56:00 +01002334 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002335 this, streamType, valid);
2336 Mutex::Autolock _l(mLock);
2337
2338 mStreamTypes[streamType].valid = valid;
2339}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340
2341// getTrackName_l() must be called with ThreadBase::mLock held
2342int AudioFlinger::MixerThread::getTrackName_l()
2343{
2344 return mAudioMixer->getTrackName();
2345}
2346
2347// deleteTrackName_l() must be called with ThreadBase::mLock held
2348void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2349{
Steve Block3856b092011-10-20 11:56:00 +01002350 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 mAudioMixer->deleteTrackName(name);
2352}
2353
2354// checkForNewParameters_l() must be called with ThreadBase::mLock held
2355bool AudioFlinger::MixerThread::checkForNewParameters_l()
2356{
2357 bool reconfig = false;
2358
2359 while (!mNewParameters.isEmpty()) {
2360 status_t status = NO_ERROR;
2361 String8 keyValuePair = mNewParameters[0];
2362 AudioParameter param = AudioParameter(keyValuePair);
2363 int value;
2364
2365 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2366 reconfig = true;
2367 }
2368 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002369 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 status = BAD_VALUE;
2371 } else {
2372 reconfig = true;
2373 }
2374 }
2375 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002376 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 status = BAD_VALUE;
2378 } else {
2379 reconfig = true;
2380 }
2381 }
2382 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2383 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002384 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 // if frame count is changed after track creation
2386 if (!mTracks.isEmpty()) {
2387 status = INVALID_OPERATION;
2388 } else {
2389 reconfig = true;
2390 }
2391 }
2392 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002393 // when changing the audio output device, call addBatteryData to notify
2394 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002395 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002396 uint32_t params = 0;
2397 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002398 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002399 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2400 }
2401
2402 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002403 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002404 // check if any other device (except speaker) is on
2405 if (value & deviceWithoutSpeaker ) {
2406 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2407 }
2408
2409 if (params != 0) {
2410 addBatteryData(params);
2411 }
2412 }
2413
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 // forward device change to effects that have requested to be
2415 // aware of attached audio device.
2416 mDevice = (uint32_t)value;
2417 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002418 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 }
2420 }
2421
2422 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002423 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002424 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002426 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 mStandby = true;
2428 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002429 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002430 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 }
2432 if (status == NO_ERROR && reconfig) {
2433 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002434 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2435 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 readOutputParameters();
2437 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2438 for (size_t i = 0; i < mTracks.size() ; i++) {
2439 int name = getTrackName_l();
2440 if (name < 0) break;
2441 mTracks[i]->mName = name;
2442 // limit track sample rate to 2 x new output sample rate
2443 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2444 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2445 }
2446 }
2447 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2448 }
2449 }
2450
2451 mNewParameters.removeAt(0);
2452
2453 mParamStatus = status;
2454 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002455 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2456 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002457 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002458 }
2459 return reconfig;
2460}
2461
2462status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2463{
2464 const size_t SIZE = 256;
2465 char buffer[SIZE];
2466 String8 result;
2467
2468 PlaybackThread::dumpInternals(fd, args);
2469
2470 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2471 result.append(buffer);
2472 write(fd, result.string(), result.size());
2473 return NO_ERROR;
2474}
2475
Mathias Agopian65ab4712010-07-14 17:59:35 -07002476uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2477{
Eric Laurent60e18242010-07-29 06:50:24 -07002478 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479}
2480
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002481uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2482{
2483 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2484}
2485
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002487AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2488 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002489 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002490 // mLeftVolFloat, mRightVolFloat
2491 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493}
2494
2495AudioFlinger::DirectOutputThread::~DirectOutputThread()
2496{
2497}
2498
Mathias Agopian65ab4712010-07-14 17:59:35 -07002499void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2500{
2501 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002502 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503 return;
2504 }
2505
2506 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002507 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508 size_t count = mFrameCount * mChannelCount;
2509 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2510 int16_t *dst = mMixBuffer + count-1;
2511 while(count--) {
2512 *dst-- = (int16_t)(*src--^0x80) << 8;
2513 }
2514 }
2515
2516 size_t frameCount = mFrameCount;
2517 int16_t *out = mMixBuffer;
2518 if (ramp) {
2519 if (mChannelCount == 1) {
2520 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2521 int32_t vlInc = d / (int32_t)frameCount;
2522 int32_t vl = ((int32_t)mLeftVolShort << 16);
2523 do {
2524 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2525 out++;
2526 vl += vlInc;
2527 } while (--frameCount);
2528
2529 } else {
2530 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2531 int32_t vlInc = d / (int32_t)frameCount;
2532 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2533 int32_t vrInc = d / (int32_t)frameCount;
2534 int32_t vl = ((int32_t)mLeftVolShort << 16);
2535 int32_t vr = ((int32_t)mRightVolShort << 16);
2536 do {
2537 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2538 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2539 out += 2;
2540 vl += vlInc;
2541 vr += vrInc;
2542 } while (--frameCount);
2543 }
2544 } else {
2545 if (mChannelCount == 1) {
2546 do {
2547 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2548 out++;
2549 } while (--frameCount);
2550 } else {
2551 do {
2552 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2553 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2554 out += 2;
2555 } while (--frameCount);
2556 }
2557 }
2558
2559 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002560 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 size_t count = mFrameCount * mChannelCount;
2562 int16_t *src = mMixBuffer;
2563 uint8_t *dst = (uint8_t *)mMixBuffer;
2564 while(count--) {
2565 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2566 }
2567 }
2568
2569 mLeftVolShort = leftVol;
2570 mRightVolShort = rightVol;
2571}
2572
2573bool AudioFlinger::DirectOutputThread::threadLoop()
2574{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002575 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002576 sp<Track> trackToRemove;
2577 sp<Track> activeTrack;
2578 nsecs_t standbyTime = systemTime();
2579 int8_t *curBuf;
2580 size_t mixBufferSize = mFrameCount*mFrameSize;
2581 uint32_t activeSleepTime = activeSleepTimeUs();
2582 uint32_t idleSleepTime = idleSleepTimeUs();
2583 uint32_t sleepTime = idleSleepTime;
2584 // use shorter standby delay as on normal output to release
2585 // hardware resources as soon as possible
2586 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2587
Eric Laurentfeb0db62011-07-22 09:04:31 -07002588 acquireWakeLock();
2589
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 while (!exitPending())
2591 {
2592 bool rampVolume;
2593 uint16_t leftVol;
2594 uint16_t rightVol;
2595 Vector< sp<EffectChain> > effectChains;
2596
2597 processConfigEvents();
2598
2599 mixerStatus = MIXER_IDLE;
2600
2601 { // scope for the mLock
2602
2603 Mutex::Autolock _l(mLock);
2604
2605 if (checkForNewParameters_l()) {
2606 mixBufferSize = mFrameCount*mFrameSize;
2607 activeSleepTime = activeSleepTimeUs();
2608 idleSleepTime = idleSleepTimeUs();
2609 standbyDelay = microseconds(activeSleepTime*2);
2610 }
2611
2612 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002613 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2614 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 // wait until we have something to do...
2616 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002617 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002618 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619 mStandby = true;
2620 mBytesWritten = 0;
2621 }
2622
2623 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2624 // we're about to wait, flush the binder command buffer
2625 IPCThreadState::self()->flushCommands();
2626
2627 if (exitPending()) break;
2628
Eric Laurentfeb0db62011-07-22 09:04:31 -07002629 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002630 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002632 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002633 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002634
Glenn Kastenf1d45922012-01-13 15:54:24 -08002635 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636 char value[PROPERTY_VALUE_MAX];
2637 property_get("ro.audio.silent", value, "0");
2638 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002639 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002640 setMasterMute(true);
2641 }
2642 }
2643
2644 standbyTime = systemTime() + standbyDelay;
2645 sleepTime = idleSleepTime;
2646 continue;
2647 }
2648 }
2649
2650 effectChains = mEffectChains;
2651
2652 // find out which tracks need to be processed
2653 if (mActiveTracks.size() != 0) {
2654 sp<Track> t = mActiveTracks[0].promote();
2655 if (t == 0) continue;
2656
2657 Track* const track = t.get();
2658 audio_track_cblk_t* cblk = track->cblk();
2659
2660 // The first time a track is added we wait
2661 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002662 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 !track->isPaused() && !track->isTerminated())
2664 {
Steve Block3856b092011-10-20 11:56:00 +01002665 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002666
2667 if (track->mFillingUpStatus == Track::FS_FILLED) {
2668 track->mFillingUpStatus = Track::FS_ACTIVE;
2669 mLeftVolFloat = mRightVolFloat = 0;
2670 mLeftVolShort = mRightVolShort = 0;
2671 if (track->mState == TrackBase::RESUMING) {
2672 track->mState = TrackBase::ACTIVE;
2673 rampVolume = true;
2674 }
2675 } else if (cblk->server != 0) {
2676 // If the track is stopped before the first frame was mixed,
2677 // do not apply ramp
2678 rampVolume = true;
2679 }
2680 // compute volume for this track
2681 float left, right;
2682 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002683 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 left = right = 0;
2685 if (track->isPausing()) {
2686 track->setPaused();
2687 }
2688 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002689 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002691 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002692 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2694 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002695 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2697 right = v_clamped/MAX_GAIN;
2698 }
2699
2700 if (left != mLeftVolFloat || right != mRightVolFloat) {
2701 mLeftVolFloat = left;
2702 mRightVolFloat = right;
2703
2704 // If audio HAL implements volume control,
2705 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002706 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 left = 1.0f;
2708 right = 1.0f;
2709 }
2710
2711 // Convert volumes from float to 8.24
2712 uint32_t vl = (uint32_t)(left * (1 << 24));
2713 uint32_t vr = (uint32_t)(right * (1 << 24));
2714
2715 // Delegate volume control to effect in track effect chain if needed
2716 // only one effect chain can be present on DirectOutputThread, so if
2717 // there is one, the track is connected to it
2718 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002719 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002720 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 rampVolume = false;
2722 }
2723 }
2724
2725 // Convert volumes from 8.24 to 4.12 format
2726 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2727 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2728 leftVol = (uint16_t)v_clamped;
2729 v_clamped = (vr + (1 << 11)) >> 12;
2730 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2731 rightVol = (uint16_t)v_clamped;
2732 } else {
2733 leftVol = mLeftVolShort;
2734 rightVol = mRightVolShort;
2735 rampVolume = false;
2736 }
2737
2738 // reset retry count
2739 track->mRetryCount = kMaxTrackRetriesDirect;
2740 activeTrack = t;
2741 mixerStatus = MIXER_TRACKS_READY;
2742 } else {
Steve Block3856b092011-10-20 11:56:00 +01002743 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 if (track->isStopped()) {
2745 track->reset();
2746 }
2747 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2748 // We have consumed all the buffers of this track.
2749 // Remove it from the list of active tracks.
2750 trackToRemove = track;
2751 } else {
2752 // No buffers for this track. Give it a few chances to
2753 // fill a buffer, then remove it from active list.
2754 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002755 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756 trackToRemove = track;
2757 } else {
2758 mixerStatus = MIXER_TRACKS_ENABLED;
2759 }
2760 }
2761 }
2762 }
2763
2764 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002765 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 mActiveTracks.remove(trackToRemove);
2767 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002768 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002769 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002770 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 }
2772 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002773 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002774 }
2775 }
2776
Eric Laurentde070132010-07-13 04:45:46 -07002777 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 }
2779
Glenn Kastenf6b16782011-12-15 09:51:17 -08002780 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781 AudioBufferProvider::Buffer buffer;
2782 size_t frameCount = mFrameCount;
2783 curBuf = (int8_t *)mMixBuffer;
2784 // output audio to hardware
2785 while (frameCount) {
2786 buffer.frameCount = frameCount;
2787 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002788 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 memset(curBuf, 0, frameCount * mFrameSize);
2790 break;
2791 }
2792 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2793 frameCount -= buffer.frameCount;
2794 curBuf += buffer.frameCount * mFrameSize;
2795 activeTrack->releaseBuffer(&buffer);
2796 }
2797 sleepTime = 0;
2798 standbyTime = systemTime() + standbyDelay;
2799 } else {
2800 if (sleepTime == 0) {
2801 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2802 sleepTime = activeSleepTime;
2803 } else {
2804 sleepTime = idleSleepTime;
2805 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002806 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2808 sleepTime = 0;
2809 }
2810 }
2811
2812 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002813 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 }
2815 // sleepTime == 0 means we must write to audio hardware
2816 if (sleepTime == 0) {
2817 if (mixerStatus == MIXER_TRACKS_READY) {
2818 applyVolume(leftVol, rightVol, rampVolume);
2819 }
2820 for (size_t i = 0; i < effectChains.size(); i ++) {
2821 effectChains[i]->process_l();
2822 }
Eric Laurentde070132010-07-13 04:45:46 -07002823 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824
2825 mLastWriteTime = systemTime();
2826 mInWrite = true;
2827 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002828 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002829 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2830 mNumWrites++;
2831 mInWrite = false;
2832 mStandby = false;
2833 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002834 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002835 usleep(sleepTime);
2836 }
2837
2838 // finally let go of removed track, without the lock held
2839 // since we can't guarantee the destructors won't acquire that
2840 // same lock.
2841 trackToRemove.clear();
2842 activeTrack.clear();
2843
2844 // Effect chains will be actually deleted here if they were removed from
2845 // mEffectChains list during mixing or effects processing
2846 effectChains.clear();
2847 }
2848
2849 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002850 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 }
2852
Eric Laurentfeb0db62011-07-22 09:04:31 -07002853 releaseWakeLock();
2854
Steve Block3856b092011-10-20 11:56:00 +01002855 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 return false;
2857}
2858
2859// getTrackName_l() must be called with ThreadBase::mLock held
2860int AudioFlinger::DirectOutputThread::getTrackName_l()
2861{
2862 return 0;
2863}
2864
2865// deleteTrackName_l() must be called with ThreadBase::mLock held
2866void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2867{
2868}
2869
2870// checkForNewParameters_l() must be called with ThreadBase::mLock held
2871bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2872{
2873 bool reconfig = false;
2874
2875 while (!mNewParameters.isEmpty()) {
2876 status_t status = NO_ERROR;
2877 String8 keyValuePair = mNewParameters[0];
2878 AudioParameter param = AudioParameter(keyValuePair);
2879 int value;
2880
2881 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2882 // do not accept frame count changes if tracks are open as the track buffer
2883 // size depends on frame count and correct behavior would not be garantied
2884 // if frame count is changed after track creation
2885 if (!mTracks.isEmpty()) {
2886 status = INVALID_OPERATION;
2887 } else {
2888 reconfig = true;
2889 }
2890 }
2891 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002892 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002893 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002895 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002896 mStandby = true;
2897 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002898 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002899 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 }
2901 if (status == NO_ERROR && reconfig) {
2902 readOutputParameters();
2903 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2904 }
2905 }
2906
2907 mNewParameters.removeAt(0);
2908
2909 mParamStatus = status;
2910 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002911 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2912 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002913 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 }
2915 return reconfig;
2916}
2917
2918uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2919{
2920 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002921 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002922 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 } else {
2924 time = 10000;
2925 }
2926 return time;
2927}
2928
2929uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2930{
2931 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002932 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002933 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002934 } else {
2935 time = 10000;
2936 }
2937 return time;
2938}
2939
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002940uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2941{
2942 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002943 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002944 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2945 } else {
2946 time = 10000;
2947 }
2948 return time;
2949}
2950
2951
Mathias Agopian65ab4712010-07-14 17:59:35 -07002952// ----------------------------------------------------------------------------
2953
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002954AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002955 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002956 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2957 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 addOutputTrack(mainThread);
2960}
2961
2962AudioFlinger::DuplicatingThread::~DuplicatingThread()
2963{
2964 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2965 mOutputTracks[i]->destroy();
2966 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967}
2968
2969bool AudioFlinger::DuplicatingThread::threadLoop()
2970{
2971 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002972 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 nsecs_t standbyTime = systemTime();
2974 size_t mixBufferSize = mFrameCount*mFrameSize;
2975 SortedVector< sp<OutputTrack> > outputTracks;
2976 uint32_t writeFrames = 0;
2977 uint32_t activeSleepTime = activeSleepTimeUs();
2978 uint32_t idleSleepTime = idleSleepTimeUs();
2979 uint32_t sleepTime = idleSleepTime;
2980 Vector< sp<EffectChain> > effectChains;
2981
Eric Laurentfeb0db62011-07-22 09:04:31 -07002982 acquireWakeLock();
2983
Mathias Agopian65ab4712010-07-14 17:59:35 -07002984 while (!exitPending())
2985 {
2986 processConfigEvents();
2987
2988 mixerStatus = MIXER_IDLE;
2989 { // scope for the mLock
2990
2991 Mutex::Autolock _l(mLock);
2992
2993 if (checkForNewParameters_l()) {
2994 mixBufferSize = mFrameCount*mFrameSize;
2995 updateWaitTime();
2996 activeSleepTime = activeSleepTimeUs();
2997 idleSleepTime = idleSleepTimeUs();
2998 }
2999
3000 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3001
3002 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3003 outputTracks.add(mOutputTracks[i]);
3004 }
3005
3006 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003007 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3008 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 if (!mStandby) {
3010 for (size_t i = 0; i < outputTracks.size(); i++) {
3011 outputTracks[i]->stop();
3012 }
3013 mStandby = true;
3014 mBytesWritten = 0;
3015 }
3016
3017 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3018 // we're about to wait, flush the binder command buffer
3019 IPCThreadState::self()->flushCommands();
3020 outputTracks.clear();
3021
3022 if (exitPending()) break;
3023
Eric Laurentfeb0db62011-07-22 09:04:31 -07003024 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003025 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003027 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003028 acquireWakeLock_l();
3029
Eric Laurent27741442012-01-17 19:20:12 -08003030 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003031 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 char value[PROPERTY_VALUE_MAX];
3033 property_get("ro.audio.silent", value, "0");
3034 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003035 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 setMasterMute(true);
3037 }
3038 }
3039
3040 standbyTime = systemTime() + kStandbyTimeInNsecs;
3041 sleepTime = idleSleepTime;
3042 continue;
3043 }
3044 }
3045
3046 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3047
3048 // prevent any changes in effect chain list and in each effect chain
3049 // during mixing and effect process as the audio buffers could be deleted
3050 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003051 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 }
3053
Glenn Kastenf6b16782011-12-15 09:51:17 -08003054 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 // mix buffers...
3056 if (outputsReady(outputTracks)) {
3057 mAudioMixer->process();
3058 } else {
3059 memset(mMixBuffer, 0, mixBufferSize);
3060 }
3061 sleepTime = 0;
3062 writeFrames = mFrameCount;
3063 } else {
3064 if (sleepTime == 0) {
3065 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3066 sleepTime = activeSleepTime;
3067 } else {
3068 sleepTime = idleSleepTime;
3069 }
3070 } else if (mBytesWritten != 0) {
3071 // flush remaining overflow buffers in output tracks
3072 for (size_t i = 0; i < outputTracks.size(); i++) {
3073 if (outputTracks[i]->isActive()) {
3074 sleepTime = 0;
3075 writeFrames = 0;
3076 memset(mMixBuffer, 0, mixBufferSize);
3077 break;
3078 }
3079 }
3080 }
3081 }
3082
3083 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003084 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085 }
3086 // sleepTime == 0 means we must write to audio hardware
3087 if (sleepTime == 0) {
3088 for (size_t i = 0; i < effectChains.size(); i ++) {
3089 effectChains[i]->process_l();
3090 }
3091 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003092 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093
3094 standbyTime = systemTime() + kStandbyTimeInNsecs;
3095 for (size_t i = 0; i < outputTracks.size(); i++) {
3096 outputTracks[i]->write(mMixBuffer, writeFrames);
3097 }
3098 mStandby = false;
3099 mBytesWritten += mixBufferSize;
3100 } else {
3101 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003102 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 usleep(sleepTime);
3104 }
3105
3106 // finally let go of all our tracks, without the lock held
3107 // since we can't guarantee the destructors won't acquire that
3108 // same lock.
3109 tracksToRemove.clear();
3110 outputTracks.clear();
3111
3112 // Effect chains will be actually deleted here if they were removed from
3113 // mEffectChains list during mixing or effects processing
3114 effectChains.clear();
3115 }
3116
Eric Laurentfeb0db62011-07-22 09:04:31 -07003117 releaseWakeLock();
3118
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119 return false;
3120}
3121
3122void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3123{
3124 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3125 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3126 this,
3127 mSampleRate,
3128 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003129 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130 frameCount);
3131 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003132 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003134 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 updateWaitTime();
3136 }
3137}
3138
3139void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3140{
3141 Mutex::Autolock _l(mLock);
3142 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3143 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3144 mOutputTracks[i]->destroy();
3145 mOutputTracks.removeAt(i);
3146 updateWaitTime();
3147 return;
3148 }
3149 }
Steve Block3856b092011-10-20 11:56:00 +01003150 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151}
3152
3153void AudioFlinger::DuplicatingThread::updateWaitTime()
3154{
3155 mWaitTimeMs = UINT_MAX;
3156 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3157 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003158 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3160 if (waitTimeMs < mWaitTimeMs) {
3161 mWaitTimeMs = waitTimeMs;
3162 }
3163 }
3164 }
3165}
3166
3167
3168bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3169{
3170 for (size_t i = 0; i < outputTracks.size(); i++) {
3171 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3172 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003173 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174 return false;
3175 }
3176 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3177 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003178 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003179 return false;
3180 }
3181 }
3182 return true;
3183}
3184
3185uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3186{
3187 return (mWaitTimeMs * 1000) / 2;
3188}
3189
3190// ----------------------------------------------------------------------------
3191
3192// TrackBase constructor must be called with AudioFlinger::mLock held
3193AudioFlinger::ThreadBase::TrackBase::TrackBase(
3194 const wp<ThreadBase>& thread,
3195 const sp<Client>& client,
3196 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003197 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003198 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003199 int frameCount,
3200 uint32_t flags,
3201 const sp<IMemory>& sharedBuffer,
3202 int sessionId)
3203 : RefBase(),
3204 mThread(thread),
3205 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003206 mCblk(NULL),
3207 // mBuffer
3208 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 mFrameCount(0),
3210 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003211 mFormat(format),
3212 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3213 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003214 // mChannelCount
3215 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003216{
Steve Block3856b092011-10-20 11:56:00 +01003217 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003218
Steve Blockb8a80522011-12-20 16:23:08 +00003219 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003221 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3223 if (sharedBuffer == 0) {
3224 size += bufferSize;
3225 }
3226
3227 if (client != NULL) {
3228 mCblkMemory = client->heap()->allocate(size);
3229 if (mCblkMemory != 0) {
3230 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003231 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232 new(mCblk) audio_track_cblk_t();
3233 // clear all buffers
3234 mCblk->frameCount = frameCount;
3235 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003236 mChannelCount = channelCount;
3237 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 if (sharedBuffer == 0) {
3239 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3240 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3241 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003242 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 mCblk->flags = CBLK_UNDERRUN_ON;
3244 } else {
3245 mBuffer = sharedBuffer->pointer();
3246 }
3247 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3248 }
3249 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003250 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 client->heap()->dump("AudioTrack");
3252 return;
3253 }
3254 } else {
3255 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003256 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 new(mCblk) audio_track_cblk_t();
3258 // clear all buffers
3259 mCblk->frameCount = frameCount;
3260 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003261 mChannelCount = channelCount;
3262 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3264 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3265 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003266 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 mCblk->flags = CBLK_UNDERRUN_ON;
3268 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 }
3270}
3271
3272AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3273{
Glenn Kastena0d68332012-01-27 16:47:15 -08003274 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003275 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003277 } else {
3278 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003279 }
3280 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003281 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003282 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003283 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003285 // If the client's reference count drops to zero, the associated destructor
3286 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3287 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 mClient.clear();
3289 }
3290}
3291
3292void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3293{
Glenn Kastene0feee32011-12-13 11:53:26 -08003294 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003295 mFrameCount = buffer->frameCount;
3296 step();
3297 buffer->frameCount = 0;
3298}
3299
3300bool AudioFlinger::ThreadBase::TrackBase::step() {
3301 bool result;
3302 audio_track_cblk_t* cblk = this->cblk();
3303
3304 result = cblk->stepServer(mFrameCount);
3305 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003306 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 mFlags |= STEPSERVER_FAILED;
3308 }
3309 return result;
3310}
3311
3312void AudioFlinger::ThreadBase::TrackBase::reset() {
3313 audio_track_cblk_t* cblk = this->cblk();
3314
3315 cblk->user = 0;
3316 cblk->server = 0;
3317 cblk->userBase = 0;
3318 cblk->serverBase = 0;
3319 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003320 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321}
3322
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3324 return (int)mCblk->sampleRate;
3325}
3326
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3328 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003329 size_t frameSize = cblk->frameSize;
3330 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3331 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332
3333 // Check validity of returned pointer in case the track control block would have been corrupted.
3334 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003335 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003336 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 -07003337 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003339 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003340 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 }
3342
3343 return bufferStart;
3344}
3345
3346// ----------------------------------------------------------------------------
3347
3348// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3349AudioFlinger::PlaybackThread::Track::Track(
3350 const wp<ThreadBase>& thread,
3351 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003352 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003353 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003354 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003355 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 int frameCount,
3357 const sp<IMemory>& sharedBuffer,
3358 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003359 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003360 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3361 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362{
3363 if (mCblk != NULL) {
3364 sp<ThreadBase> baseThread = thread.promote();
3365 if (baseThread != 0) {
3366 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3367 mName = playbackThread->getTrackName_l();
3368 mMainBuffer = playbackThread->mixBuffer();
3369 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003370 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003372 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003374 mStreamType = streamType;
3375 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3376 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003377 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 }
3379}
3380
3381AudioFlinger::PlaybackThread::Track::~Track()
3382{
Steve Block3856b092011-10-20 11:56:00 +01003383 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 sp<ThreadBase> thread = mThread.promote();
3385 if (thread != 0) {
3386 Mutex::Autolock _l(thread->mLock);
3387 mState = TERMINATED;
3388 }
3389}
3390
3391void AudioFlinger::PlaybackThread::Track::destroy()
3392{
3393 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3394 // by removing it from mTracks vector, so there is a risk that this Tracks's
3395 // desctructor is called. As the destructor needs to lock mLock,
3396 // we must acquire a strong reference on this Track before locking mLock
3397 // here so that the destructor is called only when exiting this function.
3398 // On the other hand, as long as Track::destroy() is only called by
3399 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3400 // this Track with its member mTrack.
3401 sp<Track> keep(this);
3402 { // scope for mLock
3403 sp<ThreadBase> thread = mThread.promote();
3404 if (thread != 0) {
3405 if (!isOutputTrack()) {
3406 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003407 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003408
3409 // to track the speaker usage
3410 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 }
3412 AudioSystem::releaseOutput(thread->id());
3413 }
3414 Mutex::Autolock _l(thread->mLock);
3415 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3416 playbackThread->destroyTrack_l(this);
3417 }
3418 }
3419}
3420
3421void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3422{
Glenn Kasten83d86532012-01-17 14:39:34 -08003423 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003424 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 -07003425 mName - AudioMixer::TRACK0,
Glenn Kasten44deb052012-02-05 18:09:08 -08003426 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 mStreamType,
3428 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003429 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003430 mSessionId,
3431 mFrameCount,
3432 mState,
3433 mMute,
3434 mFillingUpStatus,
3435 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003436 vlr & 0xFFFF,
3437 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 mCblk->server,
3439 mCblk->user,
3440 (int)mMainBuffer,
3441 (int)mAuxBuffer);
3442}
3443
3444status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3445{
3446 audio_track_cblk_t* cblk = this->cblk();
3447 uint32_t framesReady;
3448 uint32_t framesReq = buffer->frameCount;
3449
3450 // Check if last stepServer failed, try to step now
3451 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3452 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003453 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003454 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3455 }
3456
3457 framesReady = cblk->framesReady();
3458
Glenn Kastenf6b16782011-12-15 09:51:17 -08003459 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 uint32_t s = cblk->server;
3461 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3462
3463 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3464 if (framesReq > framesReady) {
3465 framesReq = framesReady;
3466 }
3467 if (s + framesReq > bufferEnd) {
3468 framesReq = bufferEnd - s;
3469 }
3470
3471 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003472 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473
3474 buffer->frameCount = framesReq;
3475 return NO_ERROR;
3476 }
3477
3478getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003479 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003481 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 return NOT_ENOUGH_DATA;
3483}
3484
3485bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003486 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487
3488 if (mCblk->framesReady() >= mCblk->frameCount ||
3489 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3490 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003491 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 return true;
3493 }
3494 return false;
3495}
3496
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003497status_t AudioFlinger::PlaybackThread::Track::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498{
3499 status_t status = NO_ERROR;
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003500 ALOGV("start(%d), calling pid %d session %d tid %d",
3501 mName, IPCThreadState::self()->getCallingPid(), mSessionId, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003502 sp<ThreadBase> thread = mThread.promote();
3503 if (thread != 0) {
3504 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003505 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 // here the track could be either new, or restarted
3507 // in both cases "unstop" the track
3508 if (mState == PAUSED) {
3509 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003510 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 } else {
3512 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003513 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 }
3515
3516 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3517 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003518 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003520
3521 // to track the speaker usage
3522 if (status == NO_ERROR) {
3523 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3524 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 }
3526 if (status == NO_ERROR) {
3527 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3528 playbackThread->addTrack_l(this);
3529 } else {
3530 mState = state;
3531 }
3532 } else {
3533 status = BAD_VALUE;
3534 }
3535 return status;
3536}
3537
3538void AudioFlinger::PlaybackThread::Track::stop()
3539{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003540 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 sp<ThreadBase> thread = mThread.promote();
3542 if (thread != 0) {
3543 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003544 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 if (mState > STOPPED) {
3546 mState = STOPPED;
3547 // If the track is not active (PAUSED and buffers full), flush buffers
3548 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3549 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3550 reset();
3551 }
Steve Block3856b092011-10-20 11:56:00 +01003552 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 }
3554 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3555 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003556 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003557 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003558
3559 // to track the speaker usage
3560 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003561 }
3562 }
3563}
3564
3565void AudioFlinger::PlaybackThread::Track::pause()
3566{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003567 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 sp<ThreadBase> thread = mThread.promote();
3569 if (thread != 0) {
3570 Mutex::Autolock _l(thread->mLock);
3571 if (mState == ACTIVE || mState == RESUMING) {
3572 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003573 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 if (!isOutputTrack()) {
3575 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003576 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003578
3579 // to track the speaker usage
3580 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 }
3582 }
3583 }
3584}
3585
3586void AudioFlinger::PlaybackThread::Track::flush()
3587{
Steve Block3856b092011-10-20 11:56:00 +01003588 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 sp<ThreadBase> thread = mThread.promote();
3590 if (thread != 0) {
3591 Mutex::Autolock _l(thread->mLock);
3592 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3593 return;
3594 }
3595 // No point remaining in PAUSED state after a flush => go to
3596 // STOPPED state
3597 mState = STOPPED;
3598
Eric Laurent38ccae22011-03-28 18:37:07 -07003599 // do not reset the track if it is still in the process of being stopped or paused.
3600 // this will be done by prepareTracks_l() when the track is stopped.
3601 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3602 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3603 reset();
3604 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605 }
3606}
3607
3608void AudioFlinger::PlaybackThread::Track::reset()
3609{
3610 // Do not reset twice to avoid discarding data written just after a flush and before
3611 // the audioflinger thread detects the track is stopped.
3612 if (!mResetDone) {
3613 TrackBase::reset();
3614 // Force underrun condition to avoid false underrun callback until first data is
3615 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003616 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3617 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 mFillingUpStatus = FS_FILLING;
3619 mResetDone = true;
3620 }
3621}
3622
3623void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3624{
3625 mMute = muted;
3626}
3627
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3629{
3630 status_t status = DEAD_OBJECT;
3631 sp<ThreadBase> thread = mThread.promote();
3632 if (thread != 0) {
3633 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3634 status = playbackThread->attachAuxEffect(this, EffectId);
3635 }
3636 return status;
3637}
3638
3639void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3640{
3641 mAuxEffectId = EffectId;
3642 mAuxBuffer = buffer;
3643}
3644
3645// ----------------------------------------------------------------------------
3646
3647// RecordTrack constructor must be called with AudioFlinger::mLock held
3648AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3649 const wp<ThreadBase>& thread,
3650 const sp<Client>& client,
3651 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003652 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003653 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003654 int frameCount,
3655 uint32_t flags,
3656 int sessionId)
3657 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003658 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 mOverflow(false)
3660{
3661 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003662 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003663 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003664 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003665 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003666 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667 } else {
3668 mCblk->frameSize = sizeof(int8_t);
3669 }
3670 }
3671}
3672
3673AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3674{
3675 sp<ThreadBase> thread = mThread.promote();
3676 if (thread != 0) {
3677 AudioSystem::releaseInput(thread->id());
3678 }
3679}
3680
3681status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3682{
3683 audio_track_cblk_t* cblk = this->cblk();
3684 uint32_t framesAvail;
3685 uint32_t framesReq = buffer->frameCount;
3686
3687 // Check if last stepServer failed, try to step now
3688 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3689 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003690 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3692 }
3693
3694 framesAvail = cblk->framesAvailable_l();
3695
Glenn Kastenf6b16782011-12-15 09:51:17 -08003696 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003697 uint32_t s = cblk->server;
3698 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3699
3700 if (framesReq > framesAvail) {
3701 framesReq = framesAvail;
3702 }
3703 if (s + framesReq > bufferEnd) {
3704 framesReq = bufferEnd - s;
3705 }
3706
3707 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003708 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709
3710 buffer->frameCount = framesReq;
3711 return NO_ERROR;
3712 }
3713
3714getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003715 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 buffer->frameCount = 0;
3717 return NOT_ENOUGH_DATA;
3718}
3719
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003720status_t AudioFlinger::RecordThread::RecordTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721{
3722 sp<ThreadBase> thread = mThread.promote();
3723 if (thread != 0) {
3724 RecordThread *recordThread = (RecordThread *)thread.get();
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003725 return recordThread->start(this, tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726 } else {
3727 return BAD_VALUE;
3728 }
3729}
3730
3731void AudioFlinger::RecordThread::RecordTrack::stop()
3732{
3733 sp<ThreadBase> thread = mThread.promote();
3734 if (thread != 0) {
3735 RecordThread *recordThread = (RecordThread *)thread.get();
3736 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003737 TrackBase::reset();
3738 // Force overerrun condition to avoid false overrun callback until first data is
3739 // read from buffer
3740 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741 }
3742}
3743
3744void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3745{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003746 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08003747 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003749 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003750 mSessionId,
3751 mFrameCount,
3752 mState,
3753 mCblk->sampleRate,
3754 mCblk->server,
3755 mCblk->user);
3756}
3757
3758
3759// ----------------------------------------------------------------------------
3760
3761AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3762 const wp<ThreadBase>& thread,
3763 DuplicatingThread *sourceThread,
3764 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003765 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003766 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003768 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 mActive(false), mSourceThread(sourceThread)
3770{
3771
3772 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3773 if (mCblk != NULL) {
3774 mCblk->flags |= CBLK_DIRECTION_OUT;
3775 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 mOutBuffer.frameCount = 0;
3777 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003778 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003779 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3780 mCblk, mBuffer, mCblk->buffers,
3781 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003783 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003784 }
3785}
3786
3787AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3788{
3789 clearBufferQueue();
3790}
3791
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003792status_t AudioFlinger::PlaybackThread::OutputTrack::start(pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003793{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003794 status_t status = Track::start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 if (status != NO_ERROR) {
3796 return status;
3797 }
3798
3799 mActive = true;
3800 mRetryCount = 127;
3801 return status;
3802}
3803
3804void AudioFlinger::PlaybackThread::OutputTrack::stop()
3805{
3806 Track::stop();
3807 clearBufferQueue();
3808 mOutBuffer.frameCount = 0;
3809 mActive = false;
3810}
3811
3812bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3813{
3814 Buffer *pInBuffer;
3815 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003816 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003817 bool outputBufferFull = false;
3818 inBuffer.frameCount = frames;
3819 inBuffer.i16 = data;
3820
3821 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3822
3823 if (!mActive && frames != 0) {
Glenn Kasten6dbc1352012-02-02 10:56:47 -08003824 start(0);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825 sp<ThreadBase> thread = mThread.promote();
3826 if (thread != 0) {
3827 MixerThread *mixerThread = (MixerThread *)thread.get();
3828 if (mCblk->frameCount > frames){
3829 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3830 uint32_t startFrames = (mCblk->frameCount - frames);
3831 pInBuffer = new Buffer;
3832 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3833 pInBuffer->frameCount = startFrames;
3834 pInBuffer->i16 = pInBuffer->mBuffer;
3835 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3836 mBufferQueue.add(pInBuffer);
3837 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003838 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 }
3840 }
3841 }
3842 }
3843
3844 while (waitTimeLeftMs) {
3845 // First write pending buffers, then new data
3846 if (mBufferQueue.size()) {
3847 pInBuffer = mBufferQueue.itemAt(0);
3848 } else {
3849 pInBuffer = &inBuffer;
3850 }
3851
3852 if (pInBuffer->frameCount == 0) {
3853 break;
3854 }
3855
3856 if (mOutBuffer.frameCount == 0) {
3857 mOutBuffer.frameCount = pInBuffer->frameCount;
3858 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003859 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003860 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861 outputBufferFull = true;
3862 break;
3863 }
3864 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3865 if (waitTimeLeftMs >= waitTimeMs) {
3866 waitTimeLeftMs -= waitTimeMs;
3867 } else {
3868 waitTimeLeftMs = 0;
3869 }
3870 }
3871
3872 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3873 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3874 mCblk->stepUser(outFrames);
3875 pInBuffer->frameCount -= outFrames;
3876 pInBuffer->i16 += outFrames * channelCount;
3877 mOutBuffer.frameCount -= outFrames;
3878 mOutBuffer.i16 += outFrames * channelCount;
3879
3880 if (pInBuffer->frameCount == 0) {
3881 if (mBufferQueue.size()) {
3882 mBufferQueue.removeAt(0);
3883 delete [] pInBuffer->mBuffer;
3884 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003885 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 } else {
3887 break;
3888 }
3889 }
3890 }
3891
3892 // If we could not write all frames, allocate a buffer and queue it for next time.
3893 if (inBuffer.frameCount) {
3894 sp<ThreadBase> thread = mThread.promote();
3895 if (thread != 0 && !thread->standby()) {
3896 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3897 pInBuffer = new Buffer;
3898 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3899 pInBuffer->frameCount = inBuffer.frameCount;
3900 pInBuffer->i16 = pInBuffer->mBuffer;
3901 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3902 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003903 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003905 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 }
3907 }
3908 }
3909
3910 // Calling write() with a 0 length buffer, means that no more data will be written:
3911 // If no more buffers are pending, fill output track buffer to make sure it is started
3912 // by output mixer.
3913 if (frames == 0 && mBufferQueue.size() == 0) {
3914 if (mCblk->user < mCblk->frameCount) {
3915 frames = mCblk->frameCount - mCblk->user;
3916 pInBuffer = new Buffer;
3917 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3918 pInBuffer->frameCount = frames;
3919 pInBuffer->i16 = pInBuffer->mBuffer;
3920 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3921 mBufferQueue.add(pInBuffer);
3922 } else if (mActive) {
3923 stop();
3924 }
3925 }
3926
3927 return outputBufferFull;
3928}
3929
3930status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3931{
3932 int active;
3933 status_t result;
3934 audio_track_cblk_t* cblk = mCblk;
3935 uint32_t framesReq = buffer->frameCount;
3936
Steve Block3856b092011-10-20 11:56:00 +01003937// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 buffer->frameCount = 0;
3939
3940 uint32_t framesAvail = cblk->framesAvailable();
3941
3942
3943 if (framesAvail == 0) {
3944 Mutex::Autolock _l(cblk->lock);
3945 goto start_loop_here;
3946 while (framesAvail == 0) {
3947 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003948 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003949 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003950 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 }
3952 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3953 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003954 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003955 }
3956 // read the server count again
3957 start_loop_here:
3958 framesAvail = cblk->framesAvailable_l();
3959 }
3960 }
3961
3962// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003963// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003964// }
3965
3966 if (framesReq > framesAvail) {
3967 framesReq = framesAvail;
3968 }
3969
3970 uint32_t u = cblk->user;
3971 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3972
3973 if (u + framesReq > bufferEnd) {
3974 framesReq = bufferEnd - u;
3975 }
3976
3977 buffer->frameCount = framesReq;
3978 buffer->raw = (void *)cblk->buffer(u);
3979 return NO_ERROR;
3980}
3981
3982
3983void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3984{
3985 size_t size = mBufferQueue.size();
3986 Buffer *pBuffer;
3987
3988 for (size_t i = 0; i < size; i++) {
3989 pBuffer = mBufferQueue.itemAt(i);
3990 delete [] pBuffer->mBuffer;
3991 delete pBuffer;
3992 }
3993 mBufferQueue.clear();
3994}
3995
3996// ----------------------------------------------------------------------------
3997
3998AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3999 : RefBase(),
4000 mAudioFlinger(audioFlinger),
4001 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4002 mPid(pid)
4003{
4004 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4005}
4006
4007// Client destructor must be called with AudioFlinger::mLock held
4008AudioFlinger::Client::~Client()
4009{
4010 mAudioFlinger->removeClient_l(mPid);
4011}
4012
Glenn Kasten435dbe62012-01-30 10:15:48 -08004013sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004014{
4015 return mMemoryDealer;
4016}
4017
4018// ----------------------------------------------------------------------------
4019
4020AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4021 const sp<IAudioFlingerClient>& client,
4022 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004023 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024{
4025}
4026
4027AudioFlinger::NotificationClient::~NotificationClient()
4028{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
4031void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4032{
4033 sp<NotificationClient> keep(this);
4034 {
4035 mAudioFlinger->removeNotificationClient(mPid);
4036 }
4037}
4038
4039// ----------------------------------------------------------------------------
4040
4041AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4042 : BnAudioTrack(),
4043 mTrack(track)
4044{
4045}
4046
4047AudioFlinger::TrackHandle::~TrackHandle() {
4048 // just stop the track on deletion, associated resources
4049 // will be freed from the main thread once all pending buffers have
4050 // been played. Unless it's not in the active track list, in which
4051 // case we free everything now...
4052 mTrack->destroy();
4053}
4054
Glenn Kasten90716c52012-01-26 13:40:12 -08004055sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4056 return mTrack->getCblk();
4057}
4058
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004059status_t AudioFlinger::TrackHandle::start(pid_t tid) {
4060 return mTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061}
4062
4063void AudioFlinger::TrackHandle::stop() {
4064 mTrack->stop();
4065}
4066
4067void AudioFlinger::TrackHandle::flush() {
4068 mTrack->flush();
4069}
4070
4071void AudioFlinger::TrackHandle::mute(bool e) {
4072 mTrack->mute(e);
4073}
4074
4075void AudioFlinger::TrackHandle::pause() {
4076 mTrack->pause();
4077}
4078
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4080{
4081 return mTrack->attachAuxEffect(EffectId);
4082}
4083
4084status_t AudioFlinger::TrackHandle::onTransact(
4085 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4086{
4087 return BnAudioTrack::onTransact(code, data, reply, flags);
4088}
4089
4090// ----------------------------------------------------------------------------
4091
4092sp<IAudioRecord> AudioFlinger::openRecord(
4093 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004094 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004095 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004096 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004097 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 int frameCount,
4099 uint32_t flags,
4100 int *sessionId,
4101 status_t *status)
4102{
4103 sp<RecordThread::RecordTrack> recordTrack;
4104 sp<RecordHandle> recordHandle;
4105 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 status_t lStatus;
4107 RecordThread *thread;
4108 size_t inFrameCount;
4109 int lSessionId;
4110
4111 // check calling permissions
4112 if (!recordingAllowed()) {
4113 lStatus = PERMISSION_DENIED;
4114 goto Exit;
4115 }
4116
4117 // add client to list
4118 { // scope for mLock
4119 Mutex::Autolock _l(mLock);
4120 thread = checkRecordThread_l(input);
4121 if (thread == NULL) {
4122 lStatus = BAD_VALUE;
4123 goto Exit;
4124 }
4125
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004126 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127
4128 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004129 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 lSessionId = *sessionId;
4131 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004132 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 if (sessionId != NULL) {
4134 *sessionId = lSessionId;
4135 }
4136 }
4137 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004138 recordTrack = thread->createRecordTrack_l(client,
4139 sampleRate,
4140 format,
4141 channelMask,
4142 frameCount,
4143 flags,
4144 lSessionId,
4145 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004146 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004147 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4149 // destructor is called by the TrackBase destructor with mLock held
4150 client.clear();
4151 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004152 goto Exit;
4153 }
4154
4155 // return to handle to client
4156 recordHandle = new RecordHandle(recordTrack);
4157 lStatus = NO_ERROR;
4158
4159Exit:
4160 if (status) {
4161 *status = lStatus;
4162 }
4163 return recordHandle;
4164}
4165
4166// ----------------------------------------------------------------------------
4167
4168AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4169 : BnAudioRecord(),
4170 mRecordTrack(recordTrack)
4171{
4172}
4173
4174AudioFlinger::RecordHandle::~RecordHandle() {
4175 stop();
4176}
4177
Glenn Kasten90716c52012-01-26 13:40:12 -08004178sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4179 return mRecordTrack->getCblk();
4180}
4181
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004182status_t AudioFlinger::RecordHandle::start(pid_t tid) {
Steve Block3856b092011-10-20 11:56:00 +01004183 ALOGV("RecordHandle::start()");
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004184 return mRecordTrack->start(tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185}
4186
4187void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004188 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 mRecordTrack->stop();
4190}
4191
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192status_t AudioFlinger::RecordHandle::onTransact(
4193 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4194{
4195 return BnAudioRecord::onTransact(code, data, reply, flags);
4196}
4197
4198// ----------------------------------------------------------------------------
4199
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004200AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4201 AudioStreamIn *input,
4202 uint32_t sampleRate,
4203 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004204 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004205 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004206 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004207 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4208 // mRsmpInIndex and mInputBytes set by readInputParameters()
4209 mReqChannelCount(popcount(channels)),
4210 mReqSampleRate(sampleRate)
4211 // mBytesRead is only meaningful while active, and so is cleared in start()
4212 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004214 snprintf(mName, kNameLength, "AudioIn_%d", id);
4215
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 readInputParameters();
4217}
4218
4219
4220AudioFlinger::RecordThread::~RecordThread()
4221{
4222 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004223 delete mResampler;
4224 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225}
4226
4227void AudioFlinger::RecordThread::onFirstRef()
4228{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004229 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230}
4231
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004232status_t AudioFlinger::RecordThread::readyToRun()
4233{
4234 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004235 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004236 return status;
4237}
4238
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239bool AudioFlinger::RecordThread::threadLoop()
4240{
4241 AudioBufferProvider::Buffer buffer;
4242 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004243 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244
Eric Laurent44d98482010-09-30 16:12:31 -07004245 nsecs_t lastWarning = 0;
4246
Eric Laurentfeb0db62011-07-22 09:04:31 -07004247 acquireWakeLock();
4248
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 // start recording
4250 while (!exitPending()) {
4251
4252 processConfigEvents();
4253
4254 { // scope for mLock
4255 Mutex::Autolock _l(mLock);
4256 checkForNewParameters_l();
4257 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4258 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004259 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 mStandby = true;
4261 }
4262
4263 if (exitPending()) break;
4264
Eric Laurentfeb0db62011-07-22 09:04:31 -07004265 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004266 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 // go to sleep
4268 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004269 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004270 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 continue;
4272 }
4273 if (mActiveTrack != 0) {
4274 if (mActiveTrack->mState == TrackBase::PAUSING) {
4275 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004276 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277 mStandby = true;
4278 }
4279 mActiveTrack.clear();
4280 mStartStopCond.broadcast();
4281 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4282 if (mReqChannelCount != mActiveTrack->channelCount()) {
4283 mActiveTrack.clear();
4284 mStartStopCond.broadcast();
4285 } else if (mBytesRead != 0) {
4286 // record start succeeds only if first read from audio input
4287 // succeeds
4288 if (mBytesRead > 0) {
4289 mActiveTrack->mState = TrackBase::ACTIVE;
4290 } else {
4291 mActiveTrack.clear();
4292 }
4293 mStartStopCond.broadcast();
4294 }
4295 mStandby = false;
4296 }
4297 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004298 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 }
4300
4301 if (mActiveTrack != 0) {
4302 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4303 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004304 unlockEffectChains(effectChains);
4305 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 continue;
4307 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004308 for (size_t i = 0; i < effectChains.size(); i ++) {
4309 effectChains[i]->process_l();
4310 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004311
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004313 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004315 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 // no resampling
4317 while (framesOut) {
4318 size_t framesIn = mFrameCount - mRsmpInIndex;
4319 if (framesIn) {
4320 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4321 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4322 if (framesIn > framesOut)
4323 framesIn = framesOut;
4324 mRsmpInIndex += framesIn;
4325 framesOut -= framesIn;
4326 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004327 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 memcpy(dst, src, framesIn * mFrameSize);
4329 } else {
4330 int16_t *src16 = (int16_t *)src;
4331 int16_t *dst16 = (int16_t *)dst;
4332 if (mChannelCount == 1) {
4333 while (framesIn--) {
4334 *dst16++ = *src16;
4335 *dst16++ = *src16++;
4336 }
4337 } else {
4338 while (framesIn--) {
4339 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4340 src16 += 2;
4341 }
4342 }
4343 }
4344 }
4345 if (framesOut && mFrameCount == mRsmpInIndex) {
4346 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004347 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004348 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 framesOut = 0;
4350 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004351 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004352 mRsmpInIndex = 0;
4353 }
4354 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004355 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004356 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4357 // Force input into standby so that it tries to
4358 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004359 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004360 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361 }
4362 mRsmpInIndex = mFrameCount;
4363 framesOut = 0;
4364 buffer.frameCount = 0;
4365 }
4366 }
4367 }
4368 } else {
4369 // resampling
4370
4371 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4372 // alter output frame count as if we were expecting stereo samples
4373 if (mChannelCount == 1 && mReqChannelCount == 1) {
4374 framesOut >>= 1;
4375 }
4376 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4377 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4378 // are 32 bit aligned which should be always true.
4379 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004380 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 // the resampler always outputs stereo samples: do post stereo to mono conversion
4382 int16_t *src = (int16_t *)mRsmpOutBuffer;
4383 int16_t *dst = buffer.i16;
4384 while (framesOut--) {
4385 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4386 src += 2;
4387 }
4388 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004389 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 }
4391
4392 }
4393 mActiveTrack->releaseBuffer(&buffer);
4394 mActiveTrack->overflow();
4395 }
4396 // client isn't retrieving buffers fast enough
4397 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004398 if (!mActiveTrack->setOverflow()) {
4399 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004400 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004401 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004402 lastWarning = now;
4403 }
4404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 // Release the processor for a while before asking for a new buffer.
4406 // This will give the application more chance to read from the buffer and
4407 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004408 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 }
4410 }
Eric Laurentec437d82011-07-26 20:54:46 -07004411 // enable changes in effect chain
4412 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004413 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004414 }
4415
4416 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004417 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004418 }
4419 mActiveTrack.clear();
4420
4421 mStartStopCond.broadcast();
4422
Eric Laurentfeb0db62011-07-22 09:04:31 -07004423 releaseWakeLock();
4424
Steve Block3856b092011-10-20 11:56:00 +01004425 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 return false;
4427}
4428
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004429
4430sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4431 const sp<AudioFlinger::Client>& client,
4432 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004433 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004434 int channelMask,
4435 int frameCount,
4436 uint32_t flags,
4437 int sessionId,
4438 status_t *status)
4439{
4440 sp<RecordTrack> track;
4441 status_t lStatus;
4442
4443 lStatus = initCheck();
4444 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004445 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004446 goto Exit;
4447 }
4448
4449 { // scope for mLock
4450 Mutex::Autolock _l(mLock);
4451
4452 track = new RecordTrack(this, client, sampleRate,
4453 format, channelMask, frameCount, flags, sessionId);
4454
Glenn Kasten7378ca52012-01-20 13:44:40 -08004455 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004456 lStatus = NO_MEMORY;
4457 goto Exit;
4458 }
4459
4460 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004461 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4462 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004463 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004464 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4465 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004466 }
4467 lStatus = NO_ERROR;
4468
4469Exit:
4470 if (status) {
4471 *status = lStatus;
4472 }
4473 return track;
4474}
4475
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004476status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack, pid_t tid)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004477{
Glenn Kasten6dbc1352012-02-02 10:56:47 -08004478 ALOGV("RecordThread::start tid=%d", tid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479 sp <ThreadBase> strongMe = this;
4480 status_t status = NO_ERROR;
4481 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004482 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004483 if (mActiveTrack != 0) {
4484 if (recordTrack != mActiveTrack.get()) {
4485 status = -EBUSY;
4486 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4487 mActiveTrack->mState = TrackBase::ACTIVE;
4488 }
4489 return status;
4490 }
4491
4492 recordTrack->mState = TrackBase::IDLE;
4493 mActiveTrack = recordTrack;
4494 mLock.unlock();
4495 status_t status = AudioSystem::startInput(mId);
4496 mLock.lock();
4497 if (status != NO_ERROR) {
4498 mActiveTrack.clear();
4499 return status;
4500 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501 mRsmpInIndex = mFrameCount;
4502 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004503 if (mResampler != NULL) {
4504 mResampler->reset();
4505 }
4506 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004508 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 mWaitWorkCV.signal();
4510 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004511 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004512 mActiveTrack.clear();
4513 status = INVALID_OPERATION;
4514 goto startError;
4515 }
4516 mStartStopCond.wait(mLock);
4517 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004518 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519 status = BAD_VALUE;
4520 goto startError;
4521 }
Steve Block3856b092011-10-20 11:56:00 +01004522 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 return status;
4524 }
4525startError:
4526 AudioSystem::stopInput(mId);
4527 return status;
4528}
4529
4530void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004531 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 sp <ThreadBase> strongMe = this;
4533 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004534 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4536 mActiveTrack->mState = TrackBase::PAUSING;
4537 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004538 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 return;
4540 }
4541 mStartStopCond.wait(mLock);
4542 // if we have been restarted, recordTrack == mActiveTrack.get() here
4543 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4544 mLock.unlock();
4545 AudioSystem::stopInput(mId);
4546 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004547 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 }
4549 }
4550 }
4551}
4552
4553status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4554{
4555 const size_t SIZE = 256;
4556 char buffer[SIZE];
4557 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558
4559 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4560 result.append(buffer);
4561
4562 if (mActiveTrack != 0) {
4563 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004564 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 mActiveTrack->dump(buffer, SIZE);
4566 result.append(buffer);
4567
4568 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4569 result.append(buffer);
4570 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4571 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004572 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004573 result.append(buffer);
4574 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4575 result.append(buffer);
4576 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4577 result.append(buffer);
4578
4579
4580 } else {
4581 result.append("No record client\n");
4582 }
4583 write(fd, result.string(), result.size());
4584
4585 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004586 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587
4588 return NO_ERROR;
4589}
4590
4591status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4592{
4593 size_t framesReq = buffer->frameCount;
4594 size_t framesReady = mFrameCount - mRsmpInIndex;
4595 int channelCount;
4596
4597 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004598 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004600 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4602 // Force input into standby so that it tries to
4603 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004604 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004605 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004607 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 buffer->frameCount = 0;
4609 return NOT_ENOUGH_DATA;
4610 }
4611 mRsmpInIndex = 0;
4612 framesReady = mFrameCount;
4613 }
4614
4615 if (framesReq > framesReady) {
4616 framesReq = framesReady;
4617 }
4618
4619 if (mChannelCount == 1 && mReqChannelCount == 2) {
4620 channelCount = 1;
4621 } else {
4622 channelCount = 2;
4623 }
4624 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4625 buffer->frameCount = framesReq;
4626 return NO_ERROR;
4627}
4628
4629void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4630{
4631 mRsmpInIndex += buffer->frameCount;
4632 buffer->frameCount = 0;
4633}
4634
4635bool AudioFlinger::RecordThread::checkForNewParameters_l()
4636{
4637 bool reconfig = false;
4638
4639 while (!mNewParameters.isEmpty()) {
4640 status_t status = NO_ERROR;
4641 String8 keyValuePair = mNewParameters[0];
4642 AudioParameter param = AudioParameter(keyValuePair);
4643 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004644 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 int reqSamplingRate = mReqSampleRate;
4646 int reqChannelCount = mReqChannelCount;
4647
4648 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4649 reqSamplingRate = value;
4650 reconfig = true;
4651 }
4652 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004653 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654 reconfig = true;
4655 }
4656 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004657 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 reconfig = true;
4659 }
4660 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4661 // do not accept frame count changes if tracks are open as the track buffer
4662 // size depends on frame count and correct behavior would not be garantied
4663 // if frame count is changed after track creation
4664 if (mActiveTrack != 0) {
4665 status = INVALID_OPERATION;
4666 } else {
4667 reconfig = true;
4668 }
4669 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004670 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4671 // forward device change to effects that have requested to be
4672 // aware of attached audio device.
4673 for (size_t i = 0; i < mEffectChains.size(); i++) {
4674 mEffectChains[i]->setDevice_l(value);
4675 }
4676 // store input device and output device but do not forward output device to audio HAL.
4677 // Note that status is ignored by the caller for output device
4678 // (see AudioFlinger::setParameters()
4679 if (value & AUDIO_DEVICE_OUT_ALL) {
4680 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4681 status = BAD_VALUE;
4682 } else {
4683 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004684 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4685 if (mTrack != NULL) {
4686 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004687 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004688 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4689 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4690 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004691 }
4692 mDevice |= (uint32_t)value;
4693 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004695 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004696 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004697 mInput->stream->common.standby(&mInput->stream->common);
4698 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699 }
4700 if (reconfig) {
4701 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004702 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004703 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004704 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4705 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004706 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707 status = NO_ERROR;
4708 }
4709 if (status == NO_ERROR) {
4710 readInputParameters();
4711 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4712 }
4713 }
4714 }
4715
4716 mNewParameters.removeAt(0);
4717
4718 mParamStatus = status;
4719 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004720 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4721 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004722 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 }
4724 return reconfig;
4725}
4726
4727String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4728{
Dima Zavinfce7a472011-04-19 22:30:36 -07004729 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004730 String8 out_s8 = String8();
4731
4732 Mutex::Autolock _l(mLock);
4733 if (initCheck() != NO_ERROR) {
4734 return out_s8;
4735 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004736
Dima Zavin799a70e2011-04-18 16:57:27 -07004737 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004738 out_s8 = String8(s);
4739 free(s);
4740 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741}
4742
4743void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4744 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004745 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746
4747 switch (event) {
4748 case AudioSystem::INPUT_OPENED:
4749 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004750 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004751 desc.samplingRate = mSampleRate;
4752 desc.format = mFormat;
4753 desc.frameCount = mFrameCount;
4754 desc.latency = 0;
4755 param2 = &desc;
4756 break;
4757
4758 case AudioSystem::INPUT_CLOSED:
4759 default:
4760 break;
4761 }
4762 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4763}
4764
4765void AudioFlinger::RecordThread::readInputParameters()
4766{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004767 delete mRsmpInBuffer;
4768 // mRsmpInBuffer is always assigned a new[] below
4769 delete mRsmpOutBuffer;
4770 mRsmpOutBuffer = NULL;
4771 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004772 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773
Dima Zavin799a70e2011-04-18 16:57:27 -07004774 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004775 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4776 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004777 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004778 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004779 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004780 mFrameCount = mInputBytes / mFrameSize;
4781 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4782
4783 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4784 {
4785 int channelCount;
4786 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4787 // stereo to mono post process as the resampler always outputs stereo.
4788 if (mChannelCount == 1 && mReqChannelCount == 2) {
4789 channelCount = 1;
4790 } else {
4791 channelCount = 2;
4792 }
4793 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4794 mResampler->setSampleRate(mSampleRate);
4795 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4796 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4797
4798 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4799 if (mChannelCount == 1 && mReqChannelCount == 1) {
4800 mFrameCount >>= 1;
4801 }
4802
4803 }
4804 mRsmpInIndex = mFrameCount;
4805}
4806
4807unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4808{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004809 Mutex::Autolock _l(mLock);
4810 if (initCheck() != NO_ERROR) {
4811 return 0;
4812 }
4813
Dima Zavin799a70e2011-04-18 16:57:27 -07004814 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815}
4816
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004817uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4818{
4819 Mutex::Autolock _l(mLock);
4820 uint32_t result = 0;
4821 if (getEffectChain_l(sessionId) != 0) {
4822 result = EFFECT_SESSION;
4823 }
4824
4825 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4826 result |= TRACK_SESSION;
4827 }
4828
4829 return result;
4830}
4831
Eric Laurent59bd0da2011-08-01 09:52:20 -07004832AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4833{
4834 Mutex::Autolock _l(mLock);
4835 return mTrack;
4836}
4837
Glenn Kastenaed850d2012-01-26 09:46:34 -08004838AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004839{
4840 Mutex::Autolock _l(mLock);
4841 return mInput;
4842}
4843
4844AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4845{
4846 Mutex::Autolock _l(mLock);
4847 AudioStreamIn *input = mInput;
4848 mInput = NULL;
4849 return input;
4850}
4851
4852// this method must always be called either with ThreadBase mLock held or inside the thread loop
4853audio_stream_t* AudioFlinger::RecordThread::stream()
4854{
4855 if (mInput == NULL) {
4856 return NULL;
4857 }
4858 return &mInput->stream->common;
4859}
4860
4861
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862// ----------------------------------------------------------------------------
4863
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004864audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004865 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004866 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004867 uint32_t *pChannels,
4868 uint32_t *pLatencyMs,
4869 uint32_t flags)
4870{
4871 status_t status;
4872 PlaybackThread *thread = NULL;
4873 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4874 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004875 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876 uint32_t channels = pChannels ? *pChannels : 0;
4877 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004878 audio_stream_out_t *outStream;
4879 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880
Steve Block3856b092011-10-20 11:56:00 +01004881 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004882 pDevices ? *pDevices : 0,
4883 samplingRate,
4884 format,
4885 channels,
4886 flags);
4887
4888 if (pDevices == NULL || *pDevices == 0) {
4889 return 0;
4890 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004891
Mathias Agopian65ab4712010-07-14 17:59:35 -07004892 Mutex::Autolock _l(mLock);
4893
Dima Zavin799a70e2011-04-18 16:57:27 -07004894 outHwDev = findSuitableHwDev_l(*pDevices);
4895 if (outHwDev == NULL)
4896 return 0;
4897
Glenn Kasten58f30212012-01-12 12:27:51 -08004898 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004899 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004900 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004901 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004902 samplingRate,
4903 format,
4904 channels,
4905 status);
4906
4907 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004908 if (outStream != NULL) {
4909 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004910 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004911
Dima Zavinfce7a472011-04-19 22:30:36 -07004912 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4913 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4914 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004916 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 } else {
4918 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004919 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 }
4921 mPlaybackThreads.add(id, thread);
4922
Glenn Kastena0d68332012-01-27 16:47:15 -08004923 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4924 if (pFormat != NULL) *pFormat = format;
4925 if (pChannels != NULL) *pChannels = channels;
4926 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927
4928 // notify client processes of the new output creation
4929 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4930 return id;
4931 }
4932
4933 return 0;
4934}
4935
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004936audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4937 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938{
4939 Mutex::Autolock _l(mLock);
4940 MixerThread *thread1 = checkMixerThread_l(output1);
4941 MixerThread *thread2 = checkMixerThread_l(output2);
4942
4943 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004944 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945 return 0;
4946 }
4947
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004948 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4950 thread->addOutputTrack(thread2);
4951 mPlaybackThreads.add(id, thread);
4952 // notify client processes of the new output creation
4953 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4954 return id;
4955}
4956
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004957status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958{
4959 // keep strong reference on the playback thread so that
4960 // it is not destroyed while exit() is executed
4961 sp <PlaybackThread> thread;
4962 {
4963 Mutex::Autolock _l(mLock);
4964 thread = checkPlaybackThread_l(output);
4965 if (thread == NULL) {
4966 return BAD_VALUE;
4967 }
4968
Steve Block3856b092011-10-20 11:56:00 +01004969 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004970
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004971 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004973 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004974 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4975 dupThread->removeOutputTrack((MixerThread *)thread.get());
4976 }
4977 }
4978 }
Glenn Kastena0d68332012-01-27 16:47:15 -08004979 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4981 mPlaybackThreads.removeItem(output);
4982 }
4983 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08004984 // The thread entity (active unit of execution) is no longer running here,
4985 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004987 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004988 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08004989 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004990 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07004991 out->hwDev->close_output_stream(out->hwDev, out->stream);
4992 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 }
4994 return NO_ERROR;
4995}
4996
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004997status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998{
4999 Mutex::Autolock _l(mLock);
5000 PlaybackThread *thread = checkPlaybackThread_l(output);
5001
5002 if (thread == NULL) {
5003 return BAD_VALUE;
5004 }
5005
Steve Block3856b092011-10-20 11:56:00 +01005006 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 thread->suspend();
5008
5009 return NO_ERROR;
5010}
5011
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005012status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013{
5014 Mutex::Autolock _l(mLock);
5015 PlaybackThread *thread = checkPlaybackThread_l(output);
5016
5017 if (thread == NULL) {
5018 return BAD_VALUE;
5019 }
5020
Steve Block3856b092011-10-20 11:56:00 +01005021 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005022
5023 thread->restore();
5024
5025 return NO_ERROR;
5026}
5027
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005028audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005029 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005030 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005032 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005033{
5034 status_t status;
5035 RecordThread *thread = NULL;
5036 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005037 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038 uint32_t channels = pChannels ? *pChannels : 0;
5039 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005040 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005041 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005042 audio_stream_in_t *inStream;
5043 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005044
5045 if (pDevices == NULL || *pDevices == 0) {
5046 return 0;
5047 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005048
Mathias Agopian65ab4712010-07-14 17:59:35 -07005049 Mutex::Autolock _l(mLock);
5050
Dima Zavin799a70e2011-04-18 16:57:27 -07005051 inHwDev = findSuitableHwDev_l(*pDevices);
5052 if (inHwDev == NULL)
5053 return 0;
5054
Glenn Kasten58f30212012-01-12 12:27:51 -08005055 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005056 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005057 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005058 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005059 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005060 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 samplingRate,
5062 format,
5063 channels,
5064 acoustics,
5065 status);
5066
5067 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5068 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5069 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005070 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005071 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005073 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005074 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005075 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005076 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005077 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005078 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 }
5080
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 if (inStream != NULL) {
5082 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5083
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005084 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005085 // Start record thread
5086 // RecorThread require both input and output device indication to forward to audio
5087 // pre processing modules
5088 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5089 thread = new RecordThread(this,
5090 input,
5091 reqSamplingRate,
5092 reqChannels,
5093 id,
5094 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005096 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005097 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5098 if (pFormat != NULL) *pFormat = format;
5099 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100
Dima Zavin799a70e2011-04-18 16:57:27 -07005101 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102
5103 // notify client processes of the new input creation
5104 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5105 return id;
5106 }
5107
5108 return 0;
5109}
5110
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005111status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112{
5113 // keep strong reference on the record thread so that
5114 // it is not destroyed while exit() is executed
5115 sp <RecordThread> thread;
5116 {
5117 Mutex::Autolock _l(mLock);
5118 thread = checkRecordThread_l(input);
5119 if (thread == NULL) {
5120 return BAD_VALUE;
5121 }
5122
Steve Block3856b092011-10-20 11:56:00 +01005123 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005124 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5126 mRecordThreads.removeItem(input);
5127 }
5128 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005129 // The thread entity (active unit of execution) is no longer running here,
5130 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005132 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005133 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005134 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005135 in->hwDev->close_input_stream(in->hwDev, in->stream);
5136 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005137
5138 return NO_ERROR;
5139}
5140
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005141status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142{
5143 Mutex::Autolock _l(mLock);
5144 MixerThread *dstThread = checkMixerThread_l(output);
5145 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005146 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 return BAD_VALUE;
5148 }
5149
Steve Block3856b092011-10-20 11:56:00 +01005150 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5152
Eric Laurent9f6530f2011-08-30 10:18:54 -07005153 dstThread->setStreamValid(stream, true);
5154
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5156 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5157 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005158 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005160 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 }
Eric Laurentde070132010-07-13 04:45:46 -07005163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164
5165 return NO_ERROR;
5166}
5167
5168
5169int AudioFlinger::newAudioSessionId()
5170{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005171 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172}
5173
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005174void AudioFlinger::acquireAudioSessionId(int audioSession)
5175{
5176 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005177 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005178 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005179 int num = mAudioSessionRefs.size();
5180 for (int i = 0; i< num; i++) {
5181 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5182 if (ref->sessionid == audioSession && ref->pid == caller) {
5183 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005184 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005185 return;
5186 }
5187 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005188 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5189 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005190}
5191
5192void AudioFlinger::releaseAudioSessionId(int audioSession)
5193{
5194 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005195 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005196 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005197 int num = mAudioSessionRefs.size();
5198 for (int i = 0; i< num; i++) {
5199 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5200 if (ref->sessionid == audioSession && ref->pid == caller) {
5201 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005202 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005203 if (ref->cnt == 0) {
5204 mAudioSessionRefs.removeAt(i);
5205 delete ref;
5206 purgeStaleEffects_l();
5207 }
5208 return;
5209 }
5210 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005211 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005212}
5213
5214void AudioFlinger::purgeStaleEffects_l() {
5215
Steve Block3856b092011-10-20 11:56:00 +01005216 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005217
5218 Vector< sp<EffectChain> > chains;
5219
5220 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5221 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5222 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5223 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005224 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5225 chains.push(ec);
5226 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005227 }
5228 }
5229 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5230 sp<RecordThread> t = mRecordThreads.valueAt(i);
5231 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5232 sp<EffectChain> ec = t->mEffectChains[j];
5233 chains.push(ec);
5234 }
5235 }
5236
5237 for (size_t i = 0; i < chains.size(); i++) {
5238 sp<EffectChain> ec = chains[i];
5239 int sessionid = ec->sessionId();
5240 sp<ThreadBase> t = ec->mThread.promote();
5241 if (t == 0) {
5242 continue;
5243 }
5244 size_t numsessionrefs = mAudioSessionRefs.size();
5245 bool found = false;
5246 for (size_t k = 0; k < numsessionrefs; k++) {
5247 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5248 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005249 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005250 sessionid, ref->pid, ref->cnt);
5251 found = true;
5252 break;
5253 }
5254 }
5255 if (!found) {
5256 // remove all effects from the chain
5257 while (ec->mEffects.size()) {
5258 sp<EffectModule> effect = ec->mEffects[0];
5259 effect->unPin();
5260 Mutex::Autolock _l (t->mLock);
5261 t->removeEffect_l(effect);
5262 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5263 sp<EffectHandle> handle = effect->mHandles[j].promote();
5264 if (handle != 0) {
5265 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005266 if (handle->mHasControl && handle->mEnabled) {
5267 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5268 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005269 }
5270 }
5271 AudioSystem::unregisterEffect(effect->id());
5272 }
5273 }
5274 }
5275 return;
5276}
5277
Mathias Agopian65ab4712010-07-14 17:59:35 -07005278// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005279AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005280{
5281 PlaybackThread *thread = NULL;
5282 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5283 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5284 }
5285 return thread;
5286}
5287
5288// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005289AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005290{
5291 PlaybackThread *thread = checkPlaybackThread_l(output);
5292 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005293 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294 thread = NULL;
5295 }
5296 }
5297 return (MixerThread *)thread;
5298}
5299
5300// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005301AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302{
5303 RecordThread *thread = NULL;
5304 if (mRecordThreads.indexOfKey(input) >= 0) {
5305 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5306 }
5307 return thread;
5308}
5309
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005310uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005312 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313}
5314
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005315AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5316{
5317 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5318 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005319 AudioStreamOut *output = thread->getOutput();
5320 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005321 return thread;
5322 }
5323 }
5324 return NULL;
5325}
5326
5327uint32_t AudioFlinger::primaryOutputDevice_l()
5328{
5329 PlaybackThread *thread = primaryPlaybackThread_l();
5330
5331 if (thread == NULL) {
5332 return 0;
5333 }
5334
5335 return thread->device();
5336}
5337
5338
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339// ----------------------------------------------------------------------------
5340// Effect management
5341// ----------------------------------------------------------------------------
5342
5343
Glenn Kastenf587ba52012-01-26 16:25:10 -08005344status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345{
5346 Mutex::Autolock _l(mLock);
5347 return EffectQueryNumberEffects(numEffects);
5348}
5349
Glenn Kastenf587ba52012-01-26 16:25:10 -08005350status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351{
5352 Mutex::Autolock _l(mLock);
5353 return EffectQueryEffect(index, descriptor);
5354}
5355
Glenn Kasten5e92a782012-01-30 07:40:52 -08005356status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005357 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358{
5359 Mutex::Autolock _l(mLock);
5360 return EffectGetDescriptor(pUuid, descriptor);
5361}
5362
5363
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5365 effect_descriptor_t *pDesc,
5366 const sp<IEffectClient>& effectClient,
5367 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005368 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 int sessionId,
5370 status_t *status,
5371 int *id,
5372 int *enabled)
5373{
5374 status_t lStatus = NO_ERROR;
5375 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005376 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005378 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005379 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380
5381 if (pDesc == NULL) {
5382 lStatus = BAD_VALUE;
5383 goto Exit;
5384 }
5385
Eric Laurent84e9a102010-09-23 16:10:16 -07005386 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005387 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005388 lStatus = PERMISSION_DENIED;
5389 goto Exit;
5390 }
5391
Dima Zavinfce7a472011-04-19 22:30:36 -07005392 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005393 // that can only be created by audio policy manager (running in same process)
Glenn Kasten44deb052012-02-05 18:09:08 -08005394 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid_cached != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005395 lStatus = PERMISSION_DENIED;
5396 goto Exit;
5397 }
5398
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005399 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005400 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005401 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005402 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005403 lStatus = BAD_VALUE;
5404 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005406 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005407 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005408 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005409 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005410 }
5411 }
5412
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 {
5414 Mutex::Autolock _l(mLock);
5415
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416
5417 if (!EffectIsNullUuid(&pDesc->uuid)) {
5418 // if uuid is specified, request effect descriptor
5419 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5420 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005421 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 goto Exit;
5423 }
5424 } else {
5425 // if uuid is not specified, look for an available implementation
5426 // of the required type in effect factory
5427 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005428 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 lStatus = BAD_VALUE;
5430 goto Exit;
5431 }
5432 uint32_t numEffects = 0;
5433 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005434 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435 bool found = false;
5436
5437 lStatus = EffectQueryNumberEffects(&numEffects);
5438 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005439 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 goto Exit;
5441 }
5442 for (uint32_t i = 0; i < numEffects; i++) {
5443 lStatus = EffectQueryEffect(i, &desc);
5444 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005445 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 continue;
5447 }
5448 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5449 // If matching type found save effect descriptor. If the session is
5450 // 0 and the effect is not auxiliary, continue enumeration in case
5451 // an auxiliary version of this effect type is available
5452 found = true;
5453 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005454 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005455 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5456 break;
5457 }
5458 }
5459 }
5460 if (!found) {
5461 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005462 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463 goto Exit;
5464 }
5465 // For same effect type, chose auxiliary version over insert version if
5466 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5469 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5470 }
5471 }
5472
5473 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005474 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5476 lStatus = INVALID_OPERATION;
5477 goto Exit;
5478 }
5479
Eric Laurent59255e42011-07-27 19:49:51 -07005480 // check recording permission for visualizer
5481 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5482 !recordingAllowed()) {
5483 lStatus = PERMISSION_DENIED;
5484 goto Exit;
5485 }
5486
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 // return effect descriptor
5488 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5489
5490 // If output is not specified try to find a matching audio session ID in one of the
5491 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005492 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5493 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005494 // Note: io is never 0 when creating an effect on an input
5495 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005496 // look for the thread where the specified audio session is present
5497 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5498 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005499 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005500 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005503 if (io == 0) {
5504 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5505 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5506 io = mRecordThreads.keyAt(i);
5507 break;
5508 }
5509 }
5510 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005511 // If no output thread contains the requested session ID, default to
5512 // first output. The effect chain will be moved to the correct output
5513 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005514 if (io == 0 && mPlaybackThreads.size()) {
5515 io = mPlaybackThreads.keyAt(0);
5516 }
Steve Block3856b092011-10-20 11:56:00 +01005517 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005518 }
5519 ThreadBase *thread = checkRecordThread_l(io);
5520 if (thread == NULL) {
5521 thread = checkPlaybackThread_l(io);
5522 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005523 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005524 lStatus = BAD_VALUE;
5525 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005528
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005529 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005531 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005532 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5533 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 if (handle != 0 && id != NULL) {
5535 *id = handle->id();
5536 }
5537 }
5538
5539Exit:
5540 if(status) {
5541 *status = lStatus;
5542 }
5543 return handle;
5544}
5545
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005546status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5547 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005548{
Steve Block3856b092011-10-20 11:56:00 +01005549 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005550 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005551 Mutex::Autolock _l(mLock);
5552 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005553 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005554 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 }
Eric Laurentde070132010-07-13 04:45:46 -07005556 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5557 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005558 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005559 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560 }
Eric Laurentde070132010-07-13 04:45:46 -07005561 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5562 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005563 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005564 return BAD_VALUE;
5565 }
5566
5567 Mutex::Autolock _dl(dstThread->mLock);
5568 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005569 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005570
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 return NO_ERROR;
5572}
5573
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005574// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005575status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005576 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005577 AudioFlinger::PlaybackThread *dstThread,
5578 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005579{
Steve Block3856b092011-10-20 11:56:00 +01005580 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005581 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005582
Eric Laurent59255e42011-07-27 19:49:51 -07005583 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005584 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005585 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005586 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005587 return INVALID_OPERATION;
5588 }
5589
Eric Laurent39e94f82010-07-28 01:32:47 -07005590 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005591 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005592 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005593 // removed.
5594 srcThread->removeEffectChain_l(chain);
5595
5596 // transfer all effects one by one so that new effect chain is created on new thread with
5597 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005598 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005599 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005600 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005601 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5602 while (effect != 0) {
5603 srcThread->removeEffect_l(effect);
5604 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005605 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5606 if (effect->state() == EffectModule::ACTIVE ||
5607 effect->state() == EffectModule::STOPPING) {
5608 effect->start();
5609 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005610 // if the move request is not received from audio policy manager, the effect must be
5611 // re-registered with the new strategy and output
5612 if (dstChain == 0) {
5613 dstChain = effect->chain().promote();
5614 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005615 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005616 srcThread->addEffect_l(effect);
5617 return NO_INIT;
5618 }
5619 strategy = dstChain->strategy();
5620 }
5621 if (reRegister) {
5622 AudioSystem::unregisterEffect(effect->id());
5623 AudioSystem::registerEffect(&effect->desc(),
5624 dstOutput,
5625 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005626 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005627 effect->id());
5628 }
Eric Laurentde070132010-07-13 04:45:46 -07005629 effect = chain->getEffectFromId_l(0);
5630 }
5631
5632 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633}
5634
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005635
Mathias Agopian65ab4712010-07-14 17:59:35 -07005636// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005637sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005638 const sp<AudioFlinger::Client>& client,
5639 const sp<IEffectClient>& effectClient,
5640 int32_t priority,
5641 int sessionId,
5642 effect_descriptor_t *desc,
5643 int *enabled,
5644 status_t *status
5645 )
5646{
5647 sp<EffectModule> effect;
5648 sp<EffectHandle> handle;
5649 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005651 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 bool effectCreated = false;
5653 bool effectRegistered = false;
5654
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005655 lStatus = initCheck();
5656 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005657 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658 goto Exit;
5659 }
5660
5661 // Do not allow effects with session ID 0 on direct output or duplicating threads
5662 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005663 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005664 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005665 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 lStatus = BAD_VALUE;
5667 goto Exit;
5668 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005669 // Only Pre processor effects are allowed on input threads and only on input threads
5670 if ((mType == RECORD &&
5671 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5672 (mType != RECORD &&
5673 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005674 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005675 desc->name, desc->flags, mType);
5676 lStatus = BAD_VALUE;
5677 goto Exit;
5678 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679
Steve Block3856b092011-10-20 11:56:00 +01005680 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681
5682 { // scope for mLock
5683 Mutex::Autolock _l(mLock);
5684
5685 // check for existing effect chain with the requested audio session
5686 chain = getEffectChain_l(sessionId);
5687 if (chain == 0) {
5688 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005689 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 chain = new EffectChain(this, sessionId);
5691 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005692 chain->setStrategy(getStrategyForSession_l(sessionId));
5693 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005695 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 }
5697
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005698 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699
5700 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005701 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005703 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 if (lStatus != NO_ERROR) {
5705 goto Exit;
5706 }
5707 effectRegistered = true;
5708 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005709 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 lStatus = effect->status();
5711 if (lStatus != NO_ERROR) {
5712 goto Exit;
5713 }
Eric Laurentcab11242010-07-15 12:50:15 -07005714 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 if (lStatus != NO_ERROR) {
5716 goto Exit;
5717 }
5718 effectCreated = true;
5719
5720 effect->setDevice(mDevice);
5721 effect->setMode(mAudioFlinger->getMode());
5722 }
5723 // create effect handle and connect it to effect module
5724 handle = new EffectHandle(effect, client, effectClient, priority);
5725 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005726 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727 *enabled = (int)effect->isEnabled();
5728 }
5729 }
5730
5731Exit:
5732 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005733 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005735 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 }
5737 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005738 AudioSystem::unregisterEffect(effect->id());
5739 }
5740 if (chainCreated) {
5741 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 }
5743 handle.clear();
5744 }
5745
5746 if(status) {
5747 *status = lStatus;
5748 }
5749 return handle;
5750}
5751
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005752sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5753{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005754 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005755 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005756}
5757
Eric Laurentde070132010-07-13 04:45:46 -07005758// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5759// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005760status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005761{
5762 // check for existing effect chain with the requested audio session
5763 int sessionId = effect->sessionId();
5764 sp<EffectChain> chain = getEffectChain_l(sessionId);
5765 bool chainCreated = false;
5766
5767 if (chain == 0) {
5768 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005769 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005770 chain = new EffectChain(this, sessionId);
5771 addEffectChain_l(chain);
5772 chain->setStrategy(getStrategyForSession_l(sessionId));
5773 chainCreated = true;
5774 }
Steve Block3856b092011-10-20 11:56:00 +01005775 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005776
5777 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005778 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005779 this, effect->desc().name, chain.get());
5780 return BAD_VALUE;
5781 }
5782
5783 status_t status = chain->addEffect_l(effect);
5784 if (status != NO_ERROR) {
5785 if (chainCreated) {
5786 removeEffectChain_l(chain);
5787 }
5788 return status;
5789 }
5790
5791 effect->setDevice(mDevice);
5792 effect->setMode(mAudioFlinger->getMode());
5793 return NO_ERROR;
5794}
5795
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005796void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005797
Steve Block3856b092011-10-20 11:56:00 +01005798 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005799 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005800 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5801 detachAuxEffect_l(effect->id());
5802 }
5803
5804 sp<EffectChain> chain = effect->chain().promote();
5805 if (chain != 0) {
5806 // remove effect chain if removing last effect
5807 if (chain->removeEffect_l(effect) == 0) {
5808 removeEffectChain_l(chain);
5809 }
5810 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005811 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005812 }
5813}
5814
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005815void AudioFlinger::ThreadBase::lockEffectChains_l(
5816 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5817{
5818 effectChains = mEffectChains;
5819 for (size_t i = 0; i < mEffectChains.size(); i++) {
5820 mEffectChains[i]->lock();
5821 }
5822}
5823
5824void AudioFlinger::ThreadBase::unlockEffectChains(
5825 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5826{
5827 for (size_t i = 0; i < effectChains.size(); i++) {
5828 effectChains[i]->unlock();
5829 }
5830}
5831
5832sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5833{
5834 Mutex::Autolock _l(mLock);
5835 return getEffectChain_l(sessionId);
5836}
5837
5838sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5839{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005840 size_t size = mEffectChains.size();
5841 for (size_t i = 0; i < size; i++) {
5842 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005843 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005844 }
5845 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005846 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847}
5848
Glenn Kastenf78aee72012-01-04 11:00:47 -08005849void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005850{
5851 Mutex::Autolock _l(mLock);
5852 size_t size = mEffectChains.size();
5853 for (size_t i = 0; i < size; i++) {
5854 mEffectChains[i]->setMode_l(mode);
5855 }
5856}
5857
5858void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005859 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08005860 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005861
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005863 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 // delete the effect module if removing last handle on it
5865 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08005866 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005867 removeEffect_l(effect);
5868 AudioSystem::unregisterEffect(effect->id());
5869 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870 }
5871}
5872
5873status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5874{
5875 int session = chain->sessionId();
5876 int16_t *buffer = mMixBuffer;
5877 bool ownsBuffer = false;
5878
Steve Block3856b092011-10-20 11:56:00 +01005879 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 if (session > 0) {
5881 // Only one effect chain can be present in direct output thread and it uses
5882 // the mix buffer as input
5883 if (mType != DIRECT) {
5884 size_t numSamples = mFrameCount * mChannelCount;
5885 buffer = new int16_t[numSamples];
5886 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005887 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888 ownsBuffer = true;
5889 }
5890
5891 // Attach all tracks with same session ID to this chain.
5892 for (size_t i = 0; i < mTracks.size(); ++i) {
5893 sp<Track> track = mTracks[i];
5894 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005895 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005897 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898 }
5899 }
5900
5901 // indicate all active tracks in the chain
5902 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5903 sp<Track> track = mActiveTracks[i].promote();
5904 if (track == 0) continue;
5905 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005907 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 }
5909 }
5910 }
5911
5912 chain->setInBuffer(buffer, ownsBuffer);
5913 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005914 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005915 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005916 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5917 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005919 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5920 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005921 // Effect chain for other sessions are inserted at beginning of effect
5922 // chains list to be processed before output mix effects. Relative order between other
5923 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 size_t size = mEffectChains.size();
5925 size_t i = 0;
5926 for (i = 0; i < size; i++) {
5927 if (mEffectChains[i]->sessionId() < session) break;
5928 }
5929 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005930 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931
5932 return NO_ERROR;
5933}
5934
5935size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5936{
5937 int session = chain->sessionId();
5938
Steve Block3856b092011-10-20 11:56:00 +01005939 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940
5941 for (size_t i = 0; i < mEffectChains.size(); i++) {
5942 if (chain == mEffectChains[i]) {
5943 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005944 // detach all active tracks from the chain
5945 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5946 sp<Track> track = mActiveTracks[i].promote();
5947 if (track == 0) continue;
5948 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005949 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005950 chain.get(), session);
5951 chain->decActiveTrackCnt();
5952 }
5953 }
5954
Mathias Agopian65ab4712010-07-14 17:59:35 -07005955 // detach all tracks with same session ID from this chain
5956 for (size_t i = 0; i < mTracks.size(); ++i) {
5957 sp<Track> track = mTracks[i];
5958 if (session == track->sessionId()) {
5959 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005960 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 }
5962 }
Eric Laurentde070132010-07-13 04:45:46 -07005963 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 }
5965 }
5966 return mEffectChains.size();
5967}
5968
Eric Laurentde070132010-07-13 04:45:46 -07005969status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5970 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971{
5972 Mutex::Autolock _l(mLock);
5973 return attachAuxEffect_l(track, EffectId);
5974}
5975
Eric Laurentde070132010-07-13 04:45:46 -07005976status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5977 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978{
5979 status_t status = NO_ERROR;
5980
5981 if (EffectId == 0) {
5982 track->setAuxBuffer(0, NULL);
5983 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005984 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5985 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005986 if (effect != 0) {
5987 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5988 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5989 } else {
5990 status = INVALID_OPERATION;
5991 }
5992 } else {
5993 status = BAD_VALUE;
5994 }
5995 }
5996 return status;
5997}
5998
5999void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6000{
6001 for (size_t i = 0; i < mTracks.size(); ++i) {
6002 sp<Track> track = mTracks[i];
6003 if (track->auxEffectId() == effectId) {
6004 attachAuxEffect_l(track, 0);
6005 }
6006 }
6007}
6008
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006009status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6010{
6011 // only one chain per input thread
6012 if (mEffectChains.size() != 0) {
6013 return INVALID_OPERATION;
6014 }
Steve Block3856b092011-10-20 11:56:00 +01006015 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006016
6017 chain->setInBuffer(NULL);
6018 chain->setOutBuffer(NULL);
6019
Eric Laurent59255e42011-07-27 19:49:51 -07006020 checkSuspendOnAddEffectChain_l(chain);
6021
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006022 mEffectChains.add(chain);
6023
6024 return NO_ERROR;
6025}
6026
6027size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6028{
Steve Block3856b092011-10-20 11:56:00 +01006029 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006030 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006031 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6032 chain.get(), mEffectChains.size(), this);
6033 if (mEffectChains.size() == 1) {
6034 mEffectChains.removeAt(0);
6035 }
6036 return 0;
6037}
6038
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039// ----------------------------------------------------------------------------
6040// EffectModule implementation
6041// ----------------------------------------------------------------------------
6042
6043#undef LOG_TAG
6044#define LOG_TAG "AudioFlinger::EffectModule"
6045
6046AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6047 const wp<AudioFlinger::EffectChain>& chain,
6048 effect_descriptor_t *desc,
6049 int id,
6050 int sessionId)
6051 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006052 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053{
Steve Block3856b092011-10-20 11:56:00 +01006054 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 int lStatus;
6056 sp<ThreadBase> thread = mThread.promote();
6057 if (thread == 0) {
6058 return;
6059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060
6061 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6062
6063 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006064 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065
6066 if (mStatus != NO_ERROR) {
6067 return;
6068 }
6069 lStatus = init();
6070 if (lStatus < 0) {
6071 mStatus = lStatus;
6072 goto Error;
6073 }
6074
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006075 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6076 mPinned = true;
6077 }
Steve Block3856b092011-10-20 11:56:00 +01006078 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079 return;
6080Error:
6081 EffectRelease(mEffectInterface);
6082 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006083 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084}
6085
6086AudioFlinger::EffectModule::~EffectModule()
6087{
Steve Block3856b092011-10-20 11:56:00 +01006088 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006089 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006090 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6091 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6092 sp<ThreadBase> thread = mThread.promote();
6093 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006094 audio_stream_t *stream = thread->stream();
6095 if (stream != NULL) {
6096 stream->remove_audio_effect(stream, mEffectInterface);
6097 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006098 }
6099 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006100 // release effect engine
6101 EffectRelease(mEffectInterface);
6102 }
6103}
6104
Glenn Kasten435dbe62012-01-30 10:15:48 -08006105status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106{
6107 status_t status;
6108
6109 Mutex::Autolock _l(mLock);
6110 // First handle in mHandles has highest priority and controls the effect module
6111 int priority = handle->priority();
6112 size_t size = mHandles.size();
6113 sp<EffectHandle> h;
6114 size_t i;
6115 for (i = 0; i < size; i++) {
6116 h = mHandles[i].promote();
6117 if (h == 0) continue;
6118 if (h->priority() <= priority) break;
6119 }
6120 // if inserted in first place, move effect control from previous owner to this handle
6121 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006122 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006124 enabled = h->enabled();
6125 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006126 }
Eric Laurent59255e42011-07-27 19:49:51 -07006127 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 status = NO_ERROR;
6129 } else {
6130 status = ALREADY_EXISTS;
6131 }
Steve Block3856b092011-10-20 11:56:00 +01006132 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 mHandles.insertAt(handle, i);
6134 return status;
6135}
6136
6137size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6138{
6139 Mutex::Autolock _l(mLock);
6140 size_t size = mHandles.size();
6141 size_t i;
6142 for (i = 0; i < size; i++) {
6143 if (mHandles[i] == handle) break;
6144 }
6145 if (i == size) {
6146 return size;
6147 }
Steve Block3856b092011-10-20 11:56:00 +01006148 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006149
6150 bool enabled = false;
6151 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006152 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006153 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006154 enabled = hdl->enabled();
6155 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 mHandles.removeAt(i);
6157 size = mHandles.size();
6158 // if removed from first place, move effect control from this handle to next in line
6159 if (i == 0 && size != 0) {
6160 sp<EffectHandle> h = mHandles[0].promote();
6161 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006162 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 }
6164 }
6165
Eric Laurentec437d82011-07-26 20:54:46 -07006166 // Prevent calls to process() and other functions on effect interface from now on.
6167 // The effect engine will be released by the destructor when the last strong reference on
6168 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006169 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006170 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006171 }
6172
Mathias Agopian65ab4712010-07-14 17:59:35 -07006173 return size;
6174}
6175
Eric Laurent59255e42011-07-27 19:49:51 -07006176sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6177{
6178 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006179 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006180}
6181
Glenn Kasten58123c32012-02-03 10:32:24 -08006182void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006184 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 // keep a strong reference on this EffectModule to avoid calling the
6186 // destructor before we exit
6187 sp<EffectModule> keep(this);
6188 {
6189 sp<ThreadBase> thread = mThread.promote();
6190 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006191 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 }
6193 }
6194}
6195
6196void AudioFlinger::EffectModule::updateState() {
6197 Mutex::Autolock _l(mLock);
6198
6199 switch (mState) {
6200 case RESTART:
6201 reset_l();
6202 // FALL THROUGH
6203
6204 case STARTING:
6205 // clear auxiliary effect input buffer for next accumulation
6206 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6207 memset(mConfig.inputCfg.buffer.raw,
6208 0,
6209 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6210 }
6211 start_l();
6212 mState = ACTIVE;
6213 break;
6214 case STOPPING:
6215 stop_l();
6216 mDisableWaitCnt = mMaxDisableWaitCnt;
6217 mState = STOPPED;
6218 break;
6219 case STOPPED:
6220 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6221 // turn off sequence.
6222 if (--mDisableWaitCnt == 0) {
6223 reset_l();
6224 mState = IDLE;
6225 }
6226 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006227 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 break;
6229 }
6230}
6231
6232void AudioFlinger::EffectModule::process()
6233{
6234 Mutex::Autolock _l(mLock);
6235
Eric Laurentec437d82011-07-26 20:54:46 -07006236 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 mConfig.inputCfg.buffer.raw == NULL ||
6238 mConfig.outputCfg.buffer.raw == NULL) {
6239 return;
6240 }
6241
Eric Laurent8f45bd72010-08-31 13:50:07 -07006242 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6244 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006245 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006247 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006248 }
6249
6250 // do the actual processing in the effect engine
6251 int ret = (*mEffectInterface)->process(mEffectInterface,
6252 &mConfig.inputCfg.buffer,
6253 &mConfig.outputCfg.buffer);
6254
6255 // force transition to IDLE state when engine is ready
6256 if (mState == STOPPED && ret == -ENODATA) {
6257 mDisableWaitCnt = 1;
6258 }
6259
6260 // clear auxiliary effect input buffer for next accumulation
6261 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006262 memset(mConfig.inputCfg.buffer.raw, 0,
6263 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 }
6265 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006266 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6267 // If an insert effect is idle and input buffer is different from output buffer,
6268 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006270 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006271 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6272 int16_t *in = mConfig.inputCfg.buffer.s16;
6273 int16_t *out = mConfig.outputCfg.buffer.s16;
6274 for (size_t i = 0; i < frameCnt; i++) {
6275 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 }
6278 }
6279}
6280
6281void AudioFlinger::EffectModule::reset_l()
6282{
6283 if (mEffectInterface == NULL) {
6284 return;
6285 }
6286 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6287}
6288
6289status_t AudioFlinger::EffectModule::configure()
6290{
6291 uint32_t channels;
6292 if (mEffectInterface == NULL) {
6293 return NO_INIT;
6294 }
6295
6296 sp<ThreadBase> thread = mThread.promote();
6297 if (thread == 0) {
6298 return DEAD_OBJECT;
6299 }
6300
6301 // TODO: handle configuration of effects replacing track process
6302 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006303 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006305 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 }
6307
6308 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006309 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 } else {
6311 mConfig.inputCfg.channels = channels;
6312 }
6313 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006314 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6315 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006316 mConfig.inputCfg.samplingRate = thread->sampleRate();
6317 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6318 mConfig.inputCfg.bufferProvider.cookie = NULL;
6319 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6320 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6321 mConfig.outputCfg.bufferProvider.cookie = NULL;
6322 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6323 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6324 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6325 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006326 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006327 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328 // - in other sessions:
6329 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6330 // other effect: overwrites output buffer: input buffer == output buffer
6331 // Auxiliary effect:
6332 // accumulates in output buffer: input buffer != output buffer
6333 // Therefore: accumulate <=> input buffer != output buffer
6334 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6335 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6336 } else {
6337 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6338 }
6339 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6340 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6341 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6342 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6343
Steve Block3856b092011-10-20 11:56:00 +01006344 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006345 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6346
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006348 uint32_t size = sizeof(int);
6349 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006350 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006351 sizeof(effect_config_t),
6352 &mConfig,
6353 &size,
6354 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 if (status == 0) {
6356 status = cmdStatus;
6357 }
6358
6359 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6360 (1000 * mConfig.outputCfg.buffer.frameCount);
6361
6362 return status;
6363}
6364
6365status_t AudioFlinger::EffectModule::init()
6366{
6367 Mutex::Autolock _l(mLock);
6368 if (mEffectInterface == NULL) {
6369 return NO_INIT;
6370 }
6371 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006372 uint32_t size = sizeof(status_t);
6373 status_t status = (*mEffectInterface)->command(mEffectInterface,
6374 EFFECT_CMD_INIT,
6375 0,
6376 NULL,
6377 &size,
6378 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006379 if (status == 0) {
6380 status = cmdStatus;
6381 }
6382 return status;
6383}
6384
Eric Laurentec35a142011-10-05 17:42:25 -07006385status_t AudioFlinger::EffectModule::start()
6386{
6387 Mutex::Autolock _l(mLock);
6388 return start_l();
6389}
6390
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391status_t AudioFlinger::EffectModule::start_l()
6392{
6393 if (mEffectInterface == NULL) {
6394 return NO_INIT;
6395 }
6396 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006397 uint32_t size = sizeof(status_t);
6398 status_t status = (*mEffectInterface)->command(mEffectInterface,
6399 EFFECT_CMD_ENABLE,
6400 0,
6401 NULL,
6402 &size,
6403 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404 if (status == 0) {
6405 status = cmdStatus;
6406 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006407 if (status == 0 &&
6408 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6409 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6410 sp<ThreadBase> thread = mThread.promote();
6411 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006412 audio_stream_t *stream = thread->stream();
6413 if (stream != NULL) {
6414 stream->add_audio_effect(stream, mEffectInterface);
6415 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006416 }
6417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418 return status;
6419}
6420
Eric Laurentec437d82011-07-26 20:54:46 -07006421status_t AudioFlinger::EffectModule::stop()
6422{
6423 Mutex::Autolock _l(mLock);
6424 return stop_l();
6425}
6426
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427status_t AudioFlinger::EffectModule::stop_l()
6428{
6429 if (mEffectInterface == NULL) {
6430 return NO_INIT;
6431 }
6432 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006433 uint32_t size = sizeof(status_t);
6434 status_t status = (*mEffectInterface)->command(mEffectInterface,
6435 EFFECT_CMD_DISABLE,
6436 0,
6437 NULL,
6438 &size,
6439 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 if (status == 0) {
6441 status = cmdStatus;
6442 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006443 if (status == 0 &&
6444 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6445 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6446 sp<ThreadBase> thread = mThread.promote();
6447 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006448 audio_stream_t *stream = thread->stream();
6449 if (stream != NULL) {
6450 stream->remove_audio_effect(stream, mEffectInterface);
6451 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006452 }
6453 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 return status;
6455}
6456
Eric Laurent25f43952010-07-28 05:40:18 -07006457status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6458 uint32_t cmdSize,
6459 void *pCmdData,
6460 uint32_t *replySize,
6461 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462{
6463 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006464// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465
Eric Laurentec437d82011-07-26 20:54:46 -07006466 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 return NO_INIT;
6468 }
Eric Laurent25f43952010-07-28 05:40:18 -07006469 status_t status = (*mEffectInterface)->command(mEffectInterface,
6470 cmdCode,
6471 cmdSize,
6472 pCmdData,
6473 replySize,
6474 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006475 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006476 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 for (size_t i = 1; i < mHandles.size(); i++) {
6478 sp<EffectHandle> h = mHandles[i].promote();
6479 if (h != 0) {
6480 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6481 }
6482 }
6483 }
6484 return status;
6485}
6486
6487status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6488{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006489
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006491 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492
6493 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006494 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6495 if (enabled && status != NO_ERROR) {
6496 return status;
6497 }
6498
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 switch (mState) {
6500 // going from disabled to enabled
6501 case IDLE:
6502 mState = STARTING;
6503 break;
6504 case STOPPED:
6505 mState = RESTART;
6506 break;
6507 case STOPPING:
6508 mState = ACTIVE;
6509 break;
6510
6511 // going from enabled to disabled
6512 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006513 mState = STOPPED;
6514 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515 case STARTING:
6516 mState = IDLE;
6517 break;
6518 case ACTIVE:
6519 mState = STOPPING;
6520 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006521 case DESTROYED:
6522 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523 }
6524 for (size_t i = 1; i < mHandles.size(); i++) {
6525 sp<EffectHandle> h = mHandles[i].promote();
6526 if (h != 0) {
6527 h->setEnabled(enabled);
6528 }
6529 }
6530 }
6531 return NO_ERROR;
6532}
6533
Glenn Kastenc59c0042012-02-02 14:06:11 -08006534bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535{
6536 switch (mState) {
6537 case RESTART:
6538 case STARTING:
6539 case ACTIVE:
6540 return true;
6541 case IDLE:
6542 case STOPPING:
6543 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006544 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545 default:
6546 return false;
6547 }
6548}
6549
Glenn Kastenc59c0042012-02-02 14:06:11 -08006550bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006551{
6552 switch (mState) {
6553 case RESTART:
6554 case ACTIVE:
6555 case STOPPING:
6556 case STOPPED:
6557 return true;
6558 case IDLE:
6559 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006560 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006561 default:
6562 return false;
6563 }
6564}
6565
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6567{
6568 Mutex::Autolock _l(mLock);
6569 status_t status = NO_ERROR;
6570
6571 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6572 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006573 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006574 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6575 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 status_t cmdStatus;
6577 uint32_t volume[2];
6578 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006579 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580 volume[0] = *left;
6581 volume[1] = *right;
6582 if (controller) {
6583 pVolume = volume;
6584 }
Eric Laurent25f43952010-07-28 05:40:18 -07006585 status = (*mEffectInterface)->command(mEffectInterface,
6586 EFFECT_CMD_SET_VOLUME,
6587 size,
6588 volume,
6589 &size,
6590 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006591 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6592 *left = volume[0];
6593 *right = volume[1];
6594 }
6595 }
6596 return status;
6597}
6598
6599status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6600{
6601 Mutex::Autolock _l(mLock);
6602 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006603 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6604 // audio pre processing modules on RecordThread can receive both output and
6605 // input device indication in the same call
6606 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6607 if (dev) {
6608 status_t cmdStatus;
6609 uint32_t size = sizeof(status_t);
6610
6611 status = (*mEffectInterface)->command(mEffectInterface,
6612 EFFECT_CMD_SET_DEVICE,
6613 sizeof(uint32_t),
6614 &dev,
6615 &size,
6616 &cmdStatus);
6617 if (status == NO_ERROR) {
6618 status = cmdStatus;
6619 }
6620 }
6621 dev = device & AUDIO_DEVICE_IN_ALL;
6622 if (dev) {
6623 status_t cmdStatus;
6624 uint32_t size = sizeof(status_t);
6625
6626 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6627 EFFECT_CMD_SET_INPUT_DEVICE,
6628 sizeof(uint32_t),
6629 &dev,
6630 &size,
6631 &cmdStatus);
6632 if (status2 == NO_ERROR) {
6633 status2 = cmdStatus;
6634 }
6635 if (status == NO_ERROR) {
6636 status = status2;
6637 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 }
6639 }
6640 return status;
6641}
6642
Glenn Kastenf78aee72012-01-04 11:00:47 -08006643status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644{
6645 Mutex::Autolock _l(mLock);
6646 status_t status = NO_ERROR;
6647 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006649 uint32_t size = sizeof(status_t);
6650 status = (*mEffectInterface)->command(mEffectInterface,
6651 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006652 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006653 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006654 &size,
6655 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006656 if (status == NO_ERROR) {
6657 status = cmdStatus;
6658 }
6659 }
6660 return status;
6661}
6662
Eric Laurent59255e42011-07-27 19:49:51 -07006663void AudioFlinger::EffectModule::setSuspended(bool suspended)
6664{
6665 Mutex::Autolock _l(mLock);
6666 mSuspended = suspended;
6667}
Glenn Kastena3a85482012-01-04 11:01:11 -08006668
6669bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006670{
6671 Mutex::Autolock _l(mLock);
6672 return mSuspended;
6673}
6674
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6676{
6677 const size_t SIZE = 256;
6678 char buffer[SIZE];
6679 String8 result;
6680
6681 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6682 result.append(buffer);
6683
6684 bool locked = tryLock(mLock);
6685 // failed to lock - AudioFlinger is probably deadlocked
6686 if (!locked) {
6687 result.append("\t\tCould not lock Fx mutex:\n");
6688 }
6689
6690 result.append("\t\tSession Status State Engine:\n");
6691 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6692 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6693 result.append(buffer);
6694
6695 result.append("\t\tDescriptor:\n");
6696 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6697 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6698 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6699 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6700 result.append(buffer);
6701 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6702 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6703 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6704 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6705 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006706 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707 mDescriptor.apiVersion,
6708 mDescriptor.flags);
6709 result.append(buffer);
6710 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6711 mDescriptor.name);
6712 result.append(buffer);
6713 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6714 mDescriptor.implementor);
6715 result.append(buffer);
6716
6717 result.append("\t\t- Input configuration:\n");
6718 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6719 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6720 (uint32_t)mConfig.inputCfg.buffer.raw,
6721 mConfig.inputCfg.buffer.frameCount,
6722 mConfig.inputCfg.samplingRate,
6723 mConfig.inputCfg.channels,
6724 mConfig.inputCfg.format);
6725 result.append(buffer);
6726
6727 result.append("\t\t- Output configuration:\n");
6728 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6729 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6730 (uint32_t)mConfig.outputCfg.buffer.raw,
6731 mConfig.outputCfg.buffer.frameCount,
6732 mConfig.outputCfg.samplingRate,
6733 mConfig.outputCfg.channels,
6734 mConfig.outputCfg.format);
6735 result.append(buffer);
6736
6737 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6738 result.append(buffer);
6739 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6740 for (size_t i = 0; i < mHandles.size(); ++i) {
6741 sp<EffectHandle> handle = mHandles[i].promote();
6742 if (handle != 0) {
6743 handle->dump(buffer, SIZE);
6744 result.append(buffer);
6745 }
6746 }
6747
6748 result.append("\n");
6749
6750 write(fd, result.string(), result.length());
6751
6752 if (locked) {
6753 mLock.unlock();
6754 }
6755
6756 return NO_ERROR;
6757}
6758
6759// ----------------------------------------------------------------------------
6760// EffectHandle implementation
6761// ----------------------------------------------------------------------------
6762
6763#undef LOG_TAG
6764#define LOG_TAG "AudioFlinger::EffectHandle"
6765
6766AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6767 const sp<AudioFlinger::Client>& client,
6768 const sp<IEffectClient>& effectClient,
6769 int32_t priority)
6770 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006771 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006772 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006773{
Steve Block3856b092011-10-20 11:56:00 +01006774 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006776 if (client == 0) {
6777 return;
6778 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6780 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6781 if (mCblkMemory != 0) {
6782 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6783
Glenn Kastena0d68332012-01-27 16:47:15 -08006784 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006785 new(mCblk) effect_param_cblk_t();
6786 mBuffer = (uint8_t *)mCblk + bufOffset;
6787 }
6788 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006789 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006790 return;
6791 }
6792}
6793
6794AudioFlinger::EffectHandle::~EffectHandle()
6795{
Steve Block3856b092011-10-20 11:56:00 +01006796 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006797 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006798 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799}
6800
6801status_t AudioFlinger::EffectHandle::enable()
6802{
Steve Block3856b092011-10-20 11:56:00 +01006803 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 if (!mHasControl) return INVALID_OPERATION;
6805 if (mEffect == 0) return DEAD_OBJECT;
6806
Eric Laurentdb7c0792011-08-10 10:37:50 -07006807 if (mEnabled) {
6808 return NO_ERROR;
6809 }
6810
Eric Laurent59255e42011-07-27 19:49:51 -07006811 mEnabled = true;
6812
6813 sp<ThreadBase> thread = mEffect->thread().promote();
6814 if (thread != 0) {
6815 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6816 }
6817
6818 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6819 if (mEffect->suspended()) {
6820 return NO_ERROR;
6821 }
6822
Eric Laurentdb7c0792011-08-10 10:37:50 -07006823 status_t status = mEffect->setEnabled(true);
6824 if (status != NO_ERROR) {
6825 if (thread != 0) {
6826 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6827 }
6828 mEnabled = false;
6829 }
6830 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831}
6832
6833status_t AudioFlinger::EffectHandle::disable()
6834{
Steve Block3856b092011-10-20 11:56:00 +01006835 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006837 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838
Eric Laurentdb7c0792011-08-10 10:37:50 -07006839 if (!mEnabled) {
6840 return NO_ERROR;
6841 }
Eric Laurent59255e42011-07-27 19:49:51 -07006842 mEnabled = false;
6843
6844 if (mEffect->suspended()) {
6845 return NO_ERROR;
6846 }
6847
6848 status_t status = mEffect->setEnabled(false);
6849
6850 sp<ThreadBase> thread = mEffect->thread().promote();
6851 if (thread != 0) {
6852 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6853 }
6854
6855 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856}
6857
6858void AudioFlinger::EffectHandle::disconnect()
6859{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006860 disconnect(true);
6861}
6862
Glenn Kasten58123c32012-02-03 10:32:24 -08006863void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006864{
Glenn Kasten58123c32012-02-03 10:32:24 -08006865 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 if (mEffect == 0) {
6867 return;
6868 }
Glenn Kasten58123c32012-02-03 10:32:24 -08006869 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07006870
Eric Laurenta85a74a2011-10-19 11:44:54 -07006871 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006872 sp<ThreadBase> thread = mEffect->thread().promote();
6873 if (thread != 0) {
6874 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6875 }
Eric Laurent59255e42011-07-27 19:49:51 -07006876 }
6877
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 // release sp on module => module destructor can be called now
6879 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006881 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006882 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006883 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6884 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006885 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006886 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6888 mClient.clear();
6889 }
6890}
6891
Eric Laurent25f43952010-07-28 05:40:18 -07006892status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6893 uint32_t cmdSize,
6894 void *pCmdData,
6895 uint32_t *replySize,
6896 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897{
Steve Block3856b092011-10-20 11:56:00 +01006898// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006899// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900
6901 // only get parameter command is permitted for applications not controlling the effect
6902 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6903 return INVALID_OPERATION;
6904 }
6905 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006906 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907
6908 // handle commands that are not forwarded transparently to effect engine
6909 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6910 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6911 // no risk to block the whole media server process or mixer threads is we are stuck here
6912 Mutex::Autolock _l(mCblk->lock);
6913 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6914 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6915 mCblk->serverIndex = 0;
6916 mCblk->clientIndex = 0;
6917 return BAD_VALUE;
6918 }
6919 status_t status = NO_ERROR;
6920 while (mCblk->serverIndex < mCblk->clientIndex) {
6921 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006922 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923 int *p = (int *)(mBuffer + mCblk->serverIndex);
6924 int size = *p++;
6925 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006926 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927 break;
6928 }
6929 effect_param_t *param = (effect_param_t *)p;
6930 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006931 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932 mCblk->serverIndex += size;
6933 continue;
6934 }
Eric Laurent25f43952010-07-28 05:40:18 -07006935 uint32_t psize = sizeof(effect_param_t) +
6936 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6937 param->vsize;
6938 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6939 psize,
6940 p,
6941 &rsize,
6942 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006943 // stop at first error encountered
6944 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006945 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006946 *(int *)pReplyData = reply;
6947 break;
6948 } else if (reply != NO_ERROR) {
6949 *(int *)pReplyData = reply;
6950 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 }
6952 mCblk->serverIndex += size;
6953 }
6954 mCblk->serverIndex = 0;
6955 mCblk->clientIndex = 0;
6956 return status;
6957 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006958 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 return enable();
6960 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006961 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962 return disable();
6963 }
6964
6965 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6966}
6967
Eric Laurent59255e42011-07-27 19:49:51 -07006968void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969{
Steve Block3856b092011-10-20 11:56:00 +01006970 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971
6972 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006973 mEnabled = enabled;
6974
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 if (signal && mEffectClient != 0) {
6976 mEffectClient->controlStatusChanged(hasControl);
6977 }
6978}
6979
Eric Laurent25f43952010-07-28 05:40:18 -07006980void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6981 uint32_t cmdSize,
6982 void *pCmdData,
6983 uint32_t replySize,
6984 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985{
6986 if (mEffectClient != 0) {
6987 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6988 }
6989}
6990
6991
6992
6993void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6994{
6995 if (mEffectClient != 0) {
6996 mEffectClient->enableStatusChanged(enabled);
6997 }
6998}
6999
7000status_t AudioFlinger::EffectHandle::onTransact(
7001 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7002{
7003 return BnEffect::onTransact(code, data, reply, flags);
7004}
7005
7006
7007void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7008{
Glenn Kastena0d68332012-01-27 16:47:15 -08007009 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010
7011 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten44deb052012-02-05 18:09:08 -08007012 (mClient == 0) ? getpid_cached : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 mPriority,
7014 mHasControl,
7015 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007016 mCblk ? mCblk->clientIndex : 0,
7017 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 );
7019
7020 if (locked) {
7021 mCblk->lock.unlock();
7022 }
7023}
7024
7025#undef LOG_TAG
7026#define LOG_TAG "AudioFlinger::EffectChain"
7027
7028AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7029 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007030 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007031 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7032 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007033{
Dima Zavinfce7a472011-04-19 22:30:36 -07007034 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007035 sp<ThreadBase> thread = mThread.promote();
7036 if (thread == 0) {
7037 return;
7038 }
7039 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7040 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041}
7042
7043AudioFlinger::EffectChain::~EffectChain()
7044{
7045 if (mOwnInBuffer) {
7046 delete mInBuffer;
7047 }
7048
7049}
7050
Eric Laurent59255e42011-07-27 19:49:51 -07007051// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007052sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007054 size_t size = mEffects.size();
7055
7056 for (size_t i = 0; i < size; i++) {
7057 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007058 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007059 }
7060 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007061 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007062}
7063
Eric Laurent59255e42011-07-27 19:49:51 -07007064// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007065sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007066{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 size_t size = mEffects.size();
7068
7069 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007070 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7071 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007072 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 }
7074 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007075 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076}
7077
Eric Laurent59255e42011-07-27 19:49:51 -07007078// getEffectFromType_l() must be called with ThreadBase::mLock held
7079sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7080 const effect_uuid_t *type)
7081{
Eric Laurent59255e42011-07-27 19:49:51 -07007082 size_t size = mEffects.size();
7083
7084 for (size_t i = 0; i < size; i++) {
7085 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007086 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007087 }
7088 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007089 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007090}
7091
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092// Must be called with EffectChain::mLock locked
7093void AudioFlinger::EffectChain::process_l()
7094{
Eric Laurentdac69112010-09-28 14:09:57 -07007095 sp<ThreadBase> thread = mThread.promote();
7096 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007097 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007098 return;
7099 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007100 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7101 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007102 // always process effects unless no more tracks are on the session and the effect tail
7103 // has been rendered
7104 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007105 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007106 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007107
Eric Laurent544fe9b2011-11-11 15:42:52 -08007108 if (!tracksOnSession && mTailBufferCount == 0) {
7109 doProcess = false;
7110 }
7111
7112 if (activeTrackCnt() == 0) {
7113 // if no track is active and the effect tail has not been rendered,
7114 // the input buffer must be cleared here as the mixer process will not do it
7115 if (tracksOnSession || mTailBufferCount > 0) {
7116 size_t numSamples = thread->frameCount() * thread->channelCount();
7117 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7118 if (mTailBufferCount > 0) {
7119 mTailBufferCount--;
7120 }
7121 }
7122 }
Eric Laurentdac69112010-09-28 14:09:57 -07007123 }
7124
Mathias Agopian65ab4712010-07-14 17:59:35 -07007125 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007126 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007127 for (size_t i = 0; i < size; i++) {
7128 mEffects[i]->process();
7129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130 }
7131 for (size_t i = 0; i < size; i++) {
7132 mEffects[i]->updateState();
7133 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134}
7135
Eric Laurentcab11242010-07-15 12:50:15 -07007136// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007137status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007138{
7139 effect_descriptor_t desc = effect->desc();
7140 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7141
7142 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007143 effect->setChain(this);
7144 sp<ThreadBase> thread = mThread.promote();
7145 if (thread == 0) {
7146 return NO_INIT;
7147 }
7148 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149
7150 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7151 // Auxiliary effects are inserted at the beginning of mEffects vector as
7152 // they are processed first and accumulated in chain input buffer
7153 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007154
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155 // the input buffer for auxiliary effect contains mono samples in
7156 // 32 bit format. This is to avoid saturation in AudoMixer
7157 // accumulation stage. Saturation is done in EffectModule::process() before
7158 // calling the process in effect engine
7159 size_t numSamples = thread->frameCount();
7160 int32_t *buffer = new int32_t[numSamples];
7161 memset(buffer, 0, numSamples * sizeof(int32_t));
7162 effect->setInBuffer((int16_t *)buffer);
7163 // auxiliary effects output samples to chain input buffer for further processing
7164 // by insert effects
7165 effect->setOutBuffer(mInBuffer);
7166 } else {
7167 // Insert effects are inserted at the end of mEffects vector as they are processed
7168 // after track and auxiliary effects.
7169 // Insert effect order as a function of indicated preference:
7170 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7171 // another effect is present
7172 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7173 // last effect claiming first position
7174 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7175 // first effect claiming last position
7176 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7177 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7178 // already present
7179
7180 int size = (int)mEffects.size();
7181 int idx_insert = size;
7182 int idx_insert_first = -1;
7183 int idx_insert_last = -1;
7184
7185 for (int i = 0; i < size; i++) {
7186 effect_descriptor_t d = mEffects[i]->desc();
7187 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7188 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7189 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7190 // check invalid effect chaining combinations
7191 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7192 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007193 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007194 return INVALID_OPERATION;
7195 }
7196 // remember position of first insert effect and by default
7197 // select this as insert position for new effect
7198 if (idx_insert == size) {
7199 idx_insert = i;
7200 }
7201 // remember position of last insert effect claiming
7202 // first position
7203 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7204 idx_insert_first = i;
7205 }
7206 // remember position of first insert effect claiming
7207 // last position
7208 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7209 idx_insert_last == -1) {
7210 idx_insert_last = i;
7211 }
7212 }
7213 }
7214
7215 // modify idx_insert from first position if needed
7216 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7217 if (idx_insert_last != -1) {
7218 idx_insert = idx_insert_last;
7219 } else {
7220 idx_insert = size;
7221 }
7222 } else {
7223 if (idx_insert_first != -1) {
7224 idx_insert = idx_insert_first + 1;
7225 }
7226 }
7227
7228 // always read samples from chain input buffer
7229 effect->setInBuffer(mInBuffer);
7230
7231 // if last effect in the chain, output samples to chain
7232 // output buffer, otherwise to chain input buffer
7233 if (idx_insert == size) {
7234 if (idx_insert != 0) {
7235 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7236 mEffects[idx_insert-1]->configure();
7237 }
7238 effect->setOutBuffer(mOutBuffer);
7239 } else {
7240 effect->setOutBuffer(mInBuffer);
7241 }
7242 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007243
Steve Block3856b092011-10-20 11:56:00 +01007244 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007245 }
7246 effect->configure();
7247 return NO_ERROR;
7248}
7249
Eric Laurentcab11242010-07-15 12:50:15 -07007250// removeEffect_l() must be called with PlaybackThread::mLock held
7251size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007252{
7253 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254 int size = (int)mEffects.size();
7255 int i;
7256 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7257
7258 for (i = 0; i < size; i++) {
7259 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007260 // calling stop here will remove pre-processing effect from the audio HAL.
7261 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7262 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007263 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7264 mEffects[i]->state() == EffectModule::STOPPING) {
7265 mEffects[i]->stop();
7266 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007267 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7268 delete[] effect->inBuffer();
7269 } else {
7270 if (i == size - 1 && i != 0) {
7271 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7272 mEffects[i - 1]->configure();
7273 }
7274 }
7275 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007276 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007277 break;
7278 }
7279 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280
7281 return mEffects.size();
7282}
7283
Eric Laurentcab11242010-07-15 12:50:15 -07007284// setDevice_l() must be called with PlaybackThread::mLock held
7285void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286{
7287 size_t size = mEffects.size();
7288 for (size_t i = 0; i < size; i++) {
7289 mEffects[i]->setDevice(device);
7290 }
7291}
7292
Eric Laurentcab11242010-07-15 12:50:15 -07007293// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007294void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295{
7296 size_t size = mEffects.size();
7297 for (size_t i = 0; i < size; i++) {
7298 mEffects[i]->setMode(mode);
7299 }
7300}
7301
Eric Laurentcab11242010-07-15 12:50:15 -07007302// setVolume_l() must be called with PlaybackThread::mLock held
7303bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304{
7305 uint32_t newLeft = *left;
7306 uint32_t newRight = *right;
7307 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007308 int ctrlIdx = -1;
7309 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310
Eric Laurentcab11242010-07-15 12:50:15 -07007311 // first update volume controller
7312 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007313 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007314 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7315 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007316 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007317 break;
7318 }
7319 }
7320
7321 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007322 if (hasControl) {
7323 *left = mNewLeftVolume;
7324 *right = mNewRightVolume;
7325 }
7326 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007327 }
7328
7329 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007330 mLeftVolume = newLeft;
7331 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007332
7333 // second get volume update from volume controller
7334 if (ctrlIdx >= 0) {
7335 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007336 mNewLeftVolume = newLeft;
7337 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338 }
7339 // then indicate volume to all other effects in chain.
7340 // Pass altered volume to effects before volume controller
7341 // and requested volume to effects after controller
7342 uint32_t lVol = newLeft;
7343 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007344
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007346 if ((int)i == ctrlIdx) continue;
7347 // this also works for ctrlIdx == -1 when there is no volume controller
7348 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349 lVol = *left;
7350 rVol = *right;
7351 }
7352 mEffects[i]->setVolume(&lVol, &rVol, false);
7353 }
7354 *left = newLeft;
7355 *right = newRight;
7356
7357 return hasControl;
7358}
7359
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7361{
7362 const size_t SIZE = 256;
7363 char buffer[SIZE];
7364 String8 result;
7365
7366 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7367 result.append(buffer);
7368
7369 bool locked = tryLock(mLock);
7370 // failed to lock - AudioFlinger is probably deadlocked
7371 if (!locked) {
7372 result.append("\tCould not lock mutex:\n");
7373 }
7374
Eric Laurentcab11242010-07-15 12:50:15 -07007375 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7376 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 mEffects.size(),
7378 (uint32_t)mInBuffer,
7379 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380 mActiveTrackCnt);
7381 result.append(buffer);
7382 write(fd, result.string(), result.size());
7383
7384 for (size_t i = 0; i < mEffects.size(); ++i) {
7385 sp<EffectModule> effect = mEffects[i];
7386 if (effect != 0) {
7387 effect->dump(fd, args);
7388 }
7389 }
7390
7391 if (locked) {
7392 mLock.unlock();
7393 }
7394
7395 return NO_ERROR;
7396}
7397
Eric Laurent59255e42011-07-27 19:49:51 -07007398// must be called with ThreadBase::mLock held
7399void AudioFlinger::EffectChain::setEffectSuspended_l(
7400 const effect_uuid_t *type, bool suspend)
7401{
7402 sp<SuspendedEffectDesc> desc;
7403 // use effect type UUID timelow as key as there is no real risk of identical
7404 // timeLow fields among effect type UUIDs.
7405 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7406 if (suspend) {
7407 if (index >= 0) {
7408 desc = mSuspendedEffects.valueAt(index);
7409 } else {
7410 desc = new SuspendedEffectDesc();
7411 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7412 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007413 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007414 }
7415 if (desc->mRefCount++ == 0) {
7416 sp<EffectModule> effect = getEffectIfEnabled(type);
7417 if (effect != 0) {
7418 desc->mEffect = effect;
7419 effect->setSuspended(true);
7420 effect->setEnabled(false);
7421 }
7422 }
7423 } else {
7424 if (index < 0) {
7425 return;
7426 }
7427 desc = mSuspendedEffects.valueAt(index);
7428 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007429 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007430 desc->mRefCount = 1;
7431 }
7432 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007433 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007434 if (desc->mEffect != 0) {
7435 sp<EffectModule> effect = desc->mEffect.promote();
7436 if (effect != 0) {
7437 effect->setSuspended(false);
7438 sp<EffectHandle> handle = effect->controlHandle();
7439 if (handle != 0) {
7440 effect->setEnabled(handle->enabled());
7441 }
7442 }
7443 desc->mEffect.clear();
7444 }
7445 mSuspendedEffects.removeItemsAt(index);
7446 }
7447 }
7448}
7449
7450// must be called with ThreadBase::mLock held
7451void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7452{
7453 sp<SuspendedEffectDesc> desc;
7454
7455 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7456 if (suspend) {
7457 if (index >= 0) {
7458 desc = mSuspendedEffects.valueAt(index);
7459 } else {
7460 desc = new SuspendedEffectDesc();
7461 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007462 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007463 }
7464 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007465 Vector< sp<EffectModule> > effects;
7466 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007467 for (size_t i = 0; i < effects.size(); i++) {
7468 setEffectSuspended_l(&effects[i]->desc().type, true);
7469 }
7470 }
7471 } else {
7472 if (index < 0) {
7473 return;
7474 }
7475 desc = mSuspendedEffects.valueAt(index);
7476 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007477 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007478 desc->mRefCount = 1;
7479 }
7480 if (--desc->mRefCount == 0) {
7481 Vector<const effect_uuid_t *> types;
7482 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7483 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7484 continue;
7485 }
7486 types.add(&mSuspendedEffects.valueAt(i)->mType);
7487 }
7488 for (size_t i = 0; i < types.size(); i++) {
7489 setEffectSuspended_l(types[i], false);
7490 }
Steve Block3856b092011-10-20 11:56:00 +01007491 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007492 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7493 }
7494 }
7495}
7496
Eric Laurent6bffdb82011-09-23 08:40:41 -07007497
7498// The volume effect is used for automated tests only
7499#ifndef OPENSL_ES_H_
7500static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7501 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7502const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7503#endif //OPENSL_ES_H_
7504
Eric Laurentdb7c0792011-08-10 10:37:50 -07007505bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7506{
7507 // auxiliary effects and visualizer are never suspended on output mix
7508 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7509 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007510 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7511 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007512 return false;
7513 }
7514 return true;
7515}
7516
Glenn Kastend0539712012-01-30 12:56:03 -08007517void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007518{
Glenn Kastend0539712012-01-30 12:56:03 -08007519 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007520 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007521 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7522 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007523 }
Eric Laurent59255e42011-07-27 19:49:51 -07007524 }
Eric Laurent59255e42011-07-27 19:49:51 -07007525}
7526
7527sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7528 const effect_uuid_t *type)
7529{
Glenn Kasten090f0192012-01-30 13:00:02 -08007530 sp<EffectModule> effect = getEffectFromType_l(type);
7531 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007532}
7533
7534void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7535 bool enabled)
7536{
7537 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7538 if (enabled) {
7539 if (index < 0) {
7540 // if the effect is not suspend check if all effects are suspended
7541 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7542 if (index < 0) {
7543 return;
7544 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007545 if (!isEffectEligibleForSuspend(effect->desc())) {
7546 return;
7547 }
Eric Laurent59255e42011-07-27 19:49:51 -07007548 setEffectSuspended_l(&effect->desc().type, enabled);
7549 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007550 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007551 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007552 return;
7553 }
Eric Laurent59255e42011-07-27 19:49:51 -07007554 }
Steve Block3856b092011-10-20 11:56:00 +01007555 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007556 effect->desc().type.timeLow);
7557 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7558 // if effect is requested to suspended but was not yet enabled, supend it now.
7559 if (desc->mEffect == 0) {
7560 desc->mEffect = effect;
7561 effect->setEnabled(false);
7562 effect->setSuspended(true);
7563 }
7564 } else {
7565 if (index < 0) {
7566 return;
7567 }
Steve Block3856b092011-10-20 11:56:00 +01007568 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007569 effect->desc().type.timeLow);
7570 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7571 desc->mEffect.clear();
7572 effect->setSuspended(false);
7573 }
7574}
7575
Mathias Agopian65ab4712010-07-14 17:59:35 -07007576#undef LOG_TAG
7577#define LOG_TAG "AudioFlinger"
7578
7579// ----------------------------------------------------------------------------
7580
7581status_t AudioFlinger::onTransact(
7582 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7583{
7584 return BnAudioFlinger::onTransact(code, data, reply, flags);
7585}
7586
Mathias Agopian65ab4712010-07-14 17:59:35 -07007587}; // namespace android