blob: 4cf570cf06aa4b09f5f546d208c3f2faa1229b16 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
Gloria Wang9ee159b2011-02-24 14:51:45 -080040#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080041#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080073static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070074
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000107 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000114 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800120 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
121 if (service == NULL) {
122 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000139 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800152static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800163 mPrimaryHardwareDev(NULL),
164 mHardwareStatus(AUDIO_HW_IDLE), // see also onFirstRef()
165 mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
166 mMode(AUDIO_MODE_INVALID),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
Dima Zavin799a70e2011-04-18 16:57:27 -0700188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
Steve Blockdf64d152012-01-04 20:05:49 +0000193 ALOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
Steve Block29357bc2012-01-06 19:20:56 +0000201 ALOGE("Primary audio interface not found");
Dima Zavin799a70e2011-04-18 16:57:27 -0700202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
248}
249
Dima Zavin799a70e2011-04-18 16:57:27 -0700250audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
251{
252 /* first matching HW device is returned */
253 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
254 audio_hw_device_t *dev = mAudioHwDevs[i];
255 if ((dev->get_supported_devices(dev) & devices) == devices)
256 return dev;
257 }
258 return NULL;
259}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700260
261status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
262{
263 const size_t SIZE = 256;
264 char buffer[SIZE];
265 String8 result;
266
267 result.append("Clients:\n");
268 for (size_t i = 0; i < mClients.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -0800269 sp<Client> client = mClients.valueAt(i).promote();
270 if (client != 0) {
271 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
272 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700273 }
274 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700275
276 result.append("Global session refs:\n");
277 result.append(" session pid cnt\n");
278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
279 AudioSessionRef *r = mAudioSessionRefs[i];
280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
281 result.append(buffer);
282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 write(fd, result.string(), result.size());
284 return NO_ERROR;
285}
286
287
288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800293 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700294
295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
296 result.append(buffer);
297 write(fd, result.string(), result.size());
298 return NO_ERROR;
299}
300
301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306 snprintf(buffer, SIZE, "Permission Denial: "
307 "can't dump AudioFlinger from pid=%d, uid=%d\n",
308 IPCThreadState::self()->getCallingPid(),
309 IPCThreadState::self()->getCallingUid());
310 result.append(buffer);
311 write(fd, result.string(), result.size());
312 return NO_ERROR;
313}
314
315static bool tryLock(Mutex& mutex)
316{
317 bool locked = false;
318 for (int i = 0; i < kDumpLockRetries; ++i) {
319 if (mutex.tryLock() == NO_ERROR) {
320 locked = true;
321 break;
322 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800323 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700324 }
325 return locked;
326}
327
328status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
329{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800330 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700331 dumpPermissionDenial(fd, args);
332 } else {
333 // get state of hardware lock
334 bool hardwareLocked = tryLock(mHardwareLock);
335 if (!hardwareLocked) {
336 String8 result(kHardwareLockedString);
337 write(fd, result.string(), result.size());
338 } else {
339 mHardwareLock.unlock();
340 }
341
342 bool locked = tryLock(mLock);
343
344 // failed to lock - AudioFlinger is probably deadlocked
345 if (!locked) {
346 String8 result(kDeadlockedString);
347 write(fd, result.string(), result.size());
348 }
349
350 dumpClients(fd, args);
351 dumpInternals(fd, args);
352
353 // dump playback threads
354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
355 mPlaybackThreads.valueAt(i)->dump(fd, args);
356 }
357
358 // dump record threads
359 for (size_t i = 0; i < mRecordThreads.size(); i++) {
360 mRecordThreads.valueAt(i)->dump(fd, args);
361 }
362
Dima Zavin799a70e2011-04-18 16:57:27 -0700363 // dump all hardware devs
364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
365 audio_hw_device_t *dev = mAudioHwDevs[i];
366 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 if (locked) mLock.unlock();
369 }
370 return NO_ERROR;
371}
372
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800373sp<AudioFlinger::Client> AudioFlinger::registerPid_l(pid_t pid)
374{
375 // If pid is already in the mClients wp<> map, then use that entry
376 // (for which promote() is always != 0), otherwise create a new entry and Client.
377 sp<Client> client = mClients.valueFor(pid).promote();
378 if (client == 0) {
379 client = new Client(this, pid);
380 mClients.add(pid, client);
381 }
382
383 return client;
384}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385
386// IAudioFlinger interface
387
388
389sp<IAudioTrack> AudioFlinger::createTrack(
390 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800391 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -0800393 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700394 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700395 int frameCount,
396 uint32_t flags,
397 const sp<IMemory>& sharedBuffer,
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800398 audio_io_handle_t output,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399 int *sessionId,
400 status_t *status)
401{
402 sp<PlaybackThread::Track> track;
403 sp<TrackHandle> trackHandle;
404 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 status_t lStatus;
406 int lSessionId;
407
Glenn Kasten263709e2012-01-06 08:40:01 -0800408 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
409 // but if someone uses binder directly they could bypass that and cause us to crash
410 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000411 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 lStatus = BAD_VALUE;
413 goto Exit;
414 }
415
416 {
417 Mutex::Autolock _l(mLock);
418 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700419 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000421 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422 lStatus = BAD_VALUE;
423 goto Exit;
424 }
425
Glenn Kasten98ec94c2012-01-25 14:28:29 -0800426 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700427
Steve Block3856b092011-10-20 11:56:00 +0100428 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700429 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700430 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700431 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
432 if (mPlaybackThreads.keyAt(i) != output) {
433 // prevent same audio session on different output threads
434 uint32_t sessions = t->hasAudioSession(*sessionId);
435 if (sessions & PlaybackThread::TRACK_SESSION) {
Steve Block29357bc2012-01-06 19:20:56 +0000436 ALOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700437 lStatus = BAD_VALUE;
438 goto Exit;
439 }
440 // check if an effect with same session ID is waiting for a track to be created
441 if (sessions & PlaybackThread::EFFECT_SESSION) {
442 effectThread = t.get();
443 }
Eric Laurentde070132010-07-13 04:45:46 -0700444 }
445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700446 lSessionId = *sessionId;
447 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700448 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700449 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450 if (sessionId != NULL) {
451 *sessionId = lSessionId;
452 }
453 }
Steve Block3856b092011-10-20 11:56:00 +0100454 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700455
456 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700457 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700458
459 // move effect chain to this output thread if an effect on same session was waiting
460 // for a track to be created
461 if (lStatus == NO_ERROR && effectThread != NULL) {
462 Mutex::Autolock _dl(thread->mLock);
463 Mutex::Autolock _sl(effectThread->mLock);
464 moveEffectChain_l(lSessionId, effectThread, thread, true);
465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700466 }
467 if (lStatus == NO_ERROR) {
468 trackHandle = new TrackHandle(track);
469 } else {
470 // remove local strong reference to Client before deleting the Track so that the Client
471 // destructor is called by the TrackBase destructor with mLock held
472 client.clear();
473 track.clear();
474 }
475
476Exit:
477 if(status) {
478 *status = lStatus;
479 }
480 return trackHandle;
481}
482
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800483uint32_t AudioFlinger::sampleRate(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700484{
485 Mutex::Autolock _l(mLock);
486 PlaybackThread *thread = checkPlaybackThread_l(output);
487 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000488 ALOGW("sampleRate() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700489 return 0;
490 }
491 return thread->sampleRate();
492}
493
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800494int AudioFlinger::channelCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700495{
496 Mutex::Autolock _l(mLock);
497 PlaybackThread *thread = checkPlaybackThread_l(output);
498 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000499 ALOGW("channelCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500 return 0;
501 }
502 return thread->channelCount();
503}
504
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800505audio_format_t AudioFlinger::format(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700506{
507 Mutex::Autolock _l(mLock);
508 PlaybackThread *thread = checkPlaybackThread_l(output);
509 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000510 ALOGW("format() unknown thread %d", output);
Glenn Kasten58f30212012-01-12 12:27:51 -0800511 return AUDIO_FORMAT_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700512 }
513 return thread->format();
514}
515
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800516size_t AudioFlinger::frameCount(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700517{
518 Mutex::Autolock _l(mLock);
519 PlaybackThread *thread = checkPlaybackThread_l(output);
520 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000521 ALOGW("frameCount() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700522 return 0;
523 }
524 return thread->frameCount();
525}
526
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800527uint32_t AudioFlinger::latency(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528{
529 Mutex::Autolock _l(mLock);
530 PlaybackThread *thread = checkPlaybackThread_l(output);
531 if (thread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000532 ALOGW("latency() unknown thread %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700533 return 0;
534 }
535 return thread->latency();
536}
537
538status_t AudioFlinger::setMasterVolume(float value)
539{
Eric Laurenta1884f92011-08-23 08:25:03 -0700540 status_t ret = initCheck();
541 if (ret != NO_ERROR) {
542 return ret;
543 }
544
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 // check calling permissions
546 if (!settingsAllowed()) {
547 return PERMISSION_DENIED;
548 }
549
550 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800551 { // scope for the lock
552 AutoMutex lock(mHardwareLock);
553 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700554 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800555 value = 1.0f;
556 }
557 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559
Eric Laurent93575202011-01-18 18:39:02 -0800560 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 mMasterVolume = value;
562 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
563 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
564
565 return NO_ERROR;
566}
567
Glenn Kastenf78aee72012-01-04 11:00:47 -0800568status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
Eric Laurenta1884f92011-08-23 08:25:03 -0700570 status_t ret = initCheck();
571 if (ret != NO_ERROR) {
572 return ret;
573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574
575 // check calling permissions
576 if (!settingsAllowed()) {
577 return PERMISSION_DENIED;
578 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800579 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000580 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 return BAD_VALUE;
582 }
583
584 { // scope for the lock
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700587 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 mHardwareStatus = AUDIO_HW_IDLE;
589 }
590
591 if (NO_ERROR == ret) {
592 Mutex::Autolock _l(mLock);
593 mMode = mode;
594 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
595 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 }
597
598 return ret;
599}
600
601status_t AudioFlinger::setMicMute(bool state)
602{
Eric Laurenta1884f92011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return ret;
606 }
607
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 // check calling permissions
609 if (!settingsAllowed()) {
610 return PERMISSION_DENIED;
611 }
612
613 AutoMutex lock(mHardwareLock);
614 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700615 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616 mHardwareStatus = AUDIO_HW_IDLE;
617 return ret;
618}
619
620bool AudioFlinger::getMicMute() const
621{
Eric Laurenta1884f92011-08-23 08:25:03 -0700622 status_t ret = initCheck();
623 if (ret != NO_ERROR) {
624 return false;
625 }
626
Dima Zavinfce7a472011-04-19 22:30:36 -0700627 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700629 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 mHardwareStatus = AUDIO_HW_IDLE;
631 return state;
632}
633
634status_t AudioFlinger::setMasterMute(bool muted)
635{
636 // check calling permissions
637 if (!settingsAllowed()) {
638 return PERMISSION_DENIED;
639 }
640
Eric Laurent93575202011-01-18 18:39:02 -0800641 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642 mMasterMute = muted;
643 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
644 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
645
646 return NO_ERROR;
647}
648
649float AudioFlinger::masterVolume() const
650{
Glenn Kasten98067102011-12-13 11:47:54 -0800651 Mutex::Autolock _l(mLock);
652 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653}
654
655bool AudioFlinger::masterMute() const
656{
Glenn Kasten98067102011-12-13 11:47:54 -0800657 Mutex::Autolock _l(mLock);
658 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659}
660
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800661status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value,
662 audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700663{
664 // check calling permissions
665 if (!settingsAllowed()) {
666 return PERMISSION_DENIED;
667 }
668
Glenn Kasten263709e2012-01-06 08:40:01 -0800669 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000670 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700671 return BAD_VALUE;
672 }
673
674 AutoMutex lock(mLock);
675 PlaybackThread *thread = NULL;
676 if (output) {
677 thread = checkPlaybackThread_l(output);
678 if (thread == NULL) {
679 return BAD_VALUE;
680 }
681 }
682
683 mStreamTypes[stream].volume = value;
684
685 if (thread == NULL) {
686 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
687 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
688 }
689 } else {
690 thread->setStreamVolume(stream, value);
691 }
692
693 return NO_ERROR;
694}
695
Glenn Kastenfff6d712012-01-12 16:38:12 -0800696status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697{
698 // check calling permissions
699 if (!settingsAllowed()) {
700 return PERMISSION_DENIED;
701 }
702
Glenn Kasten263709e2012-01-06 08:40:01 -0800703 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700704 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000705 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 return BAD_VALUE;
707 }
708
Eric Laurent93575202011-01-18 18:39:02 -0800709 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 mStreamTypes[stream].mute = muted;
711 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
712 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
713
714 return NO_ERROR;
715}
716
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800717float AudioFlinger::streamVolume(audio_stream_type_t stream, audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718{
Glenn Kasten263709e2012-01-06 08:40:01 -0800719 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720 return 0.0f;
721 }
722
723 AutoMutex lock(mLock);
724 float volume;
725 if (output) {
726 PlaybackThread *thread = checkPlaybackThread_l(output);
727 if (thread == NULL) {
728 return 0.0f;
729 }
730 volume = thread->streamVolume(stream);
731 } else {
Glenn Kasten6637baa2012-01-09 09:40:36 -0800732 volume = streamVolume_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700733 }
734
735 return volume;
736}
737
Glenn Kastenfff6d712012-01-12 16:38:12 -0800738bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739{
Glenn Kasten263709e2012-01-06 08:40:01 -0800740 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700741 return true;
742 }
743
Glenn Kasten6637baa2012-01-09 09:40:36 -0800744 AutoMutex lock(mLock);
745 return streamMute_l(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746}
747
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800748status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749{
750 status_t result;
751
Steve Block3856b092011-10-20 11:56:00 +0100752 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
754 // check calling permissions
755 if (!settingsAllowed()) {
756 return PERMISSION_DENIED;
757 }
758
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759 // ioHandle == 0 means the parameters are global to the audio hardware interface
760 if (ioHandle == 0) {
761 AutoMutex lock(mHardwareLock);
762 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700763 status_t final_result = NO_ERROR;
764 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
765 audio_hw_device_t *dev = mAudioHwDevs[i];
766 result = dev->set_parameters(dev, keyValuePairs.string());
767 final_result = result ?: final_result;
768 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700769 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700770 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
771 AudioParameter param = AudioParameter(keyValuePairs);
772 String8 value;
773 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
774 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700775 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
776 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700777 for (size_t i = 0; i < mRecordThreads.size(); i++) {
778 sp<RecordThread> thread = mRecordThreads.valueAt(i);
779 RecordThread::RecordTrack *track = thread->track();
780 if (track != NULL) {
781 audio_devices_t device = (audio_devices_t)(
782 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700783 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700784 thread->setEffectSuspended(FX_IID_AEC,
785 suspend,
786 track->sessionId());
787 thread->setEffectSuspended(FX_IID_NS,
788 suspend,
789 track->sessionId());
790 }
791 }
Eric Laurentbee53372011-08-29 12:42:48 -0700792 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700793 }
794 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700795 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
797
798 // hold a strong ref on thread in case closeOutput() or closeInput() is called
799 // and the thread is exited once the lock is released
800 sp<ThreadBase> thread;
801 {
802 Mutex::Autolock _l(mLock);
803 thread = checkPlaybackThread_l(ioHandle);
804 if (thread == NULL) {
805 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800806 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700807 // indicate output device change to all input threads for pre processing
808 AudioParameter param = AudioParameter(keyValuePairs);
809 int value;
810 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
811 for (size_t i = 0; i < mRecordThreads.size(); i++) {
812 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
813 }
814 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700815 }
816 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800817 if (thread != 0) {
818 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700819 }
820 return BAD_VALUE;
821}
822
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800823String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700824{
Steve Block3856b092011-10-20 11:56:00 +0100825// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
827
828 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700829 String8 out_s8;
830
Dima Zavin799a70e2011-04-18 16:57:27 -0700831 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
832 audio_hw_device_t *dev = mAudioHwDevs[i];
833 char *s = dev->get_parameters(dev, keys.string());
834 out_s8 += String8(s);
835 free(s);
836 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700837 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700838 }
839
840 Mutex::Autolock _l(mLock);
841
842 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
843 if (playbackThread != NULL) {
844 return playbackThread->getParameters(keys);
845 }
846 RecordThread *recordThread = checkRecordThread_l(ioHandle);
847 if (recordThread != NULL) {
848 return recordThread->getParameters(keys);
849 }
850 return String8("");
851}
852
Glenn Kastenf587ba52012-01-26 16:25:10 -0800853size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700854{
Eric Laurenta1884f92011-08-23 08:25:03 -0700855 status_t ret = initCheck();
856 if (ret != NO_ERROR) {
857 return 0;
858 }
859
Dima Zavin799a70e2011-04-18 16:57:27 -0700860 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700861}
862
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800863unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864{
865 if (ioHandle == 0) {
866 return 0;
867 }
868
869 Mutex::Autolock _l(mLock);
870
871 RecordThread *recordThread = checkRecordThread_l(ioHandle);
872 if (recordThread != NULL) {
873 return recordThread->getInputFramesLost();
874 }
875 return 0;
876}
877
878status_t AudioFlinger::setVoiceVolume(float value)
879{
Eric Laurenta1884f92011-08-23 08:25:03 -0700880 status_t ret = initCheck();
881 if (ret != NO_ERROR) {
882 return ret;
883 }
884
Mathias Agopian65ab4712010-07-14 17:59:35 -0700885 // check calling permissions
886 if (!settingsAllowed()) {
887 return PERMISSION_DENIED;
888 }
889
890 AutoMutex lock(mHardwareLock);
891 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700892 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893 mHardwareStatus = AUDIO_HW_IDLE;
894
895 return ret;
896}
897
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800898status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
899 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700900{
901 status_t status;
902
903 Mutex::Autolock _l(mLock);
904
905 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
906 if (playbackThread != NULL) {
907 return playbackThread->getRenderPosition(halFrames, dspFrames);
908 }
909
910 return BAD_VALUE;
911}
912
913void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
914{
915
916 Mutex::Autolock _l(mLock);
917
Glenn Kastenbb001922012-02-03 11:10:26 -0800918 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919 if (mNotificationClients.indexOfKey(pid) < 0) {
920 sp<NotificationClient> notificationClient = new NotificationClient(this,
921 client,
922 pid);
Steve Block3856b092011-10-20 11:56:00 +0100923 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700924
925 mNotificationClients.add(pid, notificationClient);
926
927 sp<IBinder> binder = client->asBinder();
928 binder->linkToDeath(notificationClient);
929
930 // the config change is always sent from playback or record threads to avoid deadlock
931 // with AudioSystem::gLock
932 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
933 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
934 }
935
936 for (size_t i = 0; i < mRecordThreads.size(); i++) {
937 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
938 }
939 }
940}
941
942void AudioFlinger::removeNotificationClient(pid_t pid)
943{
944 Mutex::Autolock _l(mLock);
945
946 int index = mNotificationClients.indexOfKey(pid);
947 if (index >= 0) {
948 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700950 mNotificationClients.removeItem(pid);
951 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700952
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 int num = mAudioSessionRefs.size();
955 bool removed = false;
956 for (int i = 0; i< num; i++) {
957 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100958 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700959 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100960 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700961 mAudioSessionRefs.removeAt(i);
962 delete ref;
963 removed = true;
964 i--;
965 num--;
966 }
967 }
968 if (removed) {
969 purgeStaleEffects_l();
970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700971}
972
973// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800974void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975{
976 size_t size = mNotificationClients.size();
977 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800978 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
979 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 }
981}
982
983// removeClient_l() must be called with AudioFlinger::mLock held
984void AudioFlinger::removeClient_l(pid_t pid)
985{
Steve Block3856b092011-10-20 11:56:00 +0100986 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 mClients.removeItem(pid);
988}
989
990
991// ----------------------------------------------------------------------------
992
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800993AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
994 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800996 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800997 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
998 // mChannelMask
999 mChannelCount(0),
1000 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1001 mParamStatus(NO_ERROR),
1002 mStandby(false), mId(id), mExiting(false),
1003 mDevice(device),
1004 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005{
1006}
1007
1008AudioFlinger::ThreadBase::~ThreadBase()
1009{
1010 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001011 // do not lock the mutex in destructor
1012 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001013 if (mPowerManager != 0) {
1014 sp<IBinder> binder = mPowerManager->asBinder();
1015 binder->unlinkToDeath(mDeathRecipient);
1016 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017}
1018
1019void AudioFlinger::ThreadBase::exit()
1020{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001021 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022 // destroyed in the middle of requestExitAndWait()
1023 sp <ThreadBase> strongMe = this;
1024
Steve Block3856b092011-10-20 11:56:00 +01001025 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001026 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001027 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001028 mExiting = true;
1029 requestExit();
1030 mWaitWorkCV.signal();
1031 }
1032 requestExitAndWait();
1033}
1034
Mathias Agopian65ab4712010-07-14 17:59:35 -07001035status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1036{
1037 status_t status;
1038
Steve Block3856b092011-10-20 11:56:00 +01001039 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040 Mutex::Autolock _l(mLock);
1041
1042 mNewParameters.add(keyValuePairs);
1043 mWaitWorkCV.signal();
1044 // wait condition with timeout in case the thread loop has exited
1045 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001046 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 status = mParamStatus;
1048 mWaitWorkCV.signal();
1049 } else {
1050 status = TIMED_OUT;
1051 }
1052 return status;
1053}
1054
1055void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1056{
1057 Mutex::Autolock _l(mLock);
1058 sendConfigEvent_l(event, param);
1059}
1060
1061// sendConfigEvent_l() must be called with ThreadBase::mLock held
1062void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1063{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001064 ConfigEvent configEvent;
1065 configEvent.mEvent = event;
1066 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001068 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001069 mWaitWorkCV.signal();
1070}
1071
1072void AudioFlinger::ThreadBase::processConfigEvents()
1073{
1074 mLock.lock();
1075 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001076 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001077 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mConfigEvents.removeAt(0);
1079 // release mLock before locking AudioFlinger mLock: lock order is always
1080 // AudioFlinger then ThreadBase to avoid cross deadlock
1081 mLock.unlock();
1082 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001083 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 mLock.lock();
1086 }
1087 mLock.unlock();
1088}
1089
1090status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1091{
1092 const size_t SIZE = 256;
1093 char buffer[SIZE];
1094 String8 result;
1095
1096 bool locked = tryLock(mLock);
1097 if (!locked) {
1098 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1099 write(fd, buffer, strlen(buffer));
1100 }
1101
1102 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1105 result.append(buffer);
1106 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1109 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001110 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1111 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1113 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001114 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001115 result.append(buffer);
1116
1117 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1118 result.append(buffer);
1119 result.append(" Index Command");
1120 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1121 snprintf(buffer, SIZE, "\n %02d ", i);
1122 result.append(buffer);
1123 result.append(mNewParameters[i]);
1124 }
1125
1126 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1127 result.append(buffer);
1128 snprintf(buffer, SIZE, " Index event param\n");
1129 result.append(buffer);
1130 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001131 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001132 result.append(buffer);
1133 }
1134 result.append("\n");
1135
1136 write(fd, result.string(), result.size());
1137
1138 if (locked) {
1139 mLock.unlock();
1140 }
1141 return NO_ERROR;
1142}
1143
Eric Laurent1d2bff02011-07-24 17:49:51 -07001144status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1145{
1146 const size_t SIZE = 256;
1147 char buffer[SIZE];
1148 String8 result;
1149
1150 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1151 write(fd, buffer, strlen(buffer));
1152
1153 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1154 sp<EffectChain> chain = mEffectChains[i];
1155 if (chain != 0) {
1156 chain->dump(fd, args);
1157 }
1158 }
1159 return NO_ERROR;
1160}
1161
Eric Laurentfeb0db62011-07-22 09:04:31 -07001162void AudioFlinger::ThreadBase::acquireWakeLock()
1163{
1164 Mutex::Autolock _l(mLock);
1165 acquireWakeLock_l();
1166}
1167
1168void AudioFlinger::ThreadBase::acquireWakeLock_l()
1169{
1170 if (mPowerManager == 0) {
1171 // use checkService() to avoid blocking if power service is not up yet
1172 sp<IBinder> binder =
1173 defaultServiceManager()->checkService(String16("power"));
1174 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001175 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001176 } else {
1177 mPowerManager = interface_cast<IPowerManager>(binder);
1178 binder->linkToDeath(mDeathRecipient);
1179 }
1180 }
1181 if (mPowerManager != 0) {
1182 sp<IBinder> binder = new BBinder();
1183 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1184 binder,
1185 String16(mName));
1186 if (status == NO_ERROR) {
1187 mWakeLockToken = binder;
1188 }
Steve Block3856b092011-10-20 11:56:00 +01001189 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001190 }
1191}
1192
1193void AudioFlinger::ThreadBase::releaseWakeLock()
1194{
1195 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001196 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001197}
1198
1199void AudioFlinger::ThreadBase::releaseWakeLock_l()
1200{
1201 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001202 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001203 if (mPowerManager != 0) {
1204 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1205 }
1206 mWakeLockToken.clear();
1207 }
1208}
1209
1210void AudioFlinger::ThreadBase::clearPowerManager()
1211{
1212 Mutex::Autolock _l(mLock);
1213 releaseWakeLock_l();
1214 mPowerManager.clear();
1215}
1216
1217void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1218{
1219 sp<ThreadBase> thread = mThread.promote();
1220 if (thread != 0) {
1221 thread->clearPowerManager();
1222 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001223 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001224}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001225
Eric Laurent59255e42011-07-27 19:49:51 -07001226void AudioFlinger::ThreadBase::setEffectSuspended(
1227 const effect_uuid_t *type, bool suspend, int sessionId)
1228{
1229 Mutex::Autolock _l(mLock);
1230 setEffectSuspended_l(type, suspend, sessionId);
1231}
1232
1233void AudioFlinger::ThreadBase::setEffectSuspended_l(
1234 const effect_uuid_t *type, bool suspend, int sessionId)
1235{
Glenn Kasten090f0192012-01-30 13:00:02 -08001236 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001237 if (chain != 0) {
1238 if (type != NULL) {
1239 chain->setEffectSuspended_l(type, suspend);
1240 } else {
1241 chain->setEffectSuspendedAll_l(suspend);
1242 }
1243 }
1244
1245 updateSuspendedSessions_l(type, suspend, sessionId);
1246}
1247
1248void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1249{
1250 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1251 if (index < 0) {
1252 return;
1253 }
1254
1255 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1256 mSuspendedSessions.editValueAt(index);
1257
1258 for (size_t i = 0; i < sessionEffects.size(); i++) {
1259 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1260 for (int j = 0; j < desc->mRefCount; j++) {
1261 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1262 chain->setEffectSuspendedAll_l(true);
1263 } else {
Steve Block3856b092011-10-20 11:56:00 +01001264 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001265 desc->mType.timeLow);
1266 chain->setEffectSuspended_l(&desc->mType, true);
1267 }
1268 }
1269 }
1270}
1271
Eric Laurent59255e42011-07-27 19:49:51 -07001272void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1273 bool suspend,
1274 int sessionId)
1275{
1276 int index = mSuspendedSessions.indexOfKey(sessionId);
1277
1278 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1279
1280 if (suspend) {
1281 if (index >= 0) {
1282 sessionEffects = mSuspendedSessions.editValueAt(index);
1283 } else {
1284 mSuspendedSessions.add(sessionId, sessionEffects);
1285 }
1286 } else {
1287 if (index < 0) {
1288 return;
1289 }
1290 sessionEffects = mSuspendedSessions.editValueAt(index);
1291 }
1292
1293
1294 int key = EffectChain::kKeyForSuspendAll;
1295 if (type != NULL) {
1296 key = type->timeLow;
1297 }
1298 index = sessionEffects.indexOfKey(key);
1299
1300 sp <SuspendedSessionDesc> desc;
1301 if (suspend) {
1302 if (index >= 0) {
1303 desc = sessionEffects.valueAt(index);
1304 } else {
1305 desc = new SuspendedSessionDesc();
1306 if (type != NULL) {
1307 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1308 }
1309 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001310 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001311 }
1312 desc->mRefCount++;
1313 } else {
1314 if (index < 0) {
1315 return;
1316 }
1317 desc = sessionEffects.valueAt(index);
1318 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001320 sessionEffects.removeItemsAt(index);
1321 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001322 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001323 sessionId);
1324 mSuspendedSessions.removeItem(sessionId);
1325 }
1326 }
1327 }
1328 if (!sessionEffects.isEmpty()) {
1329 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1330 }
1331}
1332
1333void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1334 bool enabled,
1335 int sessionId)
1336{
1337 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001338 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1339}
Eric Laurent59255e42011-07-27 19:49:51 -07001340
Eric Laurenta85a74a2011-10-19 11:44:54 -07001341void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1342 bool enabled,
1343 int sessionId)
1344{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001345 if (mType != RECORD) {
1346 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1347 // another session. This gives the priority to well behaved effect control panels
1348 // and applications not using global effects.
1349 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1350 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1351 }
1352 }
Eric Laurent59255e42011-07-27 19:49:51 -07001353
1354 sp<EffectChain> chain = getEffectChain_l(sessionId);
1355 if (chain != 0) {
1356 chain->checkSuspendOnEffectEnabled(effect, enabled);
1357 }
1358}
1359
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360// ----------------------------------------------------------------------------
1361
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001362AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1363 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001364 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001365 uint32_t device,
1366 type_t type)
1367 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001368 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1369 // Assumes constructor is called by AudioFlinger with it's mLock held,
1370 // but it would be safer to explicitly pass initial masterMute as parameter
1371 mMasterMute(audioFlinger->masterMute_l()),
1372 // mStreamTypes[] initialized in constructor body
1373 mOutput(output),
1374 // Assumes constructor is called by AudioFlinger with it's mLock held,
1375 // but it would be safer to explicitly pass initial masterVolume as parameter
1376 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001377 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001379 snprintf(mName, kNameLength, "AudioOut_%d", id);
1380
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 readOutputParameters();
1382
Glenn Kasten263709e2012-01-06 08:40:01 -08001383 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001384 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1385 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1386 stream = (audio_stream_type_t) (stream + 1)) {
Glenn Kasten6637baa2012-01-09 09:40:36 -08001387 mStreamTypes[stream].volume = mAudioFlinger->streamVolume_l(stream);
1388 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001389 // initialized by stream_type_t default constructor
1390 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 }
Glenn Kasten6637baa2012-01-09 09:40:36 -08001392 // mStreamTypes[AUDIO_STREAM_CNT] exists but isn't explicitly initialized here,
1393 // because mAudioFlinger doesn't have one to copy from
Mathias Agopian65ab4712010-07-14 17:59:35 -07001394}
1395
1396AudioFlinger::PlaybackThread::~PlaybackThread()
1397{
1398 delete [] mMixBuffer;
1399}
1400
1401status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1402{
1403 dumpInternals(fd, args);
1404 dumpTracks(fd, args);
1405 dumpEffectChains(fd, args);
1406 return NO_ERROR;
1407}
1408
1409status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1410{
1411 const size_t SIZE = 256;
1412 char buffer[SIZE];
1413 String8 result;
1414
1415 snprintf(buffer, SIZE, "Output thread %p 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 < mTracks.size(); ++i) {
1419 sp<Track> track = mTracks[i];
1420 if (track != 0) {
1421 track->dump(buffer, SIZE);
1422 result.append(buffer);
1423 }
1424 }
1425
1426 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1427 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001428 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 -07001429 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001430 sp<Track> track = mActiveTracks[i].promote();
1431 if (track != 0) {
1432 track->dump(buffer, SIZE);
1433 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434 }
1435 }
1436 write(fd, result.string(), result.size());
1437 return NO_ERROR;
1438}
1439
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1441{
1442 const size_t SIZE = 256;
1443 char buffer[SIZE];
1444 String8 result;
1445
1446 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1455 result.append(buffer);
1456 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1457 result.append(buffer);
1458 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1459 result.append(buffer);
1460 write(fd, result.string(), result.size());
1461
1462 dumpBase(fd, args);
1463
1464 return NO_ERROR;
1465}
1466
1467// Thread virtuals
1468status_t AudioFlinger::PlaybackThread::readyToRun()
1469{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001470 status_t status = initCheck();
1471 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001472 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001473 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001474 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001476 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477}
1478
1479void AudioFlinger::PlaybackThread::onFirstRef()
1480{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001481 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482}
1483
1484// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1485sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1486 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001487 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001489 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001490 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 int frameCount,
1492 const sp<IMemory>& sharedBuffer,
1493 int sessionId,
1494 status_t *status)
1495{
1496 sp<Track> track;
1497 status_t lStatus;
1498
1499 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001500 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1501 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001502 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001503 "for output %p with format %d",
1504 sampleRate, format, channelMask, mOutput, mFormat);
1505 lStatus = BAD_VALUE;
1506 goto Exit;
1507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508 }
1509 } else {
1510 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1511 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001512 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513 lStatus = BAD_VALUE;
1514 goto Exit;
1515 }
1516 }
1517
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001518 lStatus = initCheck();
1519 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001520 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 goto Exit;
1522 }
1523
1524 { // scope for mLock
1525 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001526
1527 // all tracks in same audio session must share the same routing strategy otherwise
1528 // conflicts will happen when tracks are moved from one output to another by audio policy
1529 // manager
1530 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001531 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001532 for (size_t i = 0; i < mTracks.size(); ++i) {
1533 sp<Track> t = mTracks[i];
1534 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001535 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1536 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001537 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001538 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
1542 }
1543 }
1544
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001546 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 if (track->getCblk() == NULL || track->name() < 0) {
1548 lStatus = NO_MEMORY;
1549 goto Exit;
1550 }
1551 mTracks.add(track);
1552
1553 sp<EffectChain> chain = getEffectChain_l(sessionId);
1554 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001555 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001557 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001558 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001560
1561 // invalidate track immediately if the stream type was moved to another thread since
1562 // createTrack() was called by the client process.
1563 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001564 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001565 this, streamType);
1566 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
1569 lStatus = NO_ERROR;
1570
1571Exit:
1572 if(status) {
1573 *status = lStatus;
1574 }
1575 return track;
1576}
1577
1578uint32_t AudioFlinger::PlaybackThread::latency() const
1579{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001580 Mutex::Autolock _l(mLock);
1581 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001582 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001583 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 return 0;
1585 }
1586}
1587
Glenn Kasten6637baa2012-01-09 09:40:36 -08001588void AudioFlinger::PlaybackThread::setMasterVolume(float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001590 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001591 mMasterVolume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592}
1593
Glenn Kasten6637baa2012-01-09 09:40:36 -08001594void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001596 Mutex::Autolock _l(mLock);
1597 setMasterMute_l(muted);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598}
1599
Glenn Kasten6637baa2012-01-09 09:40:36 -08001600void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001602 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603 mStreamTypes[stream].volume = value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604}
1605
Glenn Kasten6637baa2012-01-09 09:40:36 -08001606void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001607{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001608 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 mStreamTypes[stream].mute = muted;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610}
1611
Glenn Kastenfff6d712012-01-12 16:38:12 -08001612float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001613{
Glenn Kasten6637baa2012-01-09 09:40:36 -08001614 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 return mStreamTypes[stream].volume;
1616}
1617
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618// addTrack_l() must be called with ThreadBase::mLock held
1619status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1620{
1621 status_t status = ALREADY_EXISTS;
1622
1623 // set retry count for buffer fill
1624 track->mRetryCount = kMaxTrackStartupRetries;
1625 if (mActiveTracks.indexOf(track) < 0) {
1626 // the track is newly added, make sure it fills up all its
1627 // buffers before playing. This is to ensure the client will
1628 // effectively get the latency it requested.
1629 track->mFillingUpStatus = Track::FS_FILLING;
1630 track->mResetDone = false;
1631 mActiveTracks.add(track);
1632 if (track->mainBuffer() != mMixBuffer) {
1633 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1634 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001635 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001636 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 }
1638 }
1639
1640 status = NO_ERROR;
1641 }
1642
Steve Block3856b092011-10-20 11:56:00 +01001643 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644 mWaitWorkCV.broadcast();
1645
1646 return status;
1647}
1648
1649// destroyTrack_l() must be called with ThreadBase::mLock held
1650void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1651{
1652 track->mState = TrackBase::TERMINATED;
1653 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001654 removeTrack_l(track);
1655 }
1656}
1657
1658void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1659{
1660 mTracks.remove(track);
1661 deleteTrackName_l(track->name());
1662 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1663 if (chain != 0) {
1664 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 }
1666}
1667
1668String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1669{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001670 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001671 char *s;
1672
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001673 Mutex::Autolock _l(mLock);
1674 if (initCheck() != NO_ERROR) {
1675 return out_s8;
1676 }
1677
Dima Zavin799a70e2011-04-18 16:57:27 -07001678 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001679 out_s8 = String8(s);
1680 free(s);
1681 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001682}
1683
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001684// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1686 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001687 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688
Steve Block3856b092011-10-20 11:56:00 +01001689 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690
1691 switch (event) {
1692 case AudioSystem::OUTPUT_OPENED:
1693 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001694 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 desc.samplingRate = mSampleRate;
1696 desc.format = mFormat;
1697 desc.frameCount = mFrameCount;
1698 desc.latency = latency();
1699 param2 = &desc;
1700 break;
1701
1702 case AudioSystem::STREAM_CONFIG_CHANGED:
1703 param2 = &param;
1704 case AudioSystem::OUTPUT_CLOSED:
1705 default:
1706 break;
1707 }
1708 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1709}
1710
1711void AudioFlinger::PlaybackThread::readOutputParameters()
1712{
Dima Zavin799a70e2011-04-18 16:57:27 -07001713 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001714 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1715 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001716 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001717 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001718 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719
1720 // FIXME - Current mixer implementation only supports stereo output: Always
1721 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001722 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723 mMixBuffer = new int16_t[mFrameCount * 2];
1724 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1725
Eric Laurentde070132010-07-13 04:45:46 -07001726 // force reconfiguration of effect chains and engines to take new buffer size and audio
1727 // parameters into account
1728 // Note that mLock is not held when readOutputParameters() is called from the constructor
1729 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1730 // matter.
1731 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1732 Vector< sp<EffectChain> > effectChains = mEffectChains;
1733 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001734 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001735 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736}
1737
1738status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1739{
Glenn Kastena0d68332012-01-27 16:47:15 -08001740 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741 return BAD_VALUE;
1742 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001743 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001744 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 return INVALID_OPERATION;
1746 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001747 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748
Dima Zavin799a70e2011-04-18 16:57:27 -07001749 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750}
1751
Eric Laurent39e94f82010-07-28 01:32:47 -07001752uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753{
1754 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001755 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001757 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 }
1759
1760 for (size_t i = 0; i < mTracks.size(); ++i) {
1761 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001762 if (sessionId == track->sessionId() &&
1763 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001764 result |= TRACK_SESSION;
1765 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 }
1767 }
1768
Eric Laurent39e94f82010-07-28 01:32:47 -07001769 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770}
1771
Eric Laurentde070132010-07-13 04:45:46 -07001772uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1773{
Dima Zavinfce7a472011-04-19 22:30:36 -07001774 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001775 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001776 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1777 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001778 }
1779 for (size_t i = 0; i < mTracks.size(); i++) {
1780 sp<Track> track = mTracks[i];
1781 if (sessionId == track->sessionId() &&
1782 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001783 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001784 }
1785 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001786 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001787}
1788
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789
Glenn Kastenaed850d2012-01-26 09:46:34 -08001790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001791{
1792 Mutex::Autolock _l(mLock);
1793 return mOutput;
1794}
1795
1796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1797{
1798 Mutex::Autolock _l(mLock);
1799 AudioStreamOut *output = mOutput;
1800 mOutput = NULL;
1801 return output;
1802}
1803
1804// this method must always be called either with ThreadBase mLock held or inside the thread loop
1805audio_stream_t* AudioFlinger::PlaybackThread::stream()
1806{
1807 if (mOutput == NULL) {
1808 return NULL;
1809 }
1810 return &mOutput->stream->common;
1811}
1812
Eric Laurent162b40b2011-12-05 09:47:19 -08001813uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1814{
1815 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1816 // decoding and transfer time. So sleeping for half of the latency would likely cause
1817 // underruns
1818 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1819 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1820 } else {
1821 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1822 }
1823}
1824
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825// ----------------------------------------------------------------------------
1826
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001827AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001828 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001829 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001830 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1831 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001832{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 // FIXME - Current mixer implementation only supports stereo output
1834 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001835 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 }
1837}
1838
1839AudioFlinger::MixerThread::~MixerThread()
1840{
1841 delete mAudioMixer;
1842}
1843
1844bool AudioFlinger::MixerThread::threadLoop()
1845{
1846 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001847 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848 nsecs_t standbyTime = systemTime();
1849 size_t mixBufferSize = mFrameCount * mFrameSize;
1850 // FIXME: Relaxed timing because of a certain device that can't meet latency
1851 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001852 // increase threshold again due to low power audio mode. The way this warning threshold is
1853 // calculated and its usefulness should be reconsidered anyway.
1854 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 nsecs_t lastWarning = 0;
1856 bool longStandbyExit = false;
1857 uint32_t activeSleepTime = activeSleepTimeUs();
1858 uint32_t idleSleepTime = idleSleepTimeUs();
1859 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001860 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001862#ifdef DEBUG_CPU_USAGE
1863 ThreadCpuUsage cpu;
1864 const CentralTendencyStatistics& stats = cpu.statistics();
1865#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866
Eric Laurentfeb0db62011-07-22 09:04:31 -07001867 acquireWakeLock();
1868
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 while (!exitPending())
1870 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001871#ifdef DEBUG_CPU_USAGE
1872 cpu.sampleAndEnable();
1873 unsigned n = stats.n();
1874 // cpu.elapsed() is expensive, so don't call it every loop
1875 if ((n & 127) == 1) {
1876 long long elapsed = cpu.elapsed();
1877 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1878 double perLoop = elapsed / (double) n;
1879 double perLoop100 = perLoop * 0.01;
1880 double mean = stats.mean();
1881 double stddev = stats.stddev();
1882 double minimum = stats.minimum();
1883 double maximum = stats.maximum();
1884 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001885 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 -07001886 elapsed * .000000001, n, perLoop * .000001,
1887 mean * .001,
1888 stddev * .001,
1889 minimum * .001,
1890 maximum * .001,
1891 mean / perLoop100,
1892 stddev / perLoop100,
1893 minimum / perLoop100,
1894 maximum / perLoop100);
1895 }
1896 }
1897#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 processConfigEvents();
1899
1900 mixerStatus = MIXER_IDLE;
1901 { // scope for mLock
1902
1903 Mutex::Autolock _l(mLock);
1904
1905 if (checkForNewParameters_l()) {
1906 mixBufferSize = mFrameCount * mFrameSize;
1907 // FIXME: Relaxed timing because of a certain device that can't meet latency
1908 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001909 // increase threshold again due to low power audio mode. The way this warning
1910 // threshold is calculated and its usefulness should be reconsidered anyway.
1911 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912 activeSleepTime = activeSleepTimeUs();
1913 idleSleepTime = idleSleepTimeUs();
1914 }
1915
1916 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1917
1918 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001919 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1920 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001922 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001923 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 mStandby = true;
1925 mBytesWritten = 0;
1926 }
1927
1928 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1929 // we're about to wait, flush the binder command buffer
1930 IPCThreadState::self()->flushCommands();
1931
1932 if (exitPending()) break;
1933
Eric Laurentfeb0db62011-07-22 09:04:31 -07001934 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001935 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001936 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001938 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001939 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940
Eric Laurent27741442012-01-17 19:20:12 -08001941 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001942 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 char value[PROPERTY_VALUE_MAX];
1944 property_get("ro.audio.silent", value, "0");
1945 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001946 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08001947 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 }
1949 }
1950
1951 standbyTime = systemTime() + kStandbyTimeInNsecs;
1952 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001953 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954 continue;
1955 }
1956 }
1957
1958 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1959
1960 // prevent any changes in effect chain list and in each effect chain
1961 // during mixing and effect process as the audio buffers could be deleted
1962 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001963 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001964 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965
Glenn Kastenf6b16782011-12-15 09:51:17 -08001966 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 // mix buffers...
1968 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001969 // increase sleep time progressively when application underrun condition clears.
1970 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1971 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1972 // such that we would underrun the audio HAL.
1973 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001974 sleepTimeShift--;
1975 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001976 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 standbyTime = systemTime() + kStandbyTimeInNsecs;
1978 //TODO: delay standby when effects have a tail
1979 } else {
1980 // If no tracks are ready, sleep once for the duration of an output
1981 // buffer size, then write 0s to the output
1982 if (sleepTime == 0) {
1983 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001984 sleepTime = activeSleepTime >> sleepTimeShift;
1985 if (sleepTime < kMinThreadSleepTimeUs) {
1986 sleepTime = kMinThreadSleepTimeUs;
1987 }
1988 // reduce sleep time in case of consecutive application underruns to avoid
1989 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1990 // duration we would end up writing less data than needed by the audio HAL if
1991 // the condition persists.
1992 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1993 sleepTimeShift++;
1994 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995 } else {
1996 sleepTime = idleSleepTime;
1997 }
1998 } else if (mBytesWritten != 0 ||
1999 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2000 memset (mMixBuffer, 0, mixBufferSize);
2001 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002002 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 }
2004 // TODO add standby time extension fct of effect tail
2005 }
2006
2007 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002008 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 }
2010 // sleepTime == 0 means we must write to audio hardware
2011 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002012 for (size_t i = 0; i < effectChains.size(); i ++) {
2013 effectChains[i]->process_l();
2014 }
2015 // enable changes in effect chain
2016 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 mLastWriteTime = systemTime();
2018 mInWrite = true;
2019 mBytesWritten += mixBufferSize;
2020
Dima Zavin799a70e2011-04-18 16:57:27 -07002021 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2023 mNumWrites++;
2024 mInWrite = false;
2025 nsecs_t now = systemTime();
2026 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002027 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002029 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002030 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031 ns2ms(delta), mNumDelayedWrites, this);
2032 lastWarning = now;
2033 }
2034 if (mStandby) {
2035 longStandbyExit = true;
2036 }
2037 }
2038 mStandby = false;
2039 } else {
2040 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002041 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 usleep(sleepTime);
2043 }
2044
2045 // finally let go of all our tracks, without the lock held
2046 // since we can't guarantee the destructors won't acquire that
2047 // same lock.
2048 tracksToRemove.clear();
2049
2050 // Effect chains will be actually deleted here if they were removed from
2051 // mEffectChains list during mixing or effects processing
2052 effectChains.clear();
2053 }
2054
2055 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002056 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002057 }
2058
Eric Laurentfeb0db62011-07-22 09:04:31 -07002059 releaseWakeLock();
2060
Steve Block3856b092011-10-20 11:56:00 +01002061 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 return false;
2063}
2064
2065// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002066AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2067 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068{
2069
Glenn Kasten29c23c32012-01-26 13:37:52 -08002070 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 // find out which tracks need to be processed
2072 size_t count = activeTracks.size();
2073 size_t mixedTracks = 0;
2074 size_t tracksWithEffect = 0;
2075
2076 float masterVolume = mMasterVolume;
2077 bool masterMute = mMasterMute;
2078
Eric Laurent571d49c2010-08-11 05:20:11 -07002079 if (masterMute) {
2080 masterVolume = 0;
2081 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002083 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002085 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002086 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 masterVolume = (float)((v + (1 << 23)) >> 24);
2088 chain.clear();
2089 }
2090
2091 for (size_t i=0 ; i<count ; i++) {
2092 sp<Track> t = activeTracks[i].promote();
2093 if (t == 0) continue;
2094
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002095 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 Track* const track = t.get();
2097 audio_track_cblk_t* cblk = track->cblk();
2098
2099 // The first time a track is added we wait
2100 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002101 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002102 // make sure that we have enough frames to mix one full buffer.
2103 // enforce this condition only once to enable draining the buffer in case the client
2104 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002105 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002106 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002107 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002108 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002109 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002110 if (t->sampleRate() == (int)mSampleRate) {
2111 minFrames = mFrameCount;
2112 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002113 // +1 for rounding and +1 for additional sample needed for interpolation
2114 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2115 // add frames already consumed but not yet released by the resampler
2116 // because cblk->framesReady() will include these frames
2117 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2118 // the minimum track buffer size is normally twice the number of frames necessary
2119 // to fill one buffer and the resampler should not leave more than one buffer worth
2120 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002121 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002122 }
2123 }
2124 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002125 !track->isPaused() && !track->isTerminated())
2126 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002127 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002128
2129 mixedTracks++;
2130
2131 // track->mainBuffer() != mMixBuffer means there is an effect chain
2132 // connected to the track
2133 chain.clear();
2134 if (track->mainBuffer() != mMixBuffer) {
2135 chain = getEffectChain_l(track->sessionId());
2136 // Delegate volume control to effect in track effect chain if needed
2137 if (chain != 0) {
2138 tracksWithEffect++;
2139 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002140 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002141 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002142 }
2143 }
2144
2145
2146 int param = AudioMixer::VOLUME;
2147 if (track->mFillingUpStatus == Track::FS_FILLED) {
2148 // no ramp for the first volume setting
2149 track->mFillingUpStatus = Track::FS_ACTIVE;
2150 if (track->mState == TrackBase::RESUMING) {
2151 track->mState = TrackBase::ACTIVE;
2152 param = AudioMixer::RAMP_VOLUME;
2153 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002154 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002155 } else if (cblk->server != 0) {
2156 // If the track is stopped before the first frame was mixed,
2157 // do not apply ramp
2158 param = AudioMixer::RAMP_VOLUME;
2159 }
2160
2161 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002162 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002163 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002165 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 if (track->isPausing()) {
2167 track->setPaused();
2168 }
2169 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002170
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 // read original volumes with volume control
2172 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002174 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002175 vl = vlr & 0xFFFF;
2176 vr = vlr >> 16;
2177 // track volumes come from shared memory, so can't be trusted and must be clamped
2178 if (vl > MAX_GAIN_INT) {
2179 ALOGV("Track left volume out of range: %04X", vl);
2180 vl = MAX_GAIN_INT;
2181 }
2182 if (vr > MAX_GAIN_INT) {
2183 ALOGV("Track right volume out of range: %04X", vr);
2184 vr = MAX_GAIN_INT;
2185 }
2186 // now apply the master volume and stream type volume
2187 vl = (uint32_t)(v * vl) << 12;
2188 vr = (uint32_t)(v * vr) << 12;
2189 // assuming master volume and stream type volume each go up to 1.0,
2190 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191
Glenn Kasten05632a52012-01-03 14:22:33 -08002192 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2193 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002194 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002195 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002196 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002197 }
2198 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002200 // Delegate volume control to effect in track effect chain if needed
2201 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2202 // Do not ramp volume if volume is controlled by effect
2203 param = AudioMixer::VOLUME;
2204 track->mHasVolumeController = true;
2205 } else {
2206 // force no volume ramp when volume controller was just disabled or removed
2207 // from effect chain to avoid volume spike
2208 if (track->mHasVolumeController) {
2209 param = AudioMixer::VOLUME;
2210 }
2211 track->mHasVolumeController = false;
2212 }
2213
2214 // Convert volumes from 8.24 to 4.12 format
2215 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002216 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002217 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2218 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2219 left = int16_t(v_clamped);
2220 v_clamped = (vr + (1 << 11)) >> 12;
2221 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2222 right = int16_t(v_clamped);
2223
2224 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2225 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002226
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002228 mAudioMixer->setBufferProvider(name, track);
2229 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002231 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2232 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2233 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
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::TRACK,
2237 AudioMixer::FORMAT, (void *)track->format());
2238 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002239 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002241 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002243 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 AudioMixer::RESAMPLE,
2245 AudioMixer::SAMPLE_RATE,
2246 (void *)(cblk->sampleRate));
2247 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002248 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249 AudioMixer::TRACK,
2250 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2251 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002252 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 AudioMixer::TRACK,
2254 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2255
2256 // reset retry count
2257 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002258 // If one track is ready, set the mixer ready if:
2259 // - the mixer was not ready during previous round OR
2260 // - no other track is not ready
2261 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2262 mixerStatus != MIXER_TRACKS_ENABLED) {
2263 mixerStatus = MIXER_TRACKS_READY;
2264 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002265 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002266 //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 -07002267 if (track->isStopped()) {
2268 track->reset();
2269 }
2270 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2271 // We have consumed all the buffers of this track.
2272 // Remove it from the list of active tracks.
2273 tracksToRemove->add(track);
2274 } else {
2275 // No buffers for this track. Give it a few chances to
2276 // fill a buffer, then remove it from active list.
2277 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002278 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002280 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002281 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002282 // If one track is not ready, mark the mixer also not ready if:
2283 // - the mixer was ready during previous round OR
2284 // - no other track is ready
2285 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2286 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 mixerStatus = MIXER_TRACKS_ENABLED;
2288 }
2289 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002290 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291 }
2292 }
2293
2294 // remove all the tracks that need to be...
2295 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002296 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 for (size_t i=0 ; i<count ; i++) {
2298 const sp<Track>& track = tracksToRemove->itemAt(i);
2299 mActiveTracks.remove(track);
2300 if (track->mainBuffer() != mMixBuffer) {
2301 chain = getEffectChain_l(track->sessionId());
2302 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002303 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002304 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 }
2306 }
2307 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002308 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002309 }
2310 }
2311 }
2312
2313 // mix buffer must be cleared if all tracks are connected to an
2314 // effect chain as in this case the mixer will not write to
2315 // mix buffer and track effects will accumulate into it
2316 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2317 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2318 }
2319
Eric Laurent27741442012-01-17 19:20:12 -08002320 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002321 return mixerStatus;
2322}
2323
Glenn Kastenfff6d712012-01-12 16:38:12 -08002324void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325{
Steve Block3856b092011-10-20 11:56:00 +01002326 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002327 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002329
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 size_t size = mTracks.size();
2331 for (size_t i = 0; i < size; i++) {
2332 sp<Track> t = mTracks[i];
2333 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002334 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 }
2337 }
2338}
2339
Glenn Kastenfff6d712012-01-12 16:38:12 -08002340void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002341{
Steve Block3856b092011-10-20 11:56:00 +01002342 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002343 this, streamType, valid);
2344 Mutex::Autolock _l(mLock);
2345
2346 mStreamTypes[streamType].valid = valid;
2347}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348
2349// getTrackName_l() must be called with ThreadBase::mLock held
2350int AudioFlinger::MixerThread::getTrackName_l()
2351{
2352 return mAudioMixer->getTrackName();
2353}
2354
2355// deleteTrackName_l() must be called with ThreadBase::mLock held
2356void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2357{
Steve Block3856b092011-10-20 11:56:00 +01002358 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002359 mAudioMixer->deleteTrackName(name);
2360}
2361
2362// checkForNewParameters_l() must be called with ThreadBase::mLock held
2363bool AudioFlinger::MixerThread::checkForNewParameters_l()
2364{
2365 bool reconfig = false;
2366
2367 while (!mNewParameters.isEmpty()) {
2368 status_t status = NO_ERROR;
2369 String8 keyValuePair = mNewParameters[0];
2370 AudioParameter param = AudioParameter(keyValuePair);
2371 int value;
2372
2373 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2374 reconfig = true;
2375 }
2376 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002377 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 status = BAD_VALUE;
2379 } else {
2380 reconfig = true;
2381 }
2382 }
2383 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002384 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 status = BAD_VALUE;
2386 } else {
2387 reconfig = true;
2388 }
2389 }
2390 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2391 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002392 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 // if frame count is changed after track creation
2394 if (!mTracks.isEmpty()) {
2395 status = INVALID_OPERATION;
2396 } else {
2397 reconfig = true;
2398 }
2399 }
2400 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002401 // when changing the audio output device, call addBatteryData to notify
2402 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002403 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002404 uint32_t params = 0;
2405 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002406 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002407 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2408 }
2409
2410 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002411 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002412 // check if any other device (except speaker) is on
2413 if (value & deviceWithoutSpeaker ) {
2414 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2415 }
2416
2417 if (params != 0) {
2418 addBatteryData(params);
2419 }
2420 }
2421
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 // forward device change to effects that have requested to be
2423 // aware of attached audio device.
2424 mDevice = (uint32_t)value;
2425 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002426 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 }
2428 }
2429
2430 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002431 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002432 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002434 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 mStandby = true;
2436 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002437 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002438 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 }
2440 if (status == NO_ERROR && reconfig) {
2441 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002442 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2443 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002444 readOutputParameters();
2445 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2446 for (size_t i = 0; i < mTracks.size() ; i++) {
2447 int name = getTrackName_l();
2448 if (name < 0) break;
2449 mTracks[i]->mName = name;
2450 // limit track sample rate to 2 x new output sample rate
2451 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2452 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2453 }
2454 }
2455 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2456 }
2457 }
2458
2459 mNewParameters.removeAt(0);
2460
2461 mParamStatus = status;
2462 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002463 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2464 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002465 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466 }
2467 return reconfig;
2468}
2469
2470status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2471{
2472 const size_t SIZE = 256;
2473 char buffer[SIZE];
2474 String8 result;
2475
2476 PlaybackThread::dumpInternals(fd, args);
2477
2478 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2479 result.append(buffer);
2480 write(fd, result.string(), result.size());
2481 return NO_ERROR;
2482}
2483
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2485{
Eric Laurent60e18242010-07-29 06:50:24 -07002486 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487}
2488
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002489uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2490{
2491 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2492}
2493
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002495AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2496 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002497 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002498 // mLeftVolFloat, mRightVolFloat
2499 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501}
2502
2503AudioFlinger::DirectOutputThread::~DirectOutputThread()
2504{
2505}
2506
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507static inline
2508int32_t mul(int16_t in, int16_t v)
2509{
2510#if defined(__arm__) && !defined(__thumb__)
2511 int32_t out;
2512 asm( "smulbb %[out], %[in], %[v] \n"
2513 : [out]"=r"(out)
2514 : [in]"%r"(in), [v]"r"(v)
2515 : );
2516 return out;
2517#else
2518 return in * int32_t(v);
2519#endif
2520}
2521
2522void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2523{
2524 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002525 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002526 return;
2527 }
2528
2529 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002530 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002531 size_t count = mFrameCount * mChannelCount;
2532 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2533 int16_t *dst = mMixBuffer + count-1;
2534 while(count--) {
2535 *dst-- = (int16_t)(*src--^0x80) << 8;
2536 }
2537 }
2538
2539 size_t frameCount = mFrameCount;
2540 int16_t *out = mMixBuffer;
2541 if (ramp) {
2542 if (mChannelCount == 1) {
2543 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2544 int32_t vlInc = d / (int32_t)frameCount;
2545 int32_t vl = ((int32_t)mLeftVolShort << 16);
2546 do {
2547 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2548 out++;
2549 vl += vlInc;
2550 } while (--frameCount);
2551
2552 } else {
2553 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2554 int32_t vlInc = d / (int32_t)frameCount;
2555 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2556 int32_t vrInc = d / (int32_t)frameCount;
2557 int32_t vl = ((int32_t)mLeftVolShort << 16);
2558 int32_t vr = ((int32_t)mRightVolShort << 16);
2559 do {
2560 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2561 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2562 out += 2;
2563 vl += vlInc;
2564 vr += vrInc;
2565 } while (--frameCount);
2566 }
2567 } else {
2568 if (mChannelCount == 1) {
2569 do {
2570 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2571 out++;
2572 } while (--frameCount);
2573 } else {
2574 do {
2575 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2576 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2577 out += 2;
2578 } while (--frameCount);
2579 }
2580 }
2581
2582 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002583 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002584 size_t count = mFrameCount * mChannelCount;
2585 int16_t *src = mMixBuffer;
2586 uint8_t *dst = (uint8_t *)mMixBuffer;
2587 while(count--) {
2588 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2589 }
2590 }
2591
2592 mLeftVolShort = leftVol;
2593 mRightVolShort = rightVol;
2594}
2595
2596bool AudioFlinger::DirectOutputThread::threadLoop()
2597{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002598 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002599 sp<Track> trackToRemove;
2600 sp<Track> activeTrack;
2601 nsecs_t standbyTime = systemTime();
2602 int8_t *curBuf;
2603 size_t mixBufferSize = mFrameCount*mFrameSize;
2604 uint32_t activeSleepTime = activeSleepTimeUs();
2605 uint32_t idleSleepTime = idleSleepTimeUs();
2606 uint32_t sleepTime = idleSleepTime;
2607 // use shorter standby delay as on normal output to release
2608 // hardware resources as soon as possible
2609 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2610
Eric Laurentfeb0db62011-07-22 09:04:31 -07002611 acquireWakeLock();
2612
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 while (!exitPending())
2614 {
2615 bool rampVolume;
2616 uint16_t leftVol;
2617 uint16_t rightVol;
2618 Vector< sp<EffectChain> > effectChains;
2619
2620 processConfigEvents();
2621
2622 mixerStatus = MIXER_IDLE;
2623
2624 { // scope for the mLock
2625
2626 Mutex::Autolock _l(mLock);
2627
2628 if (checkForNewParameters_l()) {
2629 mixBufferSize = mFrameCount*mFrameSize;
2630 activeSleepTime = activeSleepTimeUs();
2631 idleSleepTime = idleSleepTimeUs();
2632 standbyDelay = microseconds(activeSleepTime*2);
2633 }
2634
2635 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002636 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2637 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 // wait until we have something to do...
2639 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002640 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002641 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 mStandby = true;
2643 mBytesWritten = 0;
2644 }
2645
2646 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2647 // we're about to wait, flush the binder command buffer
2648 IPCThreadState::self()->flushCommands();
2649
2650 if (exitPending()) break;
2651
Eric Laurentfeb0db62011-07-22 09:04:31 -07002652 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002653 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002655 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002656 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
Glenn Kastenf1d45922012-01-13 15:54:24 -08002658 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002659 char value[PROPERTY_VALUE_MAX];
2660 property_get("ro.audio.silent", value, "0");
2661 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002662 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08002663 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 }
2665 }
2666
2667 standbyTime = systemTime() + standbyDelay;
2668 sleepTime = idleSleepTime;
2669 continue;
2670 }
2671 }
2672
2673 effectChains = mEffectChains;
2674
2675 // find out which tracks need to be processed
2676 if (mActiveTracks.size() != 0) {
2677 sp<Track> t = mActiveTracks[0].promote();
2678 if (t == 0) continue;
2679
2680 Track* const track = t.get();
2681 audio_track_cblk_t* cblk = track->cblk();
2682
2683 // The first time a track is added we wait
2684 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002685 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002686 !track->isPaused() && !track->isTerminated())
2687 {
Steve Block3856b092011-10-20 11:56:00 +01002688 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689
2690 if (track->mFillingUpStatus == Track::FS_FILLED) {
2691 track->mFillingUpStatus = Track::FS_ACTIVE;
2692 mLeftVolFloat = mRightVolFloat = 0;
2693 mLeftVolShort = mRightVolShort = 0;
2694 if (track->mState == TrackBase::RESUMING) {
2695 track->mState = TrackBase::ACTIVE;
2696 rampVolume = true;
2697 }
2698 } else if (cblk->server != 0) {
2699 // If the track is stopped before the first frame was mixed,
2700 // do not apply ramp
2701 rampVolume = true;
2702 }
2703 // compute volume for this track
2704 float left, right;
2705 if (track->isMuted() || mMasterMute || track->isPausing() ||
2706 mStreamTypes[track->type()].mute) {
2707 left = right = 0;
2708 if (track->isPausing()) {
2709 track->setPaused();
2710 }
2711 } else {
2712 float typeVolume = mStreamTypes[track->type()].volume;
2713 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002714 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002715 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2717 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002718 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2720 right = v_clamped/MAX_GAIN;
2721 }
2722
2723 if (left != mLeftVolFloat || right != mRightVolFloat) {
2724 mLeftVolFloat = left;
2725 mRightVolFloat = right;
2726
2727 // If audio HAL implements volume control,
2728 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002729 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 left = 1.0f;
2731 right = 1.0f;
2732 }
2733
2734 // Convert volumes from float to 8.24
2735 uint32_t vl = (uint32_t)(left * (1 << 24));
2736 uint32_t vr = (uint32_t)(right * (1 << 24));
2737
2738 // Delegate volume control to effect in track effect chain if needed
2739 // only one effect chain can be present on DirectOutputThread, so if
2740 // there is one, the track is connected to it
2741 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002742 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002743 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002744 rampVolume = false;
2745 }
2746 }
2747
2748 // Convert volumes from 8.24 to 4.12 format
2749 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2750 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2751 leftVol = (uint16_t)v_clamped;
2752 v_clamped = (vr + (1 << 11)) >> 12;
2753 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2754 rightVol = (uint16_t)v_clamped;
2755 } else {
2756 leftVol = mLeftVolShort;
2757 rightVol = mRightVolShort;
2758 rampVolume = false;
2759 }
2760
2761 // reset retry count
2762 track->mRetryCount = kMaxTrackRetriesDirect;
2763 activeTrack = t;
2764 mixerStatus = MIXER_TRACKS_READY;
2765 } else {
Steve Block3856b092011-10-20 11:56:00 +01002766 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 if (track->isStopped()) {
2768 track->reset();
2769 }
2770 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2771 // We have consumed all the buffers of this track.
2772 // Remove it from the list of active tracks.
2773 trackToRemove = track;
2774 } else {
2775 // No buffers for this track. Give it a few chances to
2776 // fill a buffer, then remove it from active list.
2777 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002778 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 trackToRemove = track;
2780 } else {
2781 mixerStatus = MIXER_TRACKS_ENABLED;
2782 }
2783 }
2784 }
2785 }
2786
2787 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002788 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 mActiveTracks.remove(trackToRemove);
2790 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002791 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002792 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002793 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002794 }
2795 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002796 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 }
2798 }
2799
Eric Laurentde070132010-07-13 04:45:46 -07002800 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 }
2802
Glenn Kastenf6b16782011-12-15 09:51:17 -08002803 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804 AudioBufferProvider::Buffer buffer;
2805 size_t frameCount = mFrameCount;
2806 curBuf = (int8_t *)mMixBuffer;
2807 // output audio to hardware
2808 while (frameCount) {
2809 buffer.frameCount = frameCount;
2810 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002811 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 memset(curBuf, 0, frameCount * mFrameSize);
2813 break;
2814 }
2815 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2816 frameCount -= buffer.frameCount;
2817 curBuf += buffer.frameCount * mFrameSize;
2818 activeTrack->releaseBuffer(&buffer);
2819 }
2820 sleepTime = 0;
2821 standbyTime = systemTime() + standbyDelay;
2822 } else {
2823 if (sleepTime == 0) {
2824 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2825 sleepTime = activeSleepTime;
2826 } else {
2827 sleepTime = idleSleepTime;
2828 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002829 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2831 sleepTime = 0;
2832 }
2833 }
2834
2835 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002836 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 }
2838 // sleepTime == 0 means we must write to audio hardware
2839 if (sleepTime == 0) {
2840 if (mixerStatus == MIXER_TRACKS_READY) {
2841 applyVolume(leftVol, rightVol, rampVolume);
2842 }
2843 for (size_t i = 0; i < effectChains.size(); i ++) {
2844 effectChains[i]->process_l();
2845 }
Eric Laurentde070132010-07-13 04:45:46 -07002846 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847
2848 mLastWriteTime = systemTime();
2849 mInWrite = true;
2850 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002851 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2853 mNumWrites++;
2854 mInWrite = false;
2855 mStandby = false;
2856 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002857 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 usleep(sleepTime);
2859 }
2860
2861 // finally let go of removed track, without the lock held
2862 // since we can't guarantee the destructors won't acquire that
2863 // same lock.
2864 trackToRemove.clear();
2865 activeTrack.clear();
2866
2867 // Effect chains will be actually deleted here if they were removed from
2868 // mEffectChains list during mixing or effects processing
2869 effectChains.clear();
2870 }
2871
2872 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002873 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 }
2875
Eric Laurentfeb0db62011-07-22 09:04:31 -07002876 releaseWakeLock();
2877
Steve Block3856b092011-10-20 11:56:00 +01002878 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 return false;
2880}
2881
2882// getTrackName_l() must be called with ThreadBase::mLock held
2883int AudioFlinger::DirectOutputThread::getTrackName_l()
2884{
2885 return 0;
2886}
2887
2888// deleteTrackName_l() must be called with ThreadBase::mLock held
2889void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2890{
2891}
2892
2893// checkForNewParameters_l() must be called with ThreadBase::mLock held
2894bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2895{
2896 bool reconfig = false;
2897
2898 while (!mNewParameters.isEmpty()) {
2899 status_t status = NO_ERROR;
2900 String8 keyValuePair = mNewParameters[0];
2901 AudioParameter param = AudioParameter(keyValuePair);
2902 int value;
2903
2904 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2905 // do not accept frame count changes if tracks are open as the track buffer
2906 // size depends on frame count and correct behavior would not be garantied
2907 // if frame count is changed after track creation
2908 if (!mTracks.isEmpty()) {
2909 status = INVALID_OPERATION;
2910 } else {
2911 reconfig = true;
2912 }
2913 }
2914 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002915 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002916 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002918 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 mStandby = true;
2920 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002921 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002922 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 }
2924 if (status == NO_ERROR && reconfig) {
2925 readOutputParameters();
2926 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2927 }
2928 }
2929
2930 mNewParameters.removeAt(0);
2931
2932 mParamStatus = status;
2933 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002934 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2935 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002936 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 }
2938 return reconfig;
2939}
2940
2941uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2942{
2943 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002944 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002945 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002946 } else {
2947 time = 10000;
2948 }
2949 return time;
2950}
2951
2952uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2953{
2954 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002955 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002956 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002957 } else {
2958 time = 10000;
2959 }
2960 return time;
2961}
2962
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002963uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2964{
2965 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002966 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002967 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2968 } else {
2969 time = 10000;
2970 }
2971 return time;
2972}
2973
2974
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975// ----------------------------------------------------------------------------
2976
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002977AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002978 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002979 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2980 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 addOutputTrack(mainThread);
2983}
2984
2985AudioFlinger::DuplicatingThread::~DuplicatingThread()
2986{
2987 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2988 mOutputTracks[i]->destroy();
2989 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002990}
2991
2992bool AudioFlinger::DuplicatingThread::threadLoop()
2993{
2994 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002995 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002996 nsecs_t standbyTime = systemTime();
2997 size_t mixBufferSize = mFrameCount*mFrameSize;
2998 SortedVector< sp<OutputTrack> > outputTracks;
2999 uint32_t writeFrames = 0;
3000 uint32_t activeSleepTime = activeSleepTimeUs();
3001 uint32_t idleSleepTime = idleSleepTimeUs();
3002 uint32_t sleepTime = idleSleepTime;
3003 Vector< sp<EffectChain> > effectChains;
3004
Eric Laurentfeb0db62011-07-22 09:04:31 -07003005 acquireWakeLock();
3006
Mathias Agopian65ab4712010-07-14 17:59:35 -07003007 while (!exitPending())
3008 {
3009 processConfigEvents();
3010
3011 mixerStatus = MIXER_IDLE;
3012 { // scope for the mLock
3013
3014 Mutex::Autolock _l(mLock);
3015
3016 if (checkForNewParameters_l()) {
3017 mixBufferSize = mFrameCount*mFrameSize;
3018 updateWaitTime();
3019 activeSleepTime = activeSleepTimeUs();
3020 idleSleepTime = idleSleepTimeUs();
3021 }
3022
3023 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3024
3025 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3026 outputTracks.add(mOutputTracks[i]);
3027 }
3028
3029 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003030 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3031 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 if (!mStandby) {
3033 for (size_t i = 0; i < outputTracks.size(); i++) {
3034 outputTracks[i]->stop();
3035 }
3036 mStandby = true;
3037 mBytesWritten = 0;
3038 }
3039
3040 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3041 // we're about to wait, flush the binder command buffer
3042 IPCThreadState::self()->flushCommands();
3043 outputTracks.clear();
3044
3045 if (exitPending()) break;
3046
Eric Laurentfeb0db62011-07-22 09:04:31 -07003047 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003048 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003050 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003051 acquireWakeLock_l();
3052
Eric Laurent27741442012-01-17 19:20:12 -08003053 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003054 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003055 char value[PROPERTY_VALUE_MAX];
3056 property_get("ro.audio.silent", value, "0");
3057 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003058 ALOGD("Silence is golden");
Glenn Kasten6637baa2012-01-09 09:40:36 -08003059 setMasterMute_l(true);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 }
3061 }
3062
3063 standbyTime = systemTime() + kStandbyTimeInNsecs;
3064 sleepTime = idleSleepTime;
3065 continue;
3066 }
3067 }
3068
3069 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3070
3071 // prevent any changes in effect chain list and in each effect chain
3072 // during mixing and effect process as the audio buffers could be deleted
3073 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003074 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075 }
3076
Glenn Kastenf6b16782011-12-15 09:51:17 -08003077 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 // mix buffers...
3079 if (outputsReady(outputTracks)) {
3080 mAudioMixer->process();
3081 } else {
3082 memset(mMixBuffer, 0, mixBufferSize);
3083 }
3084 sleepTime = 0;
3085 writeFrames = mFrameCount;
3086 } else {
3087 if (sleepTime == 0) {
3088 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3089 sleepTime = activeSleepTime;
3090 } else {
3091 sleepTime = idleSleepTime;
3092 }
3093 } else if (mBytesWritten != 0) {
3094 // flush remaining overflow buffers in output tracks
3095 for (size_t i = 0; i < outputTracks.size(); i++) {
3096 if (outputTracks[i]->isActive()) {
3097 sleepTime = 0;
3098 writeFrames = 0;
3099 memset(mMixBuffer, 0, mixBufferSize);
3100 break;
3101 }
3102 }
3103 }
3104 }
3105
3106 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003107 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003108 }
3109 // sleepTime == 0 means we must write to audio hardware
3110 if (sleepTime == 0) {
3111 for (size_t i = 0; i < effectChains.size(); i ++) {
3112 effectChains[i]->process_l();
3113 }
3114 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003115 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003116
3117 standbyTime = systemTime() + kStandbyTimeInNsecs;
3118 for (size_t i = 0; i < outputTracks.size(); i++) {
3119 outputTracks[i]->write(mMixBuffer, writeFrames);
3120 }
3121 mStandby = false;
3122 mBytesWritten += mixBufferSize;
3123 } else {
3124 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003125 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 usleep(sleepTime);
3127 }
3128
3129 // finally let go of all our tracks, without the lock held
3130 // since we can't guarantee the destructors won't acquire that
3131 // same lock.
3132 tracksToRemove.clear();
3133 outputTracks.clear();
3134
3135 // Effect chains will be actually deleted here if they were removed from
3136 // mEffectChains list during mixing or effects processing
3137 effectChains.clear();
3138 }
3139
Eric Laurentfeb0db62011-07-22 09:04:31 -07003140 releaseWakeLock();
3141
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 return false;
3143}
3144
3145void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3146{
3147 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3148 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3149 this,
3150 mSampleRate,
3151 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003152 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 frameCount);
3154 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003155 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003157 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 updateWaitTime();
3159 }
3160}
3161
3162void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3163{
3164 Mutex::Autolock _l(mLock);
3165 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3166 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3167 mOutputTracks[i]->destroy();
3168 mOutputTracks.removeAt(i);
3169 updateWaitTime();
3170 return;
3171 }
3172 }
Steve Block3856b092011-10-20 11:56:00 +01003173 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003174}
3175
3176void AudioFlinger::DuplicatingThread::updateWaitTime()
3177{
3178 mWaitTimeMs = UINT_MAX;
3179 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3180 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003181 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003182 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3183 if (waitTimeMs < mWaitTimeMs) {
3184 mWaitTimeMs = waitTimeMs;
3185 }
3186 }
3187 }
3188}
3189
3190
3191bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3192{
3193 for (size_t i = 0; i < outputTracks.size(); i++) {
3194 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3195 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003196 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197 return false;
3198 }
3199 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3200 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003201 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003202 return false;
3203 }
3204 }
3205 return true;
3206}
3207
3208uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3209{
3210 return (mWaitTimeMs * 1000) / 2;
3211}
3212
3213// ----------------------------------------------------------------------------
3214
3215// TrackBase constructor must be called with AudioFlinger::mLock held
3216AudioFlinger::ThreadBase::TrackBase::TrackBase(
3217 const wp<ThreadBase>& thread,
3218 const sp<Client>& client,
3219 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003220 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003221 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 int frameCount,
3223 uint32_t flags,
3224 const sp<IMemory>& sharedBuffer,
3225 int sessionId)
3226 : RefBase(),
3227 mThread(thread),
3228 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003229 mCblk(NULL),
3230 // mBuffer
3231 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232 mFrameCount(0),
3233 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 mFormat(format),
3235 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3236 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003237 // mChannelCount
3238 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003239{
Steve Block3856b092011-10-20 11:56:00 +01003240 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241
Steve Blockb8a80522011-12-20 16:23:08 +00003242 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003244 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3246 if (sharedBuffer == 0) {
3247 size += bufferSize;
3248 }
3249
3250 if (client != NULL) {
3251 mCblkMemory = client->heap()->allocate(size);
3252 if (mCblkMemory != 0) {
3253 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003254 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 new(mCblk) audio_track_cblk_t();
3256 // clear all buffers
3257 mCblk->frameCount = frameCount;
3258 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003259 mChannelCount = channelCount;
3260 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 if (sharedBuffer == 0) {
3262 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3263 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3264 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003265 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 mCblk->flags = CBLK_UNDERRUN_ON;
3267 } else {
3268 mBuffer = sharedBuffer->pointer();
3269 }
3270 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3271 }
3272 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003273 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 client->heap()->dump("AudioTrack");
3275 return;
3276 }
3277 } else {
3278 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003279 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 new(mCblk) audio_track_cblk_t();
3281 // clear all buffers
3282 mCblk->frameCount = frameCount;
3283 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003284 mChannelCount = channelCount;
3285 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3287 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3288 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003289 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 mCblk->flags = CBLK_UNDERRUN_ON;
3291 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 }
3293}
3294
3295AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3296{
Glenn Kastena0d68332012-01-27 16:47:15 -08003297 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003298 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003300 } else {
3301 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 }
3303 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003304 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003305 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003306 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003307 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003308 // If the client's reference count drops to zero, the associated destructor
3309 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3310 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311 mClient.clear();
3312 }
3313}
3314
3315void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3316{
Glenn Kastene0feee32011-12-13 11:53:26 -08003317 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318 mFrameCount = buffer->frameCount;
3319 step();
3320 buffer->frameCount = 0;
3321}
3322
3323bool AudioFlinger::ThreadBase::TrackBase::step() {
3324 bool result;
3325 audio_track_cblk_t* cblk = this->cblk();
3326
3327 result = cblk->stepServer(mFrameCount);
3328 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003329 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 mFlags |= STEPSERVER_FAILED;
3331 }
3332 return result;
3333}
3334
3335void AudioFlinger::ThreadBase::TrackBase::reset() {
3336 audio_track_cblk_t* cblk = this->cblk();
3337
3338 cblk->user = 0;
3339 cblk->server = 0;
3340 cblk->userBase = 0;
3341 cblk->serverBase = 0;
3342 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003343 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344}
3345
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3347 return (int)mCblk->sampleRate;
3348}
3349
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3351 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003352 size_t frameSize = cblk->frameSize;
3353 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3354 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355
3356 // Check validity of returned pointer in case the track control block would have been corrupted.
3357 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003358 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003359 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 -07003360 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003362 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003363 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003364 }
3365
3366 return bufferStart;
3367}
3368
3369// ----------------------------------------------------------------------------
3370
3371// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3372AudioFlinger::PlaybackThread::Track::Track(
3373 const wp<ThreadBase>& thread,
3374 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003375 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003377 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003378 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 int frameCount,
3380 const sp<IMemory>& sharedBuffer,
3381 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003382 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003383 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3384 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385{
3386 if (mCblk != NULL) {
3387 sp<ThreadBase> baseThread = thread.promote();
3388 if (baseThread != 0) {
3389 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3390 mName = playbackThread->getTrackName_l();
3391 mMainBuffer = playbackThread->mixBuffer();
3392 }
Steve Block3856b092011-10-20 11:56:00 +01003393 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003395 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003396 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 mStreamType = streamType;
3398 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3399 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003400 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003401 }
3402}
3403
3404AudioFlinger::PlaybackThread::Track::~Track()
3405{
Steve Block3856b092011-10-20 11:56:00 +01003406 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 sp<ThreadBase> thread = mThread.promote();
3408 if (thread != 0) {
3409 Mutex::Autolock _l(thread->mLock);
3410 mState = TERMINATED;
3411 }
3412}
3413
3414void AudioFlinger::PlaybackThread::Track::destroy()
3415{
3416 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3417 // by removing it from mTracks vector, so there is a risk that this Tracks's
3418 // desctructor is called. As the destructor needs to lock mLock,
3419 // we must acquire a strong reference on this Track before locking mLock
3420 // here so that the destructor is called only when exiting this function.
3421 // On the other hand, as long as Track::destroy() is only called by
3422 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3423 // this Track with its member mTrack.
3424 sp<Track> keep(this);
3425 { // scope for mLock
3426 sp<ThreadBase> thread = mThread.promote();
3427 if (thread != 0) {
3428 if (!isOutputTrack()) {
3429 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003430 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003431 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003432 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003433
3434 // to track the speaker usage
3435 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 }
3437 AudioSystem::releaseOutput(thread->id());
3438 }
3439 Mutex::Autolock _l(thread->mLock);
3440 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3441 playbackThread->destroyTrack_l(this);
3442 }
3443 }
3444}
3445
3446void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3447{
Glenn Kasten83d86532012-01-17 14:39:34 -08003448 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003449 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 -07003450 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003451 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 mStreamType,
3453 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003454 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 mSessionId,
3456 mFrameCount,
3457 mState,
3458 mMute,
3459 mFillingUpStatus,
3460 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003461 vlr & 0xFFFF,
3462 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 mCblk->server,
3464 mCblk->user,
3465 (int)mMainBuffer,
3466 (int)mAuxBuffer);
3467}
3468
3469status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3470{
3471 audio_track_cblk_t* cblk = this->cblk();
3472 uint32_t framesReady;
3473 uint32_t framesReq = buffer->frameCount;
3474
3475 // Check if last stepServer failed, try to step now
3476 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3477 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003478 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3480 }
3481
3482 framesReady = cblk->framesReady();
3483
Glenn Kastenf6b16782011-12-15 09:51:17 -08003484 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 uint32_t s = cblk->server;
3486 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3487
3488 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3489 if (framesReq > framesReady) {
3490 framesReq = framesReady;
3491 }
3492 if (s + framesReq > bufferEnd) {
3493 framesReq = bufferEnd - s;
3494 }
3495
3496 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003497 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003498
3499 buffer->frameCount = framesReq;
3500 return NO_ERROR;
3501 }
3502
3503getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003504 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003506 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 return NOT_ENOUGH_DATA;
3508}
3509
3510bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003511 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003512
3513 if (mCblk->framesReady() >= mCblk->frameCount ||
3514 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3515 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003516 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 return true;
3518 }
3519 return false;
3520}
3521
3522status_t AudioFlinger::PlaybackThread::Track::start()
3523{
3524 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003525 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003526 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003527 sp<ThreadBase> thread = mThread.promote();
3528 if (thread != 0) {
3529 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003530 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 // here the track could be either new, or restarted
3532 // in both cases "unstop" the track
3533 if (mState == PAUSED) {
3534 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003535 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 } else {
3537 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003538 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 }
3540
3541 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3542 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003543 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003544 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003545 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003547
3548 // to track the speaker usage
3549 if (status == NO_ERROR) {
3550 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552 }
3553 if (status == NO_ERROR) {
3554 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3555 playbackThread->addTrack_l(this);
3556 } else {
3557 mState = state;
3558 }
3559 } else {
3560 status = BAD_VALUE;
3561 }
3562 return status;
3563}
3564
3565void AudioFlinger::PlaybackThread::Track::stop()
3566{
Steve Block3856b092011-10-20 11:56:00 +01003567 ALOGV("stop(%d), calling thread %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);
Glenn Kastenb853e982012-01-26 13:39:18 -08003571 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572 if (mState > STOPPED) {
3573 mState = STOPPED;
3574 // If the track is not active (PAUSED and buffers full), flush buffers
3575 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3576 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3577 reset();
3578 }
Steve Block3856b092011-10-20 11:56:00 +01003579 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 }
3581 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3582 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003583 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003584 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003585 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003586 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003587
3588 // to track the speaker usage
3589 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 }
3591 }
3592}
3593
3594void AudioFlinger::PlaybackThread::Track::pause()
3595{
Steve Block3856b092011-10-20 11:56:00 +01003596 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 sp<ThreadBase> thread = mThread.promote();
3598 if (thread != 0) {
3599 Mutex::Autolock _l(thread->mLock);
3600 if (mState == ACTIVE || mState == RESUMING) {
3601 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003602 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 if (!isOutputTrack()) {
3604 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003605 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003606 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003607 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003609
3610 // to track the speaker usage
3611 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 }
3613 }
3614 }
3615}
3616
3617void AudioFlinger::PlaybackThread::Track::flush()
3618{
Steve Block3856b092011-10-20 11:56:00 +01003619 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 sp<ThreadBase> thread = mThread.promote();
3621 if (thread != 0) {
3622 Mutex::Autolock _l(thread->mLock);
3623 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3624 return;
3625 }
3626 // No point remaining in PAUSED state after a flush => go to
3627 // STOPPED state
3628 mState = STOPPED;
3629
Eric Laurent38ccae22011-03-28 18:37:07 -07003630 // do not reset the track if it is still in the process of being stopped or paused.
3631 // this will be done by prepareTracks_l() when the track is stopped.
3632 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3633 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3634 reset();
3635 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003636 }
3637}
3638
3639void AudioFlinger::PlaybackThread::Track::reset()
3640{
3641 // Do not reset twice to avoid discarding data written just after a flush and before
3642 // the audioflinger thread detects the track is stopped.
3643 if (!mResetDone) {
3644 TrackBase::reset();
3645 // Force underrun condition to avoid false underrun callback until first data is
3646 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003647 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3648 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649 mFillingUpStatus = FS_FILLING;
3650 mResetDone = true;
3651 }
3652}
3653
3654void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3655{
3656 mMute = muted;
3657}
3658
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3660{
3661 status_t status = DEAD_OBJECT;
3662 sp<ThreadBase> thread = mThread.promote();
3663 if (thread != 0) {
3664 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3665 status = playbackThread->attachAuxEffect(this, EffectId);
3666 }
3667 return status;
3668}
3669
3670void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3671{
3672 mAuxEffectId = EffectId;
3673 mAuxBuffer = buffer;
3674}
3675
3676// ----------------------------------------------------------------------------
3677
3678// RecordTrack constructor must be called with AudioFlinger::mLock held
3679AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3680 const wp<ThreadBase>& thread,
3681 const sp<Client>& client,
3682 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003683 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003684 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 int frameCount,
3686 uint32_t flags,
3687 int sessionId)
3688 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003689 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 mOverflow(false)
3691{
3692 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003693 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003694 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003695 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003696 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003697 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 } else {
3699 mCblk->frameSize = sizeof(int8_t);
3700 }
3701 }
3702}
3703
3704AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3705{
3706 sp<ThreadBase> thread = mThread.promote();
3707 if (thread != 0) {
3708 AudioSystem::releaseInput(thread->id());
3709 }
3710}
3711
3712status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3713{
3714 audio_track_cblk_t* cblk = this->cblk();
3715 uint32_t framesAvail;
3716 uint32_t framesReq = buffer->frameCount;
3717
3718 // Check if last stepServer failed, try to step now
3719 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3720 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003721 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003722 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3723 }
3724
3725 framesAvail = cblk->framesAvailable_l();
3726
Glenn Kastenf6b16782011-12-15 09:51:17 -08003727 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728 uint32_t s = cblk->server;
3729 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3730
3731 if (framesReq > framesAvail) {
3732 framesReq = framesAvail;
3733 }
3734 if (s + framesReq > bufferEnd) {
3735 framesReq = bufferEnd - s;
3736 }
3737
3738 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003739 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740
3741 buffer->frameCount = framesReq;
3742 return NO_ERROR;
3743 }
3744
3745getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003746 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747 buffer->frameCount = 0;
3748 return NOT_ENOUGH_DATA;
3749}
3750
3751status_t AudioFlinger::RecordThread::RecordTrack::start()
3752{
3753 sp<ThreadBase> thread = mThread.promote();
3754 if (thread != 0) {
3755 RecordThread *recordThread = (RecordThread *)thread.get();
3756 return recordThread->start(this);
3757 } else {
3758 return BAD_VALUE;
3759 }
3760}
3761
3762void AudioFlinger::RecordThread::RecordTrack::stop()
3763{
3764 sp<ThreadBase> thread = mThread.promote();
3765 if (thread != 0) {
3766 RecordThread *recordThread = (RecordThread *)thread.get();
3767 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003768 TrackBase::reset();
3769 // Force overerrun condition to avoid false overrun callback until first data is
3770 // read from buffer
3771 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 }
3773}
3774
3775void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3776{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003777 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003778 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003780 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781 mSessionId,
3782 mFrameCount,
3783 mState,
3784 mCblk->sampleRate,
3785 mCblk->server,
3786 mCblk->user);
3787}
3788
3789
3790// ----------------------------------------------------------------------------
3791
3792AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3793 const wp<ThreadBase>& thread,
3794 DuplicatingThread *sourceThread,
3795 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003796 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003797 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003798 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003799 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003800 mActive(false), mSourceThread(sourceThread)
3801{
3802
3803 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3804 if (mCblk != NULL) {
3805 mCblk->flags |= CBLK_DIRECTION_OUT;
3806 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 mOutBuffer.frameCount = 0;
3808 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003809 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003810 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3811 mCblk, mBuffer, mCblk->buffers,
3812 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003813 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003814 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815 }
3816}
3817
3818AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3819{
3820 clearBufferQueue();
3821}
3822
3823status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3824{
3825 status_t status = Track::start();
3826 if (status != NO_ERROR) {
3827 return status;
3828 }
3829
3830 mActive = true;
3831 mRetryCount = 127;
3832 return status;
3833}
3834
3835void AudioFlinger::PlaybackThread::OutputTrack::stop()
3836{
3837 Track::stop();
3838 clearBufferQueue();
3839 mOutBuffer.frameCount = 0;
3840 mActive = false;
3841}
3842
3843bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3844{
3845 Buffer *pInBuffer;
3846 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003847 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003848 bool outputBufferFull = false;
3849 inBuffer.frameCount = frames;
3850 inBuffer.i16 = data;
3851
3852 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3853
3854 if (!mActive && frames != 0) {
3855 start();
3856 sp<ThreadBase> thread = mThread.promote();
3857 if (thread != 0) {
3858 MixerThread *mixerThread = (MixerThread *)thread.get();
3859 if (mCblk->frameCount > frames){
3860 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3861 uint32_t startFrames = (mCblk->frameCount - frames);
3862 pInBuffer = new Buffer;
3863 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3864 pInBuffer->frameCount = startFrames;
3865 pInBuffer->i16 = pInBuffer->mBuffer;
3866 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3867 mBufferQueue.add(pInBuffer);
3868 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003869 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870 }
3871 }
3872 }
3873 }
3874
3875 while (waitTimeLeftMs) {
3876 // First write pending buffers, then new data
3877 if (mBufferQueue.size()) {
3878 pInBuffer = mBufferQueue.itemAt(0);
3879 } else {
3880 pInBuffer = &inBuffer;
3881 }
3882
3883 if (pInBuffer->frameCount == 0) {
3884 break;
3885 }
3886
3887 if (mOutBuffer.frameCount == 0) {
3888 mOutBuffer.frameCount = pInBuffer->frameCount;
3889 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003890 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003891 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 outputBufferFull = true;
3893 break;
3894 }
3895 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3896 if (waitTimeLeftMs >= waitTimeMs) {
3897 waitTimeLeftMs -= waitTimeMs;
3898 } else {
3899 waitTimeLeftMs = 0;
3900 }
3901 }
3902
3903 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3904 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3905 mCblk->stepUser(outFrames);
3906 pInBuffer->frameCount -= outFrames;
3907 pInBuffer->i16 += outFrames * channelCount;
3908 mOutBuffer.frameCount -= outFrames;
3909 mOutBuffer.i16 += outFrames * channelCount;
3910
3911 if (pInBuffer->frameCount == 0) {
3912 if (mBufferQueue.size()) {
3913 mBufferQueue.removeAt(0);
3914 delete [] pInBuffer->mBuffer;
3915 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003916 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917 } else {
3918 break;
3919 }
3920 }
3921 }
3922
3923 // If we could not write all frames, allocate a buffer and queue it for next time.
3924 if (inBuffer.frameCount) {
3925 sp<ThreadBase> thread = mThread.promote();
3926 if (thread != 0 && !thread->standby()) {
3927 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3928 pInBuffer = new Buffer;
3929 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3930 pInBuffer->frameCount = inBuffer.frameCount;
3931 pInBuffer->i16 = pInBuffer->mBuffer;
3932 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3933 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003934 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003936 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937 }
3938 }
3939 }
3940
3941 // Calling write() with a 0 length buffer, means that no more data will be written:
3942 // If no more buffers are pending, fill output track buffer to make sure it is started
3943 // by output mixer.
3944 if (frames == 0 && mBufferQueue.size() == 0) {
3945 if (mCblk->user < mCblk->frameCount) {
3946 frames = mCblk->frameCount - mCblk->user;
3947 pInBuffer = new Buffer;
3948 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3949 pInBuffer->frameCount = frames;
3950 pInBuffer->i16 = pInBuffer->mBuffer;
3951 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3952 mBufferQueue.add(pInBuffer);
3953 } else if (mActive) {
3954 stop();
3955 }
3956 }
3957
3958 return outputBufferFull;
3959}
3960
3961status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3962{
3963 int active;
3964 status_t result;
3965 audio_track_cblk_t* cblk = mCblk;
3966 uint32_t framesReq = buffer->frameCount;
3967
Steve Block3856b092011-10-20 11:56:00 +01003968// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 buffer->frameCount = 0;
3970
3971 uint32_t framesAvail = cblk->framesAvailable();
3972
3973
3974 if (framesAvail == 0) {
3975 Mutex::Autolock _l(cblk->lock);
3976 goto start_loop_here;
3977 while (framesAvail == 0) {
3978 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003979 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003980 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003981 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003982 }
3983 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3984 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003985 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003986 }
3987 // read the server count again
3988 start_loop_here:
3989 framesAvail = cblk->framesAvailable_l();
3990 }
3991 }
3992
3993// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003994// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003995// }
3996
3997 if (framesReq > framesAvail) {
3998 framesReq = framesAvail;
3999 }
4000
4001 uint32_t u = cblk->user;
4002 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4003
4004 if (u + framesReq > bufferEnd) {
4005 framesReq = bufferEnd - u;
4006 }
4007
4008 buffer->frameCount = framesReq;
4009 buffer->raw = (void *)cblk->buffer(u);
4010 return NO_ERROR;
4011}
4012
4013
4014void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4015{
4016 size_t size = mBufferQueue.size();
4017 Buffer *pBuffer;
4018
4019 for (size_t i = 0; i < size; i++) {
4020 pBuffer = mBufferQueue.itemAt(i);
4021 delete [] pBuffer->mBuffer;
4022 delete pBuffer;
4023 }
4024 mBufferQueue.clear();
4025}
4026
4027// ----------------------------------------------------------------------------
4028
4029AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4030 : RefBase(),
4031 mAudioFlinger(audioFlinger),
4032 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4033 mPid(pid)
4034{
4035 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4036}
4037
4038// Client destructor must be called with AudioFlinger::mLock held
4039AudioFlinger::Client::~Client()
4040{
4041 mAudioFlinger->removeClient_l(mPid);
4042}
4043
Glenn Kasten435dbe62012-01-30 10:15:48 -08004044sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004045{
4046 return mMemoryDealer;
4047}
4048
4049// ----------------------------------------------------------------------------
4050
4051AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4052 const sp<IAudioFlingerClient>& client,
4053 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004054 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055{
4056}
4057
4058AudioFlinger::NotificationClient::~NotificationClient()
4059{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060}
4061
4062void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4063{
4064 sp<NotificationClient> keep(this);
4065 {
4066 mAudioFlinger->removeNotificationClient(mPid);
4067 }
4068}
4069
4070// ----------------------------------------------------------------------------
4071
4072AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4073 : BnAudioTrack(),
4074 mTrack(track)
4075{
4076}
4077
4078AudioFlinger::TrackHandle::~TrackHandle() {
4079 // just stop the track on deletion, associated resources
4080 // will be freed from the main thread once all pending buffers have
4081 // been played. Unless it's not in the active track list, in which
4082 // case we free everything now...
4083 mTrack->destroy();
4084}
4085
Glenn Kasten90716c52012-01-26 13:40:12 -08004086sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4087 return mTrack->getCblk();
4088}
4089
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090status_t AudioFlinger::TrackHandle::start() {
4091 return mTrack->start();
4092}
4093
4094void AudioFlinger::TrackHandle::stop() {
4095 mTrack->stop();
4096}
4097
4098void AudioFlinger::TrackHandle::flush() {
4099 mTrack->flush();
4100}
4101
4102void AudioFlinger::TrackHandle::mute(bool e) {
4103 mTrack->mute(e);
4104}
4105
4106void AudioFlinger::TrackHandle::pause() {
4107 mTrack->pause();
4108}
4109
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4111{
4112 return mTrack->attachAuxEffect(EffectId);
4113}
4114
4115status_t AudioFlinger::TrackHandle::onTransact(
4116 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4117{
4118 return BnAudioTrack::onTransact(code, data, reply, flags);
4119}
4120
4121// ----------------------------------------------------------------------------
4122
4123sp<IAudioRecord> AudioFlinger::openRecord(
4124 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004125 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004127 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004128 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 int frameCount,
4130 uint32_t flags,
4131 int *sessionId,
4132 status_t *status)
4133{
4134 sp<RecordThread::RecordTrack> recordTrack;
4135 sp<RecordHandle> recordHandle;
4136 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 status_t lStatus;
4138 RecordThread *thread;
4139 size_t inFrameCount;
4140 int lSessionId;
4141
4142 // check calling permissions
4143 if (!recordingAllowed()) {
4144 lStatus = PERMISSION_DENIED;
4145 goto Exit;
4146 }
4147
4148 // add client to list
4149 { // scope for mLock
4150 Mutex::Autolock _l(mLock);
4151 thread = checkRecordThread_l(input);
4152 if (thread == NULL) {
4153 lStatus = BAD_VALUE;
4154 goto Exit;
4155 }
4156
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004157 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158
4159 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004160 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 lSessionId = *sessionId;
4162 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004163 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 if (sessionId != NULL) {
4165 *sessionId = lSessionId;
4166 }
4167 }
4168 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004169 recordTrack = thread->createRecordTrack_l(client,
4170 sampleRate,
4171 format,
4172 channelMask,
4173 frameCount,
4174 flags,
4175 lSessionId,
4176 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004178 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004179 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4180 // destructor is called by the TrackBase destructor with mLock held
4181 client.clear();
4182 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 goto Exit;
4184 }
4185
4186 // return to handle to client
4187 recordHandle = new RecordHandle(recordTrack);
4188 lStatus = NO_ERROR;
4189
4190Exit:
4191 if (status) {
4192 *status = lStatus;
4193 }
4194 return recordHandle;
4195}
4196
4197// ----------------------------------------------------------------------------
4198
4199AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4200 : BnAudioRecord(),
4201 mRecordTrack(recordTrack)
4202{
4203}
4204
4205AudioFlinger::RecordHandle::~RecordHandle() {
4206 stop();
4207}
4208
Glenn Kasten90716c52012-01-26 13:40:12 -08004209sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4210 return mRecordTrack->getCblk();
4211}
4212
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004214 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215 return mRecordTrack->start();
4216}
4217
4218void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004219 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004220 mRecordTrack->stop();
4221}
4222
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223status_t AudioFlinger::RecordHandle::onTransact(
4224 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4225{
4226 return BnAudioRecord::onTransact(code, data, reply, flags);
4227}
4228
4229// ----------------------------------------------------------------------------
4230
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004231AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4232 AudioStreamIn *input,
4233 uint32_t sampleRate,
4234 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004235 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004236 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004237 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004238 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4239 // mRsmpInIndex and mInputBytes set by readInputParameters()
4240 mReqChannelCount(popcount(channels)),
4241 mReqSampleRate(sampleRate)
4242 // mBytesRead is only meaningful while active, and so is cleared in start()
4243 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004245 snprintf(mName, kNameLength, "AudioIn_%d", id);
4246
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247 readInputParameters();
4248}
4249
4250
4251AudioFlinger::RecordThread::~RecordThread()
4252{
4253 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004254 delete mResampler;
4255 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256}
4257
4258void AudioFlinger::RecordThread::onFirstRef()
4259{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004260 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004261}
4262
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004263status_t AudioFlinger::RecordThread::readyToRun()
4264{
4265 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004266 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004267 return status;
4268}
4269
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270bool AudioFlinger::RecordThread::threadLoop()
4271{
4272 AudioBufferProvider::Buffer buffer;
4273 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004274 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275
Eric Laurent44d98482010-09-30 16:12:31 -07004276 nsecs_t lastWarning = 0;
4277
Eric Laurentfeb0db62011-07-22 09:04:31 -07004278 acquireWakeLock();
4279
Mathias Agopian65ab4712010-07-14 17:59:35 -07004280 // start recording
4281 while (!exitPending()) {
4282
4283 processConfigEvents();
4284
4285 { // scope for mLock
4286 Mutex::Autolock _l(mLock);
4287 checkForNewParameters_l();
4288 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4289 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004290 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 mStandby = true;
4292 }
4293
4294 if (exitPending()) break;
4295
Eric Laurentfeb0db62011-07-22 09:04:31 -07004296 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004297 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 // go to sleep
4299 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004300 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004301 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302 continue;
4303 }
4304 if (mActiveTrack != 0) {
4305 if (mActiveTrack->mState == TrackBase::PAUSING) {
4306 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004307 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004308 mStandby = true;
4309 }
4310 mActiveTrack.clear();
4311 mStartStopCond.broadcast();
4312 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4313 if (mReqChannelCount != mActiveTrack->channelCount()) {
4314 mActiveTrack.clear();
4315 mStartStopCond.broadcast();
4316 } else if (mBytesRead != 0) {
4317 // record start succeeds only if first read from audio input
4318 // succeeds
4319 if (mBytesRead > 0) {
4320 mActiveTrack->mState = TrackBase::ACTIVE;
4321 } else {
4322 mActiveTrack.clear();
4323 }
4324 mStartStopCond.broadcast();
4325 }
4326 mStandby = false;
4327 }
4328 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004329 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 }
4331
4332 if (mActiveTrack != 0) {
4333 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4334 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004335 unlockEffectChains(effectChains);
4336 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337 continue;
4338 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004339 for (size_t i = 0; i < effectChains.size(); i ++) {
4340 effectChains[i]->process_l();
4341 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004342
Mathias Agopian65ab4712010-07-14 17:59:35 -07004343 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004344 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004345 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004346 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 // no resampling
4348 while (framesOut) {
4349 size_t framesIn = mFrameCount - mRsmpInIndex;
4350 if (framesIn) {
4351 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4352 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4353 if (framesIn > framesOut)
4354 framesIn = framesOut;
4355 mRsmpInIndex += framesIn;
4356 framesOut -= framesIn;
4357 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004358 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 memcpy(dst, src, framesIn * mFrameSize);
4360 } else {
4361 int16_t *src16 = (int16_t *)src;
4362 int16_t *dst16 = (int16_t *)dst;
4363 if (mChannelCount == 1) {
4364 while (framesIn--) {
4365 *dst16++ = *src16;
4366 *dst16++ = *src16++;
4367 }
4368 } else {
4369 while (framesIn--) {
4370 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4371 src16 += 2;
4372 }
4373 }
4374 }
4375 }
4376 if (framesOut && mFrameCount == mRsmpInIndex) {
4377 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004378 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004379 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 framesOut = 0;
4381 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004382 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383 mRsmpInIndex = 0;
4384 }
4385 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004386 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4388 // Force input into standby so that it tries to
4389 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004390 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004391 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 }
4393 mRsmpInIndex = mFrameCount;
4394 framesOut = 0;
4395 buffer.frameCount = 0;
4396 }
4397 }
4398 }
4399 } else {
4400 // resampling
4401
4402 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4403 // alter output frame count as if we were expecting stereo samples
4404 if (mChannelCount == 1 && mReqChannelCount == 1) {
4405 framesOut >>= 1;
4406 }
4407 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4408 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4409 // are 32 bit aligned which should be always true.
4410 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004411 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412 // the resampler always outputs stereo samples: do post stereo to mono conversion
4413 int16_t *src = (int16_t *)mRsmpOutBuffer;
4414 int16_t *dst = buffer.i16;
4415 while (framesOut--) {
4416 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4417 src += 2;
4418 }
4419 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004420 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 }
4422
4423 }
4424 mActiveTrack->releaseBuffer(&buffer);
4425 mActiveTrack->overflow();
4426 }
4427 // client isn't retrieving buffers fast enough
4428 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004429 if (!mActiveTrack->setOverflow()) {
4430 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004431 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004432 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004433 lastWarning = now;
4434 }
4435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004436 // Release the processor for a while before asking for a new buffer.
4437 // This will give the application more chance to read from the buffer and
4438 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004439 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 }
4441 }
Eric Laurentec437d82011-07-26 20:54:46 -07004442 // enable changes in effect chain
4443 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004444 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 }
4446
4447 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004448 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450 mActiveTrack.clear();
4451
4452 mStartStopCond.broadcast();
4453
Eric Laurentfeb0db62011-07-22 09:04:31 -07004454 releaseWakeLock();
4455
Steve Block3856b092011-10-20 11:56:00 +01004456 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 return false;
4458}
4459
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004460
4461sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4462 const sp<AudioFlinger::Client>& client,
4463 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004464 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004465 int channelMask,
4466 int frameCount,
4467 uint32_t flags,
4468 int sessionId,
4469 status_t *status)
4470{
4471 sp<RecordTrack> track;
4472 status_t lStatus;
4473
4474 lStatus = initCheck();
4475 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004476 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004477 goto Exit;
4478 }
4479
4480 { // scope for mLock
4481 Mutex::Autolock _l(mLock);
4482
4483 track = new RecordTrack(this, client, sampleRate,
4484 format, channelMask, frameCount, flags, sessionId);
4485
Glenn Kasten7378ca52012-01-20 13:44:40 -08004486 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004487 lStatus = NO_MEMORY;
4488 goto Exit;
4489 }
4490
4491 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004492 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4493 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004494 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004495 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4496 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004497 }
4498 lStatus = NO_ERROR;
4499
4500Exit:
4501 if (status) {
4502 *status = lStatus;
4503 }
4504 return track;
4505}
4506
Mathias Agopian65ab4712010-07-14 17:59:35 -07004507status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4508{
Steve Block3856b092011-10-20 11:56:00 +01004509 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004510 sp <ThreadBase> strongMe = this;
4511 status_t status = NO_ERROR;
4512 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004513 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 if (mActiveTrack != 0) {
4515 if (recordTrack != mActiveTrack.get()) {
4516 status = -EBUSY;
4517 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4518 mActiveTrack->mState = TrackBase::ACTIVE;
4519 }
4520 return status;
4521 }
4522
4523 recordTrack->mState = TrackBase::IDLE;
4524 mActiveTrack = recordTrack;
4525 mLock.unlock();
4526 status_t status = AudioSystem::startInput(mId);
4527 mLock.lock();
4528 if (status != NO_ERROR) {
4529 mActiveTrack.clear();
4530 return status;
4531 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 mRsmpInIndex = mFrameCount;
4533 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004534 if (mResampler != NULL) {
4535 mResampler->reset();
4536 }
4537 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004539 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 mWaitWorkCV.signal();
4541 // do not wait for mStartStopCond if exiting
4542 if (mExiting) {
4543 mActiveTrack.clear();
4544 status = INVALID_OPERATION;
4545 goto startError;
4546 }
4547 mStartStopCond.wait(mLock);
4548 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004549 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 status = BAD_VALUE;
4551 goto startError;
4552 }
Steve Block3856b092011-10-20 11:56:00 +01004553 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554 return status;
4555 }
4556startError:
4557 AudioSystem::stopInput(mId);
4558 return status;
4559}
4560
4561void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004562 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004563 sp <ThreadBase> strongMe = this;
4564 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004565 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4567 mActiveTrack->mState = TrackBase::PAUSING;
4568 // do not wait for mStartStopCond if exiting
4569 if (mExiting) {
4570 return;
4571 }
4572 mStartStopCond.wait(mLock);
4573 // if we have been restarted, recordTrack == mActiveTrack.get() here
4574 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4575 mLock.unlock();
4576 AudioSystem::stopInput(mId);
4577 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004578 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004579 }
4580 }
4581 }
4582}
4583
4584status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4585{
4586 const size_t SIZE = 256;
4587 char buffer[SIZE];
4588 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589
4590 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4591 result.append(buffer);
4592
4593 if (mActiveTrack != 0) {
4594 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004595 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 mActiveTrack->dump(buffer, SIZE);
4597 result.append(buffer);
4598
4599 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4600 result.append(buffer);
4601 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4602 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004603 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 result.append(buffer);
4605 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4606 result.append(buffer);
4607 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4608 result.append(buffer);
4609
4610
4611 } else {
4612 result.append("No record client\n");
4613 }
4614 write(fd, result.string(), result.size());
4615
4616 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004617 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004618
4619 return NO_ERROR;
4620}
4621
4622status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4623{
4624 size_t framesReq = buffer->frameCount;
4625 size_t framesReady = mFrameCount - mRsmpInIndex;
4626 int channelCount;
4627
4628 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004629 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004631 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004632 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4633 // Force input into standby so that it tries to
4634 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004635 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004636 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004638 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004639 buffer->frameCount = 0;
4640 return NOT_ENOUGH_DATA;
4641 }
4642 mRsmpInIndex = 0;
4643 framesReady = mFrameCount;
4644 }
4645
4646 if (framesReq > framesReady) {
4647 framesReq = framesReady;
4648 }
4649
4650 if (mChannelCount == 1 && mReqChannelCount == 2) {
4651 channelCount = 1;
4652 } else {
4653 channelCount = 2;
4654 }
4655 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4656 buffer->frameCount = framesReq;
4657 return NO_ERROR;
4658}
4659
4660void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4661{
4662 mRsmpInIndex += buffer->frameCount;
4663 buffer->frameCount = 0;
4664}
4665
4666bool AudioFlinger::RecordThread::checkForNewParameters_l()
4667{
4668 bool reconfig = false;
4669
4670 while (!mNewParameters.isEmpty()) {
4671 status_t status = NO_ERROR;
4672 String8 keyValuePair = mNewParameters[0];
4673 AudioParameter param = AudioParameter(keyValuePair);
4674 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004675 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004676 int reqSamplingRate = mReqSampleRate;
4677 int reqChannelCount = mReqChannelCount;
4678
4679 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4680 reqSamplingRate = value;
4681 reconfig = true;
4682 }
4683 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004684 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685 reconfig = true;
4686 }
4687 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004688 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 reconfig = true;
4690 }
4691 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4692 // do not accept frame count changes if tracks are open as the track buffer
4693 // size depends on frame count and correct behavior would not be garantied
4694 // if frame count is changed after track creation
4695 if (mActiveTrack != 0) {
4696 status = INVALID_OPERATION;
4697 } else {
4698 reconfig = true;
4699 }
4700 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004701 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4702 // forward device change to effects that have requested to be
4703 // aware of attached audio device.
4704 for (size_t i = 0; i < mEffectChains.size(); i++) {
4705 mEffectChains[i]->setDevice_l(value);
4706 }
4707 // store input device and output device but do not forward output device to audio HAL.
4708 // Note that status is ignored by the caller for output device
4709 // (see AudioFlinger::setParameters()
4710 if (value & AUDIO_DEVICE_OUT_ALL) {
4711 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4712 status = BAD_VALUE;
4713 } else {
4714 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004715 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4716 if (mTrack != NULL) {
4717 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004718 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004719 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4720 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4721 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004722 }
4723 mDevice |= (uint32_t)value;
4724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004725 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004726 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004728 mInput->stream->common.standby(&mInput->stream->common);
4729 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730 }
4731 if (reconfig) {
4732 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004733 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004734 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004735 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4736 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004737 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004738 status = NO_ERROR;
4739 }
4740 if (status == NO_ERROR) {
4741 readInputParameters();
4742 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4743 }
4744 }
4745 }
4746
4747 mNewParameters.removeAt(0);
4748
4749 mParamStatus = status;
4750 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004751 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4752 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004753 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754 }
4755 return reconfig;
4756}
4757
4758String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4759{
Dima Zavinfce7a472011-04-19 22:30:36 -07004760 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004761 String8 out_s8 = String8();
4762
4763 Mutex::Autolock _l(mLock);
4764 if (initCheck() != NO_ERROR) {
4765 return out_s8;
4766 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004767
Dima Zavin799a70e2011-04-18 16:57:27 -07004768 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004769 out_s8 = String8(s);
4770 free(s);
4771 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772}
4773
4774void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4775 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004776 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777
4778 switch (event) {
4779 case AudioSystem::INPUT_OPENED:
4780 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004781 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004782 desc.samplingRate = mSampleRate;
4783 desc.format = mFormat;
4784 desc.frameCount = mFrameCount;
4785 desc.latency = 0;
4786 param2 = &desc;
4787 break;
4788
4789 case AudioSystem::INPUT_CLOSED:
4790 default:
4791 break;
4792 }
4793 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4794}
4795
4796void AudioFlinger::RecordThread::readInputParameters()
4797{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004798 delete mRsmpInBuffer;
4799 // mRsmpInBuffer is always assigned a new[] below
4800 delete mRsmpOutBuffer;
4801 mRsmpOutBuffer = NULL;
4802 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004803 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004804
Dima Zavin799a70e2011-04-18 16:57:27 -07004805 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004806 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4807 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004808 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004809 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004810 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811 mFrameCount = mInputBytes / mFrameSize;
4812 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4813
4814 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4815 {
4816 int channelCount;
4817 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4818 // stereo to mono post process as the resampler always outputs stereo.
4819 if (mChannelCount == 1 && mReqChannelCount == 2) {
4820 channelCount = 1;
4821 } else {
4822 channelCount = 2;
4823 }
4824 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4825 mResampler->setSampleRate(mSampleRate);
4826 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4827 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4828
4829 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4830 if (mChannelCount == 1 && mReqChannelCount == 1) {
4831 mFrameCount >>= 1;
4832 }
4833
4834 }
4835 mRsmpInIndex = mFrameCount;
4836}
4837
4838unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4839{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004840 Mutex::Autolock _l(mLock);
4841 if (initCheck() != NO_ERROR) {
4842 return 0;
4843 }
4844
Dima Zavin799a70e2011-04-18 16:57:27 -07004845 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004846}
4847
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004848uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4849{
4850 Mutex::Autolock _l(mLock);
4851 uint32_t result = 0;
4852 if (getEffectChain_l(sessionId) != 0) {
4853 result = EFFECT_SESSION;
4854 }
4855
4856 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4857 result |= TRACK_SESSION;
4858 }
4859
4860 return result;
4861}
4862
Eric Laurent59bd0da2011-08-01 09:52:20 -07004863AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4864{
4865 Mutex::Autolock _l(mLock);
4866 return mTrack;
4867}
4868
Glenn Kastenaed850d2012-01-26 09:46:34 -08004869AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004870{
4871 Mutex::Autolock _l(mLock);
4872 return mInput;
4873}
4874
4875AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4876{
4877 Mutex::Autolock _l(mLock);
4878 AudioStreamIn *input = mInput;
4879 mInput = NULL;
4880 return input;
4881}
4882
4883// this method must always be called either with ThreadBase mLock held or inside the thread loop
4884audio_stream_t* AudioFlinger::RecordThread::stream()
4885{
4886 if (mInput == NULL) {
4887 return NULL;
4888 }
4889 return &mInput->stream->common;
4890}
4891
4892
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893// ----------------------------------------------------------------------------
4894
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004895audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004896 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004897 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898 uint32_t *pChannels,
4899 uint32_t *pLatencyMs,
4900 uint32_t flags)
4901{
4902 status_t status;
4903 PlaybackThread *thread = NULL;
4904 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4905 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004906 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 uint32_t channels = pChannels ? *pChannels : 0;
4908 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004909 audio_stream_out_t *outStream;
4910 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004911
Steve Block3856b092011-10-20 11:56:00 +01004912 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 pDevices ? *pDevices : 0,
4914 samplingRate,
4915 format,
4916 channels,
4917 flags);
4918
4919 if (pDevices == NULL || *pDevices == 0) {
4920 return 0;
4921 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004922
Mathias Agopian65ab4712010-07-14 17:59:35 -07004923 Mutex::Autolock _l(mLock);
4924
Dima Zavin799a70e2011-04-18 16:57:27 -07004925 outHwDev = findSuitableHwDev_l(*pDevices);
4926 if (outHwDev == NULL)
4927 return 0;
4928
Glenn Kasten58f30212012-01-12 12:27:51 -08004929 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004930 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004931 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004932 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 samplingRate,
4934 format,
4935 channels,
4936 status);
4937
4938 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004939 if (outStream != NULL) {
4940 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004941 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004942
Dima Zavinfce7a472011-04-19 22:30:36 -07004943 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4944 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4945 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004946 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004947 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004948 } else {
4949 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004950 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 }
4952 mPlaybackThreads.add(id, thread);
4953
Glenn Kastena0d68332012-01-27 16:47:15 -08004954 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4955 if (pFormat != NULL) *pFormat = format;
4956 if (pChannels != NULL) *pChannels = channels;
4957 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958
4959 // notify client processes of the new output creation
4960 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4961 return id;
4962 }
4963
4964 return 0;
4965}
4966
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004967audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4968 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004969{
4970 Mutex::Autolock _l(mLock);
4971 MixerThread *thread1 = checkMixerThread_l(output1);
4972 MixerThread *thread2 = checkMixerThread_l(output2);
4973
4974 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004975 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976 return 0;
4977 }
4978
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004979 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4981 thread->addOutputTrack(thread2);
4982 mPlaybackThreads.add(id, thread);
4983 // notify client processes of the new output creation
4984 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4985 return id;
4986}
4987
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004988status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989{
4990 // keep strong reference on the playback thread so that
4991 // it is not destroyed while exit() is executed
4992 sp <PlaybackThread> thread;
4993 {
4994 Mutex::Autolock _l(mLock);
4995 thread = checkPlaybackThread_l(output);
4996 if (thread == NULL) {
4997 return BAD_VALUE;
4998 }
4999
Steve Block3856b092011-10-20 11:56:00 +01005000 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005002 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005004 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5006 dupThread->removeOutputTrack((MixerThread *)thread.get());
5007 }
5008 }
5009 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005010 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5012 mPlaybackThreads.removeItem(output);
5013 }
5014 thread->exit();
5015
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005016 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005017 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005018 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005019 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005020 out->hwDev->close_output_stream(out->hwDev, out->stream);
5021 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005022 }
5023 return NO_ERROR;
5024}
5025
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005026status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027{
5028 Mutex::Autolock _l(mLock);
5029 PlaybackThread *thread = checkPlaybackThread_l(output);
5030
5031 if (thread == NULL) {
5032 return BAD_VALUE;
5033 }
5034
Steve Block3856b092011-10-20 11:56:00 +01005035 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036 thread->suspend();
5037
5038 return NO_ERROR;
5039}
5040
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005041status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005042{
5043 Mutex::Autolock _l(mLock);
5044 PlaybackThread *thread = checkPlaybackThread_l(output);
5045
5046 if (thread == NULL) {
5047 return BAD_VALUE;
5048 }
5049
Steve Block3856b092011-10-20 11:56:00 +01005050 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051
5052 thread->restore();
5053
5054 return NO_ERROR;
5055}
5056
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005057audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005059 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005060 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005061 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062{
5063 status_t status;
5064 RecordThread *thread = NULL;
5065 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005066 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067 uint32_t channels = pChannels ? *pChannels : 0;
5068 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005069 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005071 audio_stream_in_t *inStream;
5072 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073
5074 if (pDevices == NULL || *pDevices == 0) {
5075 return 0;
5076 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005077
Mathias Agopian65ab4712010-07-14 17:59:35 -07005078 Mutex::Autolock _l(mLock);
5079
Dima Zavin799a70e2011-04-18 16:57:27 -07005080 inHwDev = findSuitableHwDev_l(*pDevices);
5081 if (inHwDev == NULL)
5082 return 0;
5083
Glenn Kasten58f30212012-01-12 12:27:51 -08005084 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005085 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005086 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005087 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005088 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 samplingRate,
5091 format,
5092 channels,
5093 acoustics,
5094 status);
5095
5096 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5097 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5098 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005099 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005100 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005101 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005102 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005103 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005104 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005105 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005106 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005107 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 }
5109
Dima Zavin799a70e2011-04-18 16:57:27 -07005110 if (inStream != NULL) {
5111 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5112
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005113 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005114 // Start record thread
5115 // RecorThread require both input and output device indication to forward to audio
5116 // pre processing modules
5117 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5118 thread = new RecordThread(this,
5119 input,
5120 reqSamplingRate,
5121 reqChannels,
5122 id,
5123 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005124 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005125 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005126 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5127 if (pFormat != NULL) *pFormat = format;
5128 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129
Dima Zavin799a70e2011-04-18 16:57:27 -07005130 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005131
5132 // notify client processes of the new input creation
5133 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5134 return id;
5135 }
5136
5137 return 0;
5138}
5139
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005140status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005141{
5142 // keep strong reference on the record thread so that
5143 // it is not destroyed while exit() is executed
5144 sp <RecordThread> thread;
5145 {
5146 Mutex::Autolock _l(mLock);
5147 thread = checkRecordThread_l(input);
5148 if (thread == NULL) {
5149 return BAD_VALUE;
5150 }
5151
Steve Block3856b092011-10-20 11:56:00 +01005152 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005153 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5155 mRecordThreads.removeItem(input);
5156 }
5157 thread->exit();
5158
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005159 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005160 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005161 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005162 in->hwDev->close_input_stream(in->hwDev, in->stream);
5163 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164
5165 return NO_ERROR;
5166}
5167
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005168status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169{
5170 Mutex::Autolock _l(mLock);
5171 MixerThread *dstThread = checkMixerThread_l(output);
5172 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005173 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 return BAD_VALUE;
5175 }
5176
Steve Block3856b092011-10-20 11:56:00 +01005177 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5179
Eric Laurent9f6530f2011-08-30 10:18:54 -07005180 dstThread->setStreamValid(stream, true);
5181
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5183 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5184 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005185 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005187 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189 }
Eric Laurentde070132010-07-13 04:45:46 -07005190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191
5192 return NO_ERROR;
5193}
5194
5195
5196int AudioFlinger::newAudioSessionId()
5197{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005198 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199}
5200
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005201void AudioFlinger::acquireAudioSessionId(int audioSession)
5202{
5203 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005204 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005205 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005206 int num = mAudioSessionRefs.size();
5207 for (int i = 0; i< num; i++) {
5208 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5209 if (ref->sessionid == audioSession && ref->pid == caller) {
5210 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005211 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005212 return;
5213 }
5214 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005215 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5216 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005217}
5218
5219void AudioFlinger::releaseAudioSessionId(int audioSession)
5220{
5221 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005222 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005223 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005224 int num = mAudioSessionRefs.size();
5225 for (int i = 0; i< num; i++) {
5226 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5227 if (ref->sessionid == audioSession && ref->pid == caller) {
5228 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005229 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005230 if (ref->cnt == 0) {
5231 mAudioSessionRefs.removeAt(i);
5232 delete ref;
5233 purgeStaleEffects_l();
5234 }
5235 return;
5236 }
5237 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005238 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005239}
5240
5241void AudioFlinger::purgeStaleEffects_l() {
5242
Steve Block3856b092011-10-20 11:56:00 +01005243 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005244
5245 Vector< sp<EffectChain> > chains;
5246
5247 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5248 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5249 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5250 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005251 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5252 chains.push(ec);
5253 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005254 }
5255 }
5256 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5257 sp<RecordThread> t = mRecordThreads.valueAt(i);
5258 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5259 sp<EffectChain> ec = t->mEffectChains[j];
5260 chains.push(ec);
5261 }
5262 }
5263
5264 for (size_t i = 0; i < chains.size(); i++) {
5265 sp<EffectChain> ec = chains[i];
5266 int sessionid = ec->sessionId();
5267 sp<ThreadBase> t = ec->mThread.promote();
5268 if (t == 0) {
5269 continue;
5270 }
5271 size_t numsessionrefs = mAudioSessionRefs.size();
5272 bool found = false;
5273 for (size_t k = 0; k < numsessionrefs; k++) {
5274 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5275 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005276 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005277 sessionid, ref->pid, ref->cnt);
5278 found = true;
5279 break;
5280 }
5281 }
5282 if (!found) {
5283 // remove all effects from the chain
5284 while (ec->mEffects.size()) {
5285 sp<EffectModule> effect = ec->mEffects[0];
5286 effect->unPin();
5287 Mutex::Autolock _l (t->mLock);
5288 t->removeEffect_l(effect);
5289 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5290 sp<EffectHandle> handle = effect->mHandles[j].promote();
5291 if (handle != 0) {
5292 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005293 if (handle->mHasControl && handle->mEnabled) {
5294 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5295 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005296 }
5297 }
5298 AudioSystem::unregisterEffect(effect->id());
5299 }
5300 }
5301 }
5302 return;
5303}
5304
Mathias Agopian65ab4712010-07-14 17:59:35 -07005305// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005306AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307{
5308 PlaybackThread *thread = NULL;
5309 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5310 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5311 }
5312 return thread;
5313}
5314
5315// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005316AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317{
5318 PlaybackThread *thread = checkPlaybackThread_l(output);
5319 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005320 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321 thread = NULL;
5322 }
5323 }
5324 return (MixerThread *)thread;
5325}
5326
5327// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005328AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329{
5330 RecordThread *thread = NULL;
5331 if (mRecordThreads.indexOfKey(input) >= 0) {
5332 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5333 }
5334 return thread;
5335}
5336
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005337uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005338{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005339 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005340}
5341
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005342AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5343{
5344 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5345 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005346 AudioStreamOut *output = thread->getOutput();
5347 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005348 return thread;
5349 }
5350 }
5351 return NULL;
5352}
5353
5354uint32_t AudioFlinger::primaryOutputDevice_l()
5355{
5356 PlaybackThread *thread = primaryPlaybackThread_l();
5357
5358 if (thread == NULL) {
5359 return 0;
5360 }
5361
5362 return thread->device();
5363}
5364
5365
Mathias Agopian65ab4712010-07-14 17:59:35 -07005366// ----------------------------------------------------------------------------
5367// Effect management
5368// ----------------------------------------------------------------------------
5369
5370
Glenn Kastenf587ba52012-01-26 16:25:10 -08005371status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372{
5373 Mutex::Autolock _l(mLock);
5374 return EffectQueryNumberEffects(numEffects);
5375}
5376
Glenn Kastenf587ba52012-01-26 16:25:10 -08005377status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378{
5379 Mutex::Autolock _l(mLock);
5380 return EffectQueryEffect(index, descriptor);
5381}
5382
Glenn Kasten5e92a782012-01-30 07:40:52 -08005383status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005384 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385{
5386 Mutex::Autolock _l(mLock);
5387 return EffectGetDescriptor(pUuid, descriptor);
5388}
5389
5390
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5392 effect_descriptor_t *pDesc,
5393 const sp<IEffectClient>& effectClient,
5394 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005395 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 int sessionId,
5397 status_t *status,
5398 int *id,
5399 int *enabled)
5400{
5401 status_t lStatus = NO_ERROR;
5402 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005405 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005406 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407
5408 if (pDesc == NULL) {
5409 lStatus = BAD_VALUE;
5410 goto Exit;
5411 }
5412
Eric Laurent84e9a102010-09-23 16:10:16 -07005413 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005414 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005415 lStatus = PERMISSION_DENIED;
5416 goto Exit;
5417 }
5418
Dima Zavinfce7a472011-04-19 22:30:36 -07005419 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005420 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 lStatus = PERMISSION_DENIED;
5423 goto Exit;
5424 }
5425
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005426 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005427 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005428 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005429 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005430 lStatus = BAD_VALUE;
5431 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005432 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005433 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005434 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005435 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005436 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005437 }
5438 }
5439
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 {
5441 Mutex::Autolock _l(mLock);
5442
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443
5444 if (!EffectIsNullUuid(&pDesc->uuid)) {
5445 // if uuid is specified, request effect descriptor
5446 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5447 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005448 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 goto Exit;
5450 }
5451 } else {
5452 // if uuid is not specified, look for an available implementation
5453 // of the required type in effect factory
5454 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005455 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 lStatus = BAD_VALUE;
5457 goto Exit;
5458 }
5459 uint32_t numEffects = 0;
5460 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005461 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 bool found = false;
5463
5464 lStatus = EffectQueryNumberEffects(&numEffects);
5465 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005466 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467 goto Exit;
5468 }
5469 for (uint32_t i = 0; i < numEffects; i++) {
5470 lStatus = EffectQueryEffect(i, &desc);
5471 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005472 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 continue;
5474 }
5475 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5476 // If matching type found save effect descriptor. If the session is
5477 // 0 and the effect is not auxiliary, continue enumeration in case
5478 // an auxiliary version of this effect type is available
5479 found = true;
5480 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005481 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5483 break;
5484 }
5485 }
5486 }
5487 if (!found) {
5488 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005489 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005490 goto Exit;
5491 }
5492 // For same effect type, chose auxiliary version over insert version if
5493 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005494 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5496 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5497 }
5498 }
5499
5500 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005501 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005502 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5503 lStatus = INVALID_OPERATION;
5504 goto Exit;
5505 }
5506
Eric Laurent59255e42011-07-27 19:49:51 -07005507 // check recording permission for visualizer
5508 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5509 !recordingAllowed()) {
5510 lStatus = PERMISSION_DENIED;
5511 goto Exit;
5512 }
5513
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 // return effect descriptor
5515 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5516
5517 // If output is not specified try to find a matching audio session ID in one of the
5518 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005519 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5520 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005521 // Note: io is never 0 when creating an effect on an input
5522 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005523 // look for the thread where the specified audio session is present
5524 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5525 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005526 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005527 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005530 if (io == 0) {
5531 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5532 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5533 io = mRecordThreads.keyAt(i);
5534 break;
5535 }
5536 }
5537 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005538 // If no output thread contains the requested session ID, default to
5539 // first output. The effect chain will be moved to the correct output
5540 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005541 if (io == 0 && mPlaybackThreads.size()) {
5542 io = mPlaybackThreads.keyAt(0);
5543 }
Steve Block3856b092011-10-20 11:56:00 +01005544 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005545 }
5546 ThreadBase *thread = checkRecordThread_l(io);
5547 if (thread == NULL) {
5548 thread = checkPlaybackThread_l(io);
5549 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005550 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005551 lStatus = BAD_VALUE;
5552 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005553 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005555
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005556 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005558 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005559 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5560 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 if (handle != 0 && id != NULL) {
5562 *id = handle->id();
5563 }
5564 }
5565
5566Exit:
5567 if(status) {
5568 *status = lStatus;
5569 }
5570 return handle;
5571}
5572
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005573status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5574 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005575{
Steve Block3856b092011-10-20 11:56:00 +01005576 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005577 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005578 Mutex::Autolock _l(mLock);
5579 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005580 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005581 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 }
Eric Laurentde070132010-07-13 04:45:46 -07005583 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5584 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005585 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005586 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 }
Eric Laurentde070132010-07-13 04:45:46 -07005588 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5589 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005590 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005591 return BAD_VALUE;
5592 }
5593
5594 Mutex::Autolock _dl(dstThread->mLock);
5595 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005596 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005597
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 return NO_ERROR;
5599}
5600
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005601// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005602status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005603 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005604 AudioFlinger::PlaybackThread *dstThread,
5605 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005606{
Steve Block3856b092011-10-20 11:56:00 +01005607 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005608 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005609
Eric Laurent59255e42011-07-27 19:49:51 -07005610 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005611 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005612 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005613 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005614 return INVALID_OPERATION;
5615 }
5616
Eric Laurent39e94f82010-07-28 01:32:47 -07005617 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005618 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005619 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005620 // removed.
5621 srcThread->removeEffectChain_l(chain);
5622
5623 // transfer all effects one by one so that new effect chain is created on new thread with
5624 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005625 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005626 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005627 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005628 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5629 while (effect != 0) {
5630 srcThread->removeEffect_l(effect);
5631 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005632 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5633 if (effect->state() == EffectModule::ACTIVE ||
5634 effect->state() == EffectModule::STOPPING) {
5635 effect->start();
5636 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005637 // if the move request is not received from audio policy manager, the effect must be
5638 // re-registered with the new strategy and output
5639 if (dstChain == 0) {
5640 dstChain = effect->chain().promote();
5641 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005642 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005643 srcThread->addEffect_l(effect);
5644 return NO_INIT;
5645 }
5646 strategy = dstChain->strategy();
5647 }
5648 if (reRegister) {
5649 AudioSystem::unregisterEffect(effect->id());
5650 AudioSystem::registerEffect(&effect->desc(),
5651 dstOutput,
5652 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005653 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005654 effect->id());
5655 }
Eric Laurentde070132010-07-13 04:45:46 -07005656 effect = chain->getEffectFromId_l(0);
5657 }
5658
5659 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660}
5661
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005662
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005664sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005665 const sp<AudioFlinger::Client>& client,
5666 const sp<IEffectClient>& effectClient,
5667 int32_t priority,
5668 int sessionId,
5669 effect_descriptor_t *desc,
5670 int *enabled,
5671 status_t *status
5672 )
5673{
5674 sp<EffectModule> effect;
5675 sp<EffectHandle> handle;
5676 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005678 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 bool effectCreated = false;
5680 bool effectRegistered = false;
5681
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005682 lStatus = initCheck();
5683 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005684 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 goto Exit;
5686 }
5687
5688 // Do not allow effects with session ID 0 on direct output or duplicating threads
5689 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005690 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005691 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005692 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 lStatus = BAD_VALUE;
5694 goto Exit;
5695 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005696 // Only Pre processor effects are allowed on input threads and only on input threads
5697 if ((mType == RECORD &&
5698 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5699 (mType != RECORD &&
5700 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005701 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005702 desc->name, desc->flags, mType);
5703 lStatus = BAD_VALUE;
5704 goto Exit;
5705 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005706
Steve Block3856b092011-10-20 11:56:00 +01005707 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708
5709 { // scope for mLock
5710 Mutex::Autolock _l(mLock);
5711
5712 // check for existing effect chain with the requested audio session
5713 chain = getEffectChain_l(sessionId);
5714 if (chain == 0) {
5715 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005716 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 chain = new EffectChain(this, sessionId);
5718 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005719 chain->setStrategy(getStrategyForSession_l(sessionId));
5720 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005722 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 }
5724
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005725 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726
5727 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005728 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005730 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731 if (lStatus != NO_ERROR) {
5732 goto Exit;
5733 }
5734 effectRegistered = true;
5735 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005736 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 lStatus = effect->status();
5738 if (lStatus != NO_ERROR) {
5739 goto Exit;
5740 }
Eric Laurentcab11242010-07-15 12:50:15 -07005741 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 if (lStatus != NO_ERROR) {
5743 goto Exit;
5744 }
5745 effectCreated = true;
5746
5747 effect->setDevice(mDevice);
5748 effect->setMode(mAudioFlinger->getMode());
5749 }
5750 // create effect handle and connect it to effect module
5751 handle = new EffectHandle(effect, client, effectClient, priority);
5752 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005753 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 *enabled = (int)effect->isEnabled();
5755 }
5756 }
5757
5758Exit:
5759 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005760 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005762 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005763 }
5764 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005765 AudioSystem::unregisterEffect(effect->id());
5766 }
5767 if (chainCreated) {
5768 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 }
5770 handle.clear();
5771 }
5772
5773 if(status) {
5774 *status = lStatus;
5775 }
5776 return handle;
5777}
5778
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005779sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5780{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005781 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005782 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005783}
5784
Eric Laurentde070132010-07-13 04:45:46 -07005785// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5786// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005787status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005788{
5789 // check for existing effect chain with the requested audio session
5790 int sessionId = effect->sessionId();
5791 sp<EffectChain> chain = getEffectChain_l(sessionId);
5792 bool chainCreated = false;
5793
5794 if (chain == 0) {
5795 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005796 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005797 chain = new EffectChain(this, sessionId);
5798 addEffectChain_l(chain);
5799 chain->setStrategy(getStrategyForSession_l(sessionId));
5800 chainCreated = true;
5801 }
Steve Block3856b092011-10-20 11:56:00 +01005802 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005803
5804 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005805 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005806 this, effect->desc().name, chain.get());
5807 return BAD_VALUE;
5808 }
5809
5810 status_t status = chain->addEffect_l(effect);
5811 if (status != NO_ERROR) {
5812 if (chainCreated) {
5813 removeEffectChain_l(chain);
5814 }
5815 return status;
5816 }
5817
5818 effect->setDevice(mDevice);
5819 effect->setMode(mAudioFlinger->getMode());
5820 return NO_ERROR;
5821}
5822
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005823void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005824
Steve Block3856b092011-10-20 11:56:00 +01005825 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005827 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5828 detachAuxEffect_l(effect->id());
5829 }
5830
5831 sp<EffectChain> chain = effect->chain().promote();
5832 if (chain != 0) {
5833 // remove effect chain if removing last effect
5834 if (chain->removeEffect_l(effect) == 0) {
5835 removeEffectChain_l(chain);
5836 }
5837 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005838 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005839 }
5840}
5841
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005842void AudioFlinger::ThreadBase::lockEffectChains_l(
5843 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5844{
5845 effectChains = mEffectChains;
5846 for (size_t i = 0; i < mEffectChains.size(); i++) {
5847 mEffectChains[i]->lock();
5848 }
5849}
5850
5851void AudioFlinger::ThreadBase::unlockEffectChains(
5852 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5853{
5854 for (size_t i = 0; i < effectChains.size(); i++) {
5855 effectChains[i]->unlock();
5856 }
5857}
5858
5859sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5860{
5861 Mutex::Autolock _l(mLock);
5862 return getEffectChain_l(sessionId);
5863}
5864
5865sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5866{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005867 size_t size = mEffectChains.size();
5868 for (size_t i = 0; i < size; i++) {
5869 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005870 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005871 }
5872 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005873 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005874}
5875
Glenn Kastenf78aee72012-01-04 11:00:47 -08005876void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005877{
5878 Mutex::Autolock _l(mLock);
5879 size_t size = mEffectChains.size();
5880 for (size_t i = 0; i < size; i++) {
5881 mEffectChains[i]->setMode_l(mode);
5882 }
5883}
5884
5885void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005886 const wp<EffectHandle>& handle,
5887 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005888
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005890 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891 // delete the effect module if removing last handle on it
5892 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005893 if (!effect->isPinned() || unpiniflast) {
5894 removeEffect_l(effect);
5895 AudioSystem::unregisterEffect(effect->id());
5896 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 }
5898}
5899
5900status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5901{
5902 int session = chain->sessionId();
5903 int16_t *buffer = mMixBuffer;
5904 bool ownsBuffer = false;
5905
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 if (session > 0) {
5908 // Only one effect chain can be present in direct output thread and it uses
5909 // the mix buffer as input
5910 if (mType != DIRECT) {
5911 size_t numSamples = mFrameCount * mChannelCount;
5912 buffer = new int16_t[numSamples];
5913 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 ownsBuffer = true;
5916 }
5917
5918 // Attach all tracks with same session ID to this chain.
5919 for (size_t i = 0; i < mTracks.size(); ++i) {
5920 sp<Track> track = mTracks[i];
5921 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005922 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005924 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 }
5926 }
5927
5928 // indicate all active tracks in the chain
5929 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5930 sp<Track> track = mActiveTracks[i].promote();
5931 if (track == 0) continue;
5932 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005933 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005934 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935 }
5936 }
5937 }
5938
5939 chain->setInBuffer(buffer, ownsBuffer);
5940 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005941 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005942 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005943 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5944 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005946 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5947 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005948 // Effect chain for other sessions are inserted at beginning of effect
5949 // chains list to be processed before output mix effects. Relative order between other
5950 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 size_t size = mEffectChains.size();
5952 size_t i = 0;
5953 for (i = 0; i < size; i++) {
5954 if (mEffectChains[i]->sessionId() < session) break;
5955 }
5956 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005957 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958
5959 return NO_ERROR;
5960}
5961
5962size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5963{
5964 int session = chain->sessionId();
5965
Steve Block3856b092011-10-20 11:56:00 +01005966 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967
5968 for (size_t i = 0; i < mEffectChains.size(); i++) {
5969 if (chain == mEffectChains[i]) {
5970 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005971 // detach all active tracks from the chain
5972 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5973 sp<Track> track = mActiveTracks[i].promote();
5974 if (track == 0) continue;
5975 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005976 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005977 chain.get(), session);
5978 chain->decActiveTrackCnt();
5979 }
5980 }
5981
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 // detach all tracks with same session ID from this chain
5983 for (size_t i = 0; i < mTracks.size(); ++i) {
5984 sp<Track> track = mTracks[i];
5985 if (session == track->sessionId()) {
5986 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005987 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988 }
5989 }
Eric Laurentde070132010-07-13 04:45:46 -07005990 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 }
5992 }
5993 return mEffectChains.size();
5994}
5995
Eric Laurentde070132010-07-13 04:45:46 -07005996status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5997 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998{
5999 Mutex::Autolock _l(mLock);
6000 return attachAuxEffect_l(track, EffectId);
6001}
6002
Eric Laurentde070132010-07-13 04:45:46 -07006003status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6004 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005{
6006 status_t status = NO_ERROR;
6007
6008 if (EffectId == 0) {
6009 track->setAuxBuffer(0, NULL);
6010 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006011 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6012 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 if (effect != 0) {
6014 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6015 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6016 } else {
6017 status = INVALID_OPERATION;
6018 }
6019 } else {
6020 status = BAD_VALUE;
6021 }
6022 }
6023 return status;
6024}
6025
6026void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6027{
6028 for (size_t i = 0; i < mTracks.size(); ++i) {
6029 sp<Track> track = mTracks[i];
6030 if (track->auxEffectId() == effectId) {
6031 attachAuxEffect_l(track, 0);
6032 }
6033 }
6034}
6035
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6037{
6038 // only one chain per input thread
6039 if (mEffectChains.size() != 0) {
6040 return INVALID_OPERATION;
6041 }
Steve Block3856b092011-10-20 11:56:00 +01006042 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006043
6044 chain->setInBuffer(NULL);
6045 chain->setOutBuffer(NULL);
6046
Eric Laurent59255e42011-07-27 19:49:51 -07006047 checkSuspendOnAddEffectChain_l(chain);
6048
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049 mEffectChains.add(chain);
6050
6051 return NO_ERROR;
6052}
6053
6054size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6055{
Steve Block3856b092011-10-20 11:56:00 +01006056 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006057 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006058 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6059 chain.get(), mEffectChains.size(), this);
6060 if (mEffectChains.size() == 1) {
6061 mEffectChains.removeAt(0);
6062 }
6063 return 0;
6064}
6065
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066// ----------------------------------------------------------------------------
6067// EffectModule implementation
6068// ----------------------------------------------------------------------------
6069
6070#undef LOG_TAG
6071#define LOG_TAG "AudioFlinger::EffectModule"
6072
6073AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6074 const wp<AudioFlinger::EffectChain>& chain,
6075 effect_descriptor_t *desc,
6076 int id,
6077 int sessionId)
6078 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006079 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080{
Steve Block3856b092011-10-20 11:56:00 +01006081 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 int lStatus;
6083 sp<ThreadBase> thread = mThread.promote();
6084 if (thread == 0) {
6085 return;
6086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087
6088 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6089
6090 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006091 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092
6093 if (mStatus != NO_ERROR) {
6094 return;
6095 }
6096 lStatus = init();
6097 if (lStatus < 0) {
6098 mStatus = lStatus;
6099 goto Error;
6100 }
6101
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006102 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6103 mPinned = true;
6104 }
Steve Block3856b092011-10-20 11:56:00 +01006105 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 return;
6107Error:
6108 EffectRelease(mEffectInterface);
6109 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006110 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111}
6112
6113AudioFlinger::EffectModule::~EffectModule()
6114{
Steve Block3856b092011-10-20 11:56:00 +01006115 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6118 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6119 sp<ThreadBase> thread = mThread.promote();
6120 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006121 audio_stream_t *stream = thread->stream();
6122 if (stream != NULL) {
6123 stream->remove_audio_effect(stream, mEffectInterface);
6124 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006125 }
6126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 // release effect engine
6128 EffectRelease(mEffectInterface);
6129 }
6130}
6131
Glenn Kasten435dbe62012-01-30 10:15:48 -08006132status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133{
6134 status_t status;
6135
6136 Mutex::Autolock _l(mLock);
6137 // First handle in mHandles has highest priority and controls the effect module
6138 int priority = handle->priority();
6139 size_t size = mHandles.size();
6140 sp<EffectHandle> h;
6141 size_t i;
6142 for (i = 0; i < size; i++) {
6143 h = mHandles[i].promote();
6144 if (h == 0) continue;
6145 if (h->priority() <= priority) break;
6146 }
6147 // if inserted in first place, move effect control from previous owner to this handle
6148 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006149 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006151 enabled = h->enabled();
6152 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 }
Eric Laurent59255e42011-07-27 19:49:51 -07006154 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 status = NO_ERROR;
6156 } else {
6157 status = ALREADY_EXISTS;
6158 }
Steve Block3856b092011-10-20 11:56:00 +01006159 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 mHandles.insertAt(handle, i);
6161 return status;
6162}
6163
6164size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6165{
6166 Mutex::Autolock _l(mLock);
6167 size_t size = mHandles.size();
6168 size_t i;
6169 for (i = 0; i < size; i++) {
6170 if (mHandles[i] == handle) break;
6171 }
6172 if (i == size) {
6173 return size;
6174 }
Steve Block3856b092011-10-20 11:56:00 +01006175 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006176
6177 bool enabled = false;
6178 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006179 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006180 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006181 enabled = hdl->enabled();
6182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 mHandles.removeAt(i);
6184 size = mHandles.size();
6185 // if removed from first place, move effect control from this handle to next in line
6186 if (i == 0 && size != 0) {
6187 sp<EffectHandle> h = mHandles[0].promote();
6188 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006189 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 }
6191 }
6192
Eric Laurentec437d82011-07-26 20:54:46 -07006193 // Prevent calls to process() and other functions on effect interface from now on.
6194 // The effect engine will be released by the destructor when the last strong reference on
6195 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006196 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006197 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006198 }
6199
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 return size;
6201}
6202
Eric Laurent59255e42011-07-27 19:49:51 -07006203sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6204{
6205 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006206 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006207}
6208
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006209void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210{
Steve Block3856b092011-10-20 11:56:00 +01006211 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 // keep a strong reference on this EffectModule to avoid calling the
6213 // destructor before we exit
6214 sp<EffectModule> keep(this);
6215 {
6216 sp<ThreadBase> thread = mThread.promote();
6217 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006218 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 }
6220 }
6221}
6222
6223void AudioFlinger::EffectModule::updateState() {
6224 Mutex::Autolock _l(mLock);
6225
6226 switch (mState) {
6227 case RESTART:
6228 reset_l();
6229 // FALL THROUGH
6230
6231 case STARTING:
6232 // clear auxiliary effect input buffer for next accumulation
6233 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6234 memset(mConfig.inputCfg.buffer.raw,
6235 0,
6236 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6237 }
6238 start_l();
6239 mState = ACTIVE;
6240 break;
6241 case STOPPING:
6242 stop_l();
6243 mDisableWaitCnt = mMaxDisableWaitCnt;
6244 mState = STOPPED;
6245 break;
6246 case STOPPED:
6247 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6248 // turn off sequence.
6249 if (--mDisableWaitCnt == 0) {
6250 reset_l();
6251 mState = IDLE;
6252 }
6253 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006254 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 break;
6256 }
6257}
6258
6259void AudioFlinger::EffectModule::process()
6260{
6261 Mutex::Autolock _l(mLock);
6262
Eric Laurentec437d82011-07-26 20:54:46 -07006263 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 mConfig.inputCfg.buffer.raw == NULL ||
6265 mConfig.outputCfg.buffer.raw == NULL) {
6266 return;
6267 }
6268
Eric Laurent8f45bd72010-08-31 13:50:07 -07006269 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6271 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006272 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006274 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 }
6276
6277 // do the actual processing in the effect engine
6278 int ret = (*mEffectInterface)->process(mEffectInterface,
6279 &mConfig.inputCfg.buffer,
6280 &mConfig.outputCfg.buffer);
6281
6282 // force transition to IDLE state when engine is ready
6283 if (mState == STOPPED && ret == -ENODATA) {
6284 mDisableWaitCnt = 1;
6285 }
6286
6287 // clear auxiliary effect input buffer for next accumulation
6288 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006289 memset(mConfig.inputCfg.buffer.raw, 0,
6290 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 }
6292 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006293 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6294 // If an insert effect is idle and input buffer is different from output buffer,
6295 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006297 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006298 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6299 int16_t *in = mConfig.inputCfg.buffer.s16;
6300 int16_t *out = mConfig.outputCfg.buffer.s16;
6301 for (size_t i = 0; i < frameCnt; i++) {
6302 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 }
6305 }
6306}
6307
6308void AudioFlinger::EffectModule::reset_l()
6309{
6310 if (mEffectInterface == NULL) {
6311 return;
6312 }
6313 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6314}
6315
6316status_t AudioFlinger::EffectModule::configure()
6317{
6318 uint32_t channels;
6319 if (mEffectInterface == NULL) {
6320 return NO_INIT;
6321 }
6322
6323 sp<ThreadBase> thread = mThread.promote();
6324 if (thread == 0) {
6325 return DEAD_OBJECT;
6326 }
6327
6328 // TODO: handle configuration of effects replacing track process
6329 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006330 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006331 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006332 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333 }
6334
6335 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006336 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337 } else {
6338 mConfig.inputCfg.channels = channels;
6339 }
6340 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006341 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6342 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 mConfig.inputCfg.samplingRate = thread->sampleRate();
6344 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6345 mConfig.inputCfg.bufferProvider.cookie = NULL;
6346 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6347 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6348 mConfig.outputCfg.bufferProvider.cookie = NULL;
6349 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6350 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6351 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6352 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006353 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006354 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006355 // - in other sessions:
6356 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6357 // other effect: overwrites output buffer: input buffer == output buffer
6358 // Auxiliary effect:
6359 // accumulates in output buffer: input buffer != output buffer
6360 // Therefore: accumulate <=> input buffer != output buffer
6361 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6362 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6363 } else {
6364 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6365 }
6366 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6367 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6368 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6369 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6370
Steve Block3856b092011-10-20 11:56:00 +01006371 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006372 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6373
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006375 uint32_t size = sizeof(int);
6376 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006377 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006378 sizeof(effect_config_t),
6379 &mConfig,
6380 &size,
6381 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006382 if (status == 0) {
6383 status = cmdStatus;
6384 }
6385
6386 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6387 (1000 * mConfig.outputCfg.buffer.frameCount);
6388
6389 return status;
6390}
6391
6392status_t AudioFlinger::EffectModule::init()
6393{
6394 Mutex::Autolock _l(mLock);
6395 if (mEffectInterface == NULL) {
6396 return NO_INIT;
6397 }
6398 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006399 uint32_t size = sizeof(status_t);
6400 status_t status = (*mEffectInterface)->command(mEffectInterface,
6401 EFFECT_CMD_INIT,
6402 0,
6403 NULL,
6404 &size,
6405 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 if (status == 0) {
6407 status = cmdStatus;
6408 }
6409 return status;
6410}
6411
Eric Laurentec35a142011-10-05 17:42:25 -07006412status_t AudioFlinger::EffectModule::start()
6413{
6414 Mutex::Autolock _l(mLock);
6415 return start_l();
6416}
6417
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418status_t AudioFlinger::EffectModule::start_l()
6419{
6420 if (mEffectInterface == NULL) {
6421 return NO_INIT;
6422 }
6423 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006424 uint32_t size = sizeof(status_t);
6425 status_t status = (*mEffectInterface)->command(mEffectInterface,
6426 EFFECT_CMD_ENABLE,
6427 0,
6428 NULL,
6429 &size,
6430 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431 if (status == 0) {
6432 status = cmdStatus;
6433 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006434 if (status == 0 &&
6435 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6436 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6437 sp<ThreadBase> thread = mThread.promote();
6438 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006439 audio_stream_t *stream = thread->stream();
6440 if (stream != NULL) {
6441 stream->add_audio_effect(stream, mEffectInterface);
6442 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006443 }
6444 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006445 return status;
6446}
6447
Eric Laurentec437d82011-07-26 20:54:46 -07006448status_t AudioFlinger::EffectModule::stop()
6449{
6450 Mutex::Autolock _l(mLock);
6451 return stop_l();
6452}
6453
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454status_t AudioFlinger::EffectModule::stop_l()
6455{
6456 if (mEffectInterface == NULL) {
6457 return NO_INIT;
6458 }
6459 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006460 uint32_t size = sizeof(status_t);
6461 status_t status = (*mEffectInterface)->command(mEffectInterface,
6462 EFFECT_CMD_DISABLE,
6463 0,
6464 NULL,
6465 &size,
6466 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 if (status == 0) {
6468 status = cmdStatus;
6469 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006470 if (status == 0 &&
6471 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6472 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6473 sp<ThreadBase> thread = mThread.promote();
6474 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006475 audio_stream_t *stream = thread->stream();
6476 if (stream != NULL) {
6477 stream->remove_audio_effect(stream, mEffectInterface);
6478 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006479 }
6480 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 return status;
6482}
6483
Eric Laurent25f43952010-07-28 05:40:18 -07006484status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6485 uint32_t cmdSize,
6486 void *pCmdData,
6487 uint32_t *replySize,
6488 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489{
6490 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006491// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492
Eric Laurentec437d82011-07-26 20:54:46 -07006493 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 return NO_INIT;
6495 }
Eric Laurent25f43952010-07-28 05:40:18 -07006496 status_t status = (*mEffectInterface)->command(mEffectInterface,
6497 cmdCode,
6498 cmdSize,
6499 pCmdData,
6500 replySize,
6501 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006502 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006503 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 for (size_t i = 1; i < mHandles.size(); i++) {
6505 sp<EffectHandle> h = mHandles[i].promote();
6506 if (h != 0) {
6507 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6508 }
6509 }
6510 }
6511 return status;
6512}
6513
6514status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6515{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006516
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006518 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006519
6520 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006521 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6522 if (enabled && status != NO_ERROR) {
6523 return status;
6524 }
6525
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 switch (mState) {
6527 // going from disabled to enabled
6528 case IDLE:
6529 mState = STARTING;
6530 break;
6531 case STOPPED:
6532 mState = RESTART;
6533 break;
6534 case STOPPING:
6535 mState = ACTIVE;
6536 break;
6537
6538 // going from enabled to disabled
6539 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006540 mState = STOPPED;
6541 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006542 case STARTING:
6543 mState = IDLE;
6544 break;
6545 case ACTIVE:
6546 mState = STOPPING;
6547 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006548 case DESTROYED:
6549 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550 }
6551 for (size_t i = 1; i < mHandles.size(); i++) {
6552 sp<EffectHandle> h = mHandles[i].promote();
6553 if (h != 0) {
6554 h->setEnabled(enabled);
6555 }
6556 }
6557 }
6558 return NO_ERROR;
6559}
6560
Glenn Kastenc59c0042012-02-02 14:06:11 -08006561bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562{
6563 switch (mState) {
6564 case RESTART:
6565 case STARTING:
6566 case ACTIVE:
6567 return true;
6568 case IDLE:
6569 case STOPPING:
6570 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006571 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006572 default:
6573 return false;
6574 }
6575}
6576
Glenn Kastenc59c0042012-02-02 14:06:11 -08006577bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006578{
6579 switch (mState) {
6580 case RESTART:
6581 case ACTIVE:
6582 case STOPPING:
6583 case STOPPED:
6584 return true;
6585 case IDLE:
6586 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006587 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006588 default:
6589 return false;
6590 }
6591}
6592
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6594{
6595 Mutex::Autolock _l(mLock);
6596 status_t status = NO_ERROR;
6597
6598 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6599 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006600 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006601 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6602 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 status_t cmdStatus;
6604 uint32_t volume[2];
6605 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006606 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 volume[0] = *left;
6608 volume[1] = *right;
6609 if (controller) {
6610 pVolume = volume;
6611 }
Eric Laurent25f43952010-07-28 05:40:18 -07006612 status = (*mEffectInterface)->command(mEffectInterface,
6613 EFFECT_CMD_SET_VOLUME,
6614 size,
6615 volume,
6616 &size,
6617 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6619 *left = volume[0];
6620 *right = volume[1];
6621 }
6622 }
6623 return status;
6624}
6625
6626status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6627{
6628 Mutex::Autolock _l(mLock);
6629 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006630 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6631 // audio pre processing modules on RecordThread can receive both output and
6632 // input device indication in the same call
6633 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6634 if (dev) {
6635 status_t cmdStatus;
6636 uint32_t size = sizeof(status_t);
6637
6638 status = (*mEffectInterface)->command(mEffectInterface,
6639 EFFECT_CMD_SET_DEVICE,
6640 sizeof(uint32_t),
6641 &dev,
6642 &size,
6643 &cmdStatus);
6644 if (status == NO_ERROR) {
6645 status = cmdStatus;
6646 }
6647 }
6648 dev = device & AUDIO_DEVICE_IN_ALL;
6649 if (dev) {
6650 status_t cmdStatus;
6651 uint32_t size = sizeof(status_t);
6652
6653 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6654 EFFECT_CMD_SET_INPUT_DEVICE,
6655 sizeof(uint32_t),
6656 &dev,
6657 &size,
6658 &cmdStatus);
6659 if (status2 == NO_ERROR) {
6660 status2 = cmdStatus;
6661 }
6662 if (status == NO_ERROR) {
6663 status = status2;
6664 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665 }
6666 }
6667 return status;
6668}
6669
Glenn Kastenf78aee72012-01-04 11:00:47 -08006670status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671{
6672 Mutex::Autolock _l(mLock);
6673 status_t status = NO_ERROR;
6674 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006676 uint32_t size = sizeof(status_t);
6677 status = (*mEffectInterface)->command(mEffectInterface,
6678 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006679 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006680 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006681 &size,
6682 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 if (status == NO_ERROR) {
6684 status = cmdStatus;
6685 }
6686 }
6687 return status;
6688}
6689
Eric Laurent59255e42011-07-27 19:49:51 -07006690void AudioFlinger::EffectModule::setSuspended(bool suspended)
6691{
6692 Mutex::Autolock _l(mLock);
6693 mSuspended = suspended;
6694}
Glenn Kastena3a85482012-01-04 11:01:11 -08006695
6696bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006697{
6698 Mutex::Autolock _l(mLock);
6699 return mSuspended;
6700}
6701
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6703{
6704 const size_t SIZE = 256;
6705 char buffer[SIZE];
6706 String8 result;
6707
6708 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6709 result.append(buffer);
6710
6711 bool locked = tryLock(mLock);
6712 // failed to lock - AudioFlinger is probably deadlocked
6713 if (!locked) {
6714 result.append("\t\tCould not lock Fx mutex:\n");
6715 }
6716
6717 result.append("\t\tSession Status State Engine:\n");
6718 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6719 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6720 result.append(buffer);
6721
6722 result.append("\t\tDescriptor:\n");
6723 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6724 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6725 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6726 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6727 result.append(buffer);
6728 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6729 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6730 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6731 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6732 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006733 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734 mDescriptor.apiVersion,
6735 mDescriptor.flags);
6736 result.append(buffer);
6737 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6738 mDescriptor.name);
6739 result.append(buffer);
6740 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6741 mDescriptor.implementor);
6742 result.append(buffer);
6743
6744 result.append("\t\t- Input configuration:\n");
6745 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6746 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6747 (uint32_t)mConfig.inputCfg.buffer.raw,
6748 mConfig.inputCfg.buffer.frameCount,
6749 mConfig.inputCfg.samplingRate,
6750 mConfig.inputCfg.channels,
6751 mConfig.inputCfg.format);
6752 result.append(buffer);
6753
6754 result.append("\t\t- Output configuration:\n");
6755 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6756 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6757 (uint32_t)mConfig.outputCfg.buffer.raw,
6758 mConfig.outputCfg.buffer.frameCount,
6759 mConfig.outputCfg.samplingRate,
6760 mConfig.outputCfg.channels,
6761 mConfig.outputCfg.format);
6762 result.append(buffer);
6763
6764 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6765 result.append(buffer);
6766 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6767 for (size_t i = 0; i < mHandles.size(); ++i) {
6768 sp<EffectHandle> handle = mHandles[i].promote();
6769 if (handle != 0) {
6770 handle->dump(buffer, SIZE);
6771 result.append(buffer);
6772 }
6773 }
6774
6775 result.append("\n");
6776
6777 write(fd, result.string(), result.length());
6778
6779 if (locked) {
6780 mLock.unlock();
6781 }
6782
6783 return NO_ERROR;
6784}
6785
6786// ----------------------------------------------------------------------------
6787// EffectHandle implementation
6788// ----------------------------------------------------------------------------
6789
6790#undef LOG_TAG
6791#define LOG_TAG "AudioFlinger::EffectHandle"
6792
6793AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6794 const sp<AudioFlinger::Client>& client,
6795 const sp<IEffectClient>& effectClient,
6796 int32_t priority)
6797 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006798 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006799 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800{
Steve Block3856b092011-10-20 11:56:00 +01006801 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006802
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006803 if (client == 0) {
6804 return;
6805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6807 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6808 if (mCblkMemory != 0) {
6809 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6810
Glenn Kastena0d68332012-01-27 16:47:15 -08006811 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 new(mCblk) effect_param_cblk_t();
6813 mBuffer = (uint8_t *)mCblk + bufOffset;
6814 }
6815 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006816 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817 return;
6818 }
6819}
6820
6821AudioFlinger::EffectHandle::~EffectHandle()
6822{
Steve Block3856b092011-10-20 11:56:00 +01006823 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006824 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006825 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826}
6827
6828status_t AudioFlinger::EffectHandle::enable()
6829{
Steve Block3856b092011-10-20 11:56:00 +01006830 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831 if (!mHasControl) return INVALID_OPERATION;
6832 if (mEffect == 0) return DEAD_OBJECT;
6833
Eric Laurentdb7c0792011-08-10 10:37:50 -07006834 if (mEnabled) {
6835 return NO_ERROR;
6836 }
6837
Eric Laurent59255e42011-07-27 19:49:51 -07006838 mEnabled = true;
6839
6840 sp<ThreadBase> thread = mEffect->thread().promote();
6841 if (thread != 0) {
6842 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6843 }
6844
6845 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6846 if (mEffect->suspended()) {
6847 return NO_ERROR;
6848 }
6849
Eric Laurentdb7c0792011-08-10 10:37:50 -07006850 status_t status = mEffect->setEnabled(true);
6851 if (status != NO_ERROR) {
6852 if (thread != 0) {
6853 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6854 }
6855 mEnabled = false;
6856 }
6857 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858}
6859
6860status_t AudioFlinger::EffectHandle::disable()
6861{
Steve Block3856b092011-10-20 11:56:00 +01006862 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006864 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865
Eric Laurentdb7c0792011-08-10 10:37:50 -07006866 if (!mEnabled) {
6867 return NO_ERROR;
6868 }
Eric Laurent59255e42011-07-27 19:49:51 -07006869 mEnabled = false;
6870
6871 if (mEffect->suspended()) {
6872 return NO_ERROR;
6873 }
6874
6875 status_t status = mEffect->setEnabled(false);
6876
6877 sp<ThreadBase> thread = mEffect->thread().promote();
6878 if (thread != 0) {
6879 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6880 }
6881
6882 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883}
6884
6885void AudioFlinger::EffectHandle::disconnect()
6886{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006887 disconnect(true);
6888}
6889
6890void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6891{
Steve Block3856b092011-10-20 11:56:00 +01006892 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006893 if (mEffect == 0) {
6894 return;
6895 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006896 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006897
Eric Laurenta85a74a2011-10-19 11:44:54 -07006898 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006899 sp<ThreadBase> thread = mEffect->thread().promote();
6900 if (thread != 0) {
6901 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6902 }
Eric Laurent59255e42011-07-27 19:49:51 -07006903 }
6904
Mathias Agopian65ab4712010-07-14 17:59:35 -07006905 // release sp on module => module destructor can be called now
6906 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006908 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006909 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006910 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6911 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006912 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006913 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6915 mClient.clear();
6916 }
6917}
6918
Eric Laurent25f43952010-07-28 05:40:18 -07006919status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6920 uint32_t cmdSize,
6921 void *pCmdData,
6922 uint32_t *replySize,
6923 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924{
Steve Block3856b092011-10-20 11:56:00 +01006925// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006926// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927
6928 // only get parameter command is permitted for applications not controlling the effect
6929 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6930 return INVALID_OPERATION;
6931 }
6932 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006933 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934
6935 // handle commands that are not forwarded transparently to effect engine
6936 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6937 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6938 // no risk to block the whole media server process or mixer threads is we are stuck here
6939 Mutex::Autolock _l(mCblk->lock);
6940 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6941 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6942 mCblk->serverIndex = 0;
6943 mCblk->clientIndex = 0;
6944 return BAD_VALUE;
6945 }
6946 status_t status = NO_ERROR;
6947 while (mCblk->serverIndex < mCblk->clientIndex) {
6948 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006949 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 int *p = (int *)(mBuffer + mCblk->serverIndex);
6951 int size = *p++;
6952 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006953 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954 break;
6955 }
6956 effect_param_t *param = (effect_param_t *)p;
6957 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006958 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 mCblk->serverIndex += size;
6960 continue;
6961 }
Eric Laurent25f43952010-07-28 05:40:18 -07006962 uint32_t psize = sizeof(effect_param_t) +
6963 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6964 param->vsize;
6965 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6966 psize,
6967 p,
6968 &rsize,
6969 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006970 // stop at first error encountered
6971 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006973 *(int *)pReplyData = reply;
6974 break;
6975 } else if (reply != NO_ERROR) {
6976 *(int *)pReplyData = reply;
6977 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 }
6979 mCblk->serverIndex += size;
6980 }
6981 mCblk->serverIndex = 0;
6982 mCblk->clientIndex = 0;
6983 return status;
6984 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006985 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986 return enable();
6987 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006988 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 return disable();
6990 }
6991
6992 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6993}
6994
Eric Laurent59255e42011-07-27 19:49:51 -07006995void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996{
Steve Block3856b092011-10-20 11:56:00 +01006997 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998
6999 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007000 mEnabled = enabled;
7001
Mathias Agopian65ab4712010-07-14 17:59:35 -07007002 if (signal && mEffectClient != 0) {
7003 mEffectClient->controlStatusChanged(hasControl);
7004 }
7005}
7006
Eric Laurent25f43952010-07-28 05:40:18 -07007007void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7008 uint32_t cmdSize,
7009 void *pCmdData,
7010 uint32_t replySize,
7011 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012{
7013 if (mEffectClient != 0) {
7014 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7015 }
7016}
7017
7018
7019
7020void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7021{
7022 if (mEffectClient != 0) {
7023 mEffectClient->enableStatusChanged(enabled);
7024 }
7025}
7026
7027status_t AudioFlinger::EffectHandle::onTransact(
7028 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7029{
7030 return BnEffect::onTransact(code, data, reply, flags);
7031}
7032
7033
7034void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7035{
Glenn Kastena0d68332012-01-27 16:47:15 -08007036 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037
7038 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007039 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040 mPriority,
7041 mHasControl,
7042 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007043 mCblk ? mCblk->clientIndex : 0,
7044 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045 );
7046
7047 if (locked) {
7048 mCblk->lock.unlock();
7049 }
7050}
7051
7052#undef LOG_TAG
7053#define LOG_TAG "AudioFlinger::EffectChain"
7054
7055AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7056 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007057 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007058 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7059 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060{
Dima Zavinfce7a472011-04-19 22:30:36 -07007061 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007062 sp<ThreadBase> thread = mThread.promote();
7063 if (thread == 0) {
7064 return;
7065 }
7066 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7067 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068}
7069
7070AudioFlinger::EffectChain::~EffectChain()
7071{
7072 if (mOwnInBuffer) {
7073 delete mInBuffer;
7074 }
7075
7076}
7077
Eric Laurent59255e42011-07-27 19:49:51 -07007078// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007079sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 size_t size = mEffects.size();
7082
7083 for (size_t i = 0; i < size; i++) {
7084 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007085 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 }
7087 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007088 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007089}
7090
Eric Laurent59255e42011-07-27 19:49:51 -07007091// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007092sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007094 size_t size = mEffects.size();
7095
7096 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007097 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7098 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007099 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100 }
7101 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007102 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103}
7104
Eric Laurent59255e42011-07-27 19:49:51 -07007105// getEffectFromType_l() must be called with ThreadBase::mLock held
7106sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7107 const effect_uuid_t *type)
7108{
Eric Laurent59255e42011-07-27 19:49:51 -07007109 size_t size = mEffects.size();
7110
7111 for (size_t i = 0; i < size; i++) {
7112 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007113 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007114 }
7115 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007116 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007117}
7118
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119// Must be called with EffectChain::mLock locked
7120void AudioFlinger::EffectChain::process_l()
7121{
Eric Laurentdac69112010-09-28 14:09:57 -07007122 sp<ThreadBase> thread = mThread.promote();
7123 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007124 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007125 return;
7126 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007127 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7128 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007129 // always process effects unless no more tracks are on the session and the effect tail
7130 // has been rendered
7131 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007132 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007133 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007134
Eric Laurent544fe9b2011-11-11 15:42:52 -08007135 if (!tracksOnSession && mTailBufferCount == 0) {
7136 doProcess = false;
7137 }
7138
7139 if (activeTrackCnt() == 0) {
7140 // if no track is active and the effect tail has not been rendered,
7141 // the input buffer must be cleared here as the mixer process will not do it
7142 if (tracksOnSession || mTailBufferCount > 0) {
7143 size_t numSamples = thread->frameCount() * thread->channelCount();
7144 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7145 if (mTailBufferCount > 0) {
7146 mTailBufferCount--;
7147 }
7148 }
7149 }
Eric Laurentdac69112010-09-28 14:09:57 -07007150 }
7151
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007153 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007154 for (size_t i = 0; i < size; i++) {
7155 mEffects[i]->process();
7156 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157 }
7158 for (size_t i = 0; i < size; i++) {
7159 mEffects[i]->updateState();
7160 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161}
7162
Eric Laurentcab11242010-07-15 12:50:15 -07007163// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007164status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007165{
7166 effect_descriptor_t desc = effect->desc();
7167 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7168
7169 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007170 effect->setChain(this);
7171 sp<ThreadBase> thread = mThread.promote();
7172 if (thread == 0) {
7173 return NO_INIT;
7174 }
7175 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176
7177 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7178 // Auxiliary effects are inserted at the beginning of mEffects vector as
7179 // they are processed first and accumulated in chain input buffer
7180 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007181
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 // the input buffer for auxiliary effect contains mono samples in
7183 // 32 bit format. This is to avoid saturation in AudoMixer
7184 // accumulation stage. Saturation is done in EffectModule::process() before
7185 // calling the process in effect engine
7186 size_t numSamples = thread->frameCount();
7187 int32_t *buffer = new int32_t[numSamples];
7188 memset(buffer, 0, numSamples * sizeof(int32_t));
7189 effect->setInBuffer((int16_t *)buffer);
7190 // auxiliary effects output samples to chain input buffer for further processing
7191 // by insert effects
7192 effect->setOutBuffer(mInBuffer);
7193 } else {
7194 // Insert effects are inserted at the end of mEffects vector as they are processed
7195 // after track and auxiliary effects.
7196 // Insert effect order as a function of indicated preference:
7197 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7198 // another effect is present
7199 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7200 // last effect claiming first position
7201 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7202 // first effect claiming last position
7203 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7204 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7205 // already present
7206
7207 int size = (int)mEffects.size();
7208 int idx_insert = size;
7209 int idx_insert_first = -1;
7210 int idx_insert_last = -1;
7211
7212 for (int i = 0; i < size; i++) {
7213 effect_descriptor_t d = mEffects[i]->desc();
7214 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7215 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7216 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7217 // check invalid effect chaining combinations
7218 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7219 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007220 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 return INVALID_OPERATION;
7222 }
7223 // remember position of first insert effect and by default
7224 // select this as insert position for new effect
7225 if (idx_insert == size) {
7226 idx_insert = i;
7227 }
7228 // remember position of last insert effect claiming
7229 // first position
7230 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7231 idx_insert_first = i;
7232 }
7233 // remember position of first insert effect claiming
7234 // last position
7235 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7236 idx_insert_last == -1) {
7237 idx_insert_last = i;
7238 }
7239 }
7240 }
7241
7242 // modify idx_insert from first position if needed
7243 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7244 if (idx_insert_last != -1) {
7245 idx_insert = idx_insert_last;
7246 } else {
7247 idx_insert = size;
7248 }
7249 } else {
7250 if (idx_insert_first != -1) {
7251 idx_insert = idx_insert_first + 1;
7252 }
7253 }
7254
7255 // always read samples from chain input buffer
7256 effect->setInBuffer(mInBuffer);
7257
7258 // if last effect in the chain, output samples to chain
7259 // output buffer, otherwise to chain input buffer
7260 if (idx_insert == size) {
7261 if (idx_insert != 0) {
7262 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7263 mEffects[idx_insert-1]->configure();
7264 }
7265 effect->setOutBuffer(mOutBuffer);
7266 } else {
7267 effect->setOutBuffer(mInBuffer);
7268 }
7269 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007270
Steve Block3856b092011-10-20 11:56:00 +01007271 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007272 }
7273 effect->configure();
7274 return NO_ERROR;
7275}
7276
Eric Laurentcab11242010-07-15 12:50:15 -07007277// removeEffect_l() must be called with PlaybackThread::mLock held
7278size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279{
7280 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281 int size = (int)mEffects.size();
7282 int i;
7283 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7284
7285 for (i = 0; i < size; i++) {
7286 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007287 // calling stop here will remove pre-processing effect from the audio HAL.
7288 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7289 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007290 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7291 mEffects[i]->state() == EffectModule::STOPPING) {
7292 mEffects[i]->stop();
7293 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7295 delete[] effect->inBuffer();
7296 } else {
7297 if (i == size - 1 && i != 0) {
7298 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7299 mEffects[i - 1]->configure();
7300 }
7301 }
7302 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007303 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304 break;
7305 }
7306 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307
7308 return mEffects.size();
7309}
7310
Eric Laurentcab11242010-07-15 12:50:15 -07007311// setDevice_l() must be called with PlaybackThread::mLock held
7312void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313{
7314 size_t size = mEffects.size();
7315 for (size_t i = 0; i < size; i++) {
7316 mEffects[i]->setDevice(device);
7317 }
7318}
7319
Eric Laurentcab11242010-07-15 12:50:15 -07007320// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007321void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007322{
7323 size_t size = mEffects.size();
7324 for (size_t i = 0; i < size; i++) {
7325 mEffects[i]->setMode(mode);
7326 }
7327}
7328
Eric Laurentcab11242010-07-15 12:50:15 -07007329// setVolume_l() must be called with PlaybackThread::mLock held
7330bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331{
7332 uint32_t newLeft = *left;
7333 uint32_t newRight = *right;
7334 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007335 int ctrlIdx = -1;
7336 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337
Eric Laurentcab11242010-07-15 12:50:15 -07007338 // first update volume controller
7339 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007340 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007341 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7342 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007343 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007344 break;
7345 }
7346 }
7347
7348 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007349 if (hasControl) {
7350 *left = mNewLeftVolume;
7351 *right = mNewRightVolume;
7352 }
7353 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007354 }
7355
7356 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007357 mLeftVolume = newLeft;
7358 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007359
7360 // second get volume update from volume controller
7361 if (ctrlIdx >= 0) {
7362 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007363 mNewLeftVolume = newLeft;
7364 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007365 }
7366 // then indicate volume to all other effects in chain.
7367 // Pass altered volume to effects before volume controller
7368 // and requested volume to effects after controller
7369 uint32_t lVol = newLeft;
7370 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007371
Mathias Agopian65ab4712010-07-14 17:59:35 -07007372 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007373 if ((int)i == ctrlIdx) continue;
7374 // this also works for ctrlIdx == -1 when there is no volume controller
7375 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 lVol = *left;
7377 rVol = *right;
7378 }
7379 mEffects[i]->setVolume(&lVol, &rVol, false);
7380 }
7381 *left = newLeft;
7382 *right = newRight;
7383
7384 return hasControl;
7385}
7386
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7388{
7389 const size_t SIZE = 256;
7390 char buffer[SIZE];
7391 String8 result;
7392
7393 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7394 result.append(buffer);
7395
7396 bool locked = tryLock(mLock);
7397 // failed to lock - AudioFlinger is probably deadlocked
7398 if (!locked) {
7399 result.append("\tCould not lock mutex:\n");
7400 }
7401
Eric Laurentcab11242010-07-15 12:50:15 -07007402 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7403 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404 mEffects.size(),
7405 (uint32_t)mInBuffer,
7406 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407 mActiveTrackCnt);
7408 result.append(buffer);
7409 write(fd, result.string(), result.size());
7410
7411 for (size_t i = 0; i < mEffects.size(); ++i) {
7412 sp<EffectModule> effect = mEffects[i];
7413 if (effect != 0) {
7414 effect->dump(fd, args);
7415 }
7416 }
7417
7418 if (locked) {
7419 mLock.unlock();
7420 }
7421
7422 return NO_ERROR;
7423}
7424
Eric Laurent59255e42011-07-27 19:49:51 -07007425// must be called with ThreadBase::mLock held
7426void AudioFlinger::EffectChain::setEffectSuspended_l(
7427 const effect_uuid_t *type, bool suspend)
7428{
7429 sp<SuspendedEffectDesc> desc;
7430 // use effect type UUID timelow as key as there is no real risk of identical
7431 // timeLow fields among effect type UUIDs.
7432 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7433 if (suspend) {
7434 if (index >= 0) {
7435 desc = mSuspendedEffects.valueAt(index);
7436 } else {
7437 desc = new SuspendedEffectDesc();
7438 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7439 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007440 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007441 }
7442 if (desc->mRefCount++ == 0) {
7443 sp<EffectModule> effect = getEffectIfEnabled(type);
7444 if (effect != 0) {
7445 desc->mEffect = effect;
7446 effect->setSuspended(true);
7447 effect->setEnabled(false);
7448 }
7449 }
7450 } else {
7451 if (index < 0) {
7452 return;
7453 }
7454 desc = mSuspendedEffects.valueAt(index);
7455 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007456 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007457 desc->mRefCount = 1;
7458 }
7459 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007460 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007461 if (desc->mEffect != 0) {
7462 sp<EffectModule> effect = desc->mEffect.promote();
7463 if (effect != 0) {
7464 effect->setSuspended(false);
7465 sp<EffectHandle> handle = effect->controlHandle();
7466 if (handle != 0) {
7467 effect->setEnabled(handle->enabled());
7468 }
7469 }
7470 desc->mEffect.clear();
7471 }
7472 mSuspendedEffects.removeItemsAt(index);
7473 }
7474 }
7475}
7476
7477// must be called with ThreadBase::mLock held
7478void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7479{
7480 sp<SuspendedEffectDesc> desc;
7481
7482 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7483 if (suspend) {
7484 if (index >= 0) {
7485 desc = mSuspendedEffects.valueAt(index);
7486 } else {
7487 desc = new SuspendedEffectDesc();
7488 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007489 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007490 }
7491 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007492 Vector< sp<EffectModule> > effects;
7493 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007494 for (size_t i = 0; i < effects.size(); i++) {
7495 setEffectSuspended_l(&effects[i]->desc().type, true);
7496 }
7497 }
7498 } else {
7499 if (index < 0) {
7500 return;
7501 }
7502 desc = mSuspendedEffects.valueAt(index);
7503 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007504 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007505 desc->mRefCount = 1;
7506 }
7507 if (--desc->mRefCount == 0) {
7508 Vector<const effect_uuid_t *> types;
7509 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7510 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7511 continue;
7512 }
7513 types.add(&mSuspendedEffects.valueAt(i)->mType);
7514 }
7515 for (size_t i = 0; i < types.size(); i++) {
7516 setEffectSuspended_l(types[i], false);
7517 }
Steve Block3856b092011-10-20 11:56:00 +01007518 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007519 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7520 }
7521 }
7522}
7523
Eric Laurent6bffdb82011-09-23 08:40:41 -07007524
7525// The volume effect is used for automated tests only
7526#ifndef OPENSL_ES_H_
7527static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7528 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7529const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7530#endif //OPENSL_ES_H_
7531
Eric Laurentdb7c0792011-08-10 10:37:50 -07007532bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7533{
7534 // auxiliary effects and visualizer are never suspended on output mix
7535 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7536 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007537 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7538 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007539 return false;
7540 }
7541 return true;
7542}
7543
Glenn Kastend0539712012-01-30 12:56:03 -08007544void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007545{
Glenn Kastend0539712012-01-30 12:56:03 -08007546 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007547 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007548 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7549 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007550 }
Eric Laurent59255e42011-07-27 19:49:51 -07007551 }
Eric Laurent59255e42011-07-27 19:49:51 -07007552}
7553
7554sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7555 const effect_uuid_t *type)
7556{
Glenn Kasten090f0192012-01-30 13:00:02 -08007557 sp<EffectModule> effect = getEffectFromType_l(type);
7558 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007559}
7560
7561void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7562 bool enabled)
7563{
7564 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7565 if (enabled) {
7566 if (index < 0) {
7567 // if the effect is not suspend check if all effects are suspended
7568 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7569 if (index < 0) {
7570 return;
7571 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007572 if (!isEffectEligibleForSuspend(effect->desc())) {
7573 return;
7574 }
Eric Laurent59255e42011-07-27 19:49:51 -07007575 setEffectSuspended_l(&effect->desc().type, enabled);
7576 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007577 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007578 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007579 return;
7580 }
Eric Laurent59255e42011-07-27 19:49:51 -07007581 }
Steve Block3856b092011-10-20 11:56:00 +01007582 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007583 effect->desc().type.timeLow);
7584 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7585 // if effect is requested to suspended but was not yet enabled, supend it now.
7586 if (desc->mEffect == 0) {
7587 desc->mEffect = effect;
7588 effect->setEnabled(false);
7589 effect->setSuspended(true);
7590 }
7591 } else {
7592 if (index < 0) {
7593 return;
7594 }
Steve Block3856b092011-10-20 11:56:00 +01007595 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007596 effect->desc().type.timeLow);
7597 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7598 desc->mEffect.clear();
7599 effect->setSuspended(false);
7600 }
7601}
7602
Mathias Agopian65ab4712010-07-14 17:59:35 -07007603#undef LOG_TAG
7604#define LOG_TAG "AudioFlinger"
7605
7606// ----------------------------------------------------------------------------
7607
7608status_t AudioFlinger::onTransact(
7609 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7610{
7611 return BnAudioFlinger::onTransact(code, data, reply, flags);
7612}
7613
Mathias Agopian65ab4712010-07-14 17:59:35 -07007614}; // namespace android