blob: 819a12c12d8bc8d16bcbcd87188fe6c5c1b9348f [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 {
732 volume = mStreamTypes[stream].volume;
733 }
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
744 return mStreamTypes[stream].mute;
745}
746
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800747status_t AudioFlinger::setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748{
749 status_t result;
750
Steve Block3856b092011-10-20 11:56:00 +0100751 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700752 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
753 // check calling permissions
754 if (!settingsAllowed()) {
755 return PERMISSION_DENIED;
756 }
757
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 // ioHandle == 0 means the parameters are global to the audio hardware interface
759 if (ioHandle == 0) {
760 AutoMutex lock(mHardwareLock);
761 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700762 status_t final_result = NO_ERROR;
763 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
764 audio_hw_device_t *dev = mAudioHwDevs[i];
765 result = dev->set_parameters(dev, keyValuePairs.string());
766 final_result = result ?: final_result;
767 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700768 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700769 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
770 AudioParameter param = AudioParameter(keyValuePairs);
771 String8 value;
772 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
773 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700774 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
775 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700776 for (size_t i = 0; i < mRecordThreads.size(); i++) {
777 sp<RecordThread> thread = mRecordThreads.valueAt(i);
778 RecordThread::RecordTrack *track = thread->track();
779 if (track != NULL) {
780 audio_devices_t device = (audio_devices_t)(
781 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700782 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700783 thread->setEffectSuspended(FX_IID_AEC,
784 suspend,
785 track->sessionId());
786 thread->setEffectSuspended(FX_IID_NS,
787 suspend,
788 track->sessionId());
789 }
790 }
Eric Laurentbee53372011-08-29 12:42:48 -0700791 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700792 }
793 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700794 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700795 }
796
797 // hold a strong ref on thread in case closeOutput() or closeInput() is called
798 // and the thread is exited once the lock is released
799 sp<ThreadBase> thread;
800 {
801 Mutex::Autolock _l(mLock);
802 thread = checkPlaybackThread_l(ioHandle);
803 if (thread == NULL) {
804 thread = checkRecordThread_l(ioHandle);
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -0800805 } else if (thread == primaryPlaybackThread_l()) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700806 // indicate output device change to all input threads for pre processing
807 AudioParameter param = AudioParameter(keyValuePairs);
808 int value;
809 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
810 for (size_t i = 0; i < mRecordThreads.size(); i++) {
811 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
812 }
813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 }
815 }
Glenn Kasten7378ca52012-01-20 13:44:40 -0800816 if (thread != 0) {
817 return thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 }
819 return BAD_VALUE;
820}
821
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800822String8 AudioFlinger::getParameters(audio_io_handle_t ioHandle, const String8& keys) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823{
Steve Block3856b092011-10-20 11:56:00 +0100824// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
826
827 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700828 String8 out_s8;
829
Dima Zavin799a70e2011-04-18 16:57:27 -0700830 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
831 audio_hw_device_t *dev = mAudioHwDevs[i];
832 char *s = dev->get_parameters(dev, keys.string());
833 out_s8 += String8(s);
834 free(s);
835 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700836 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 }
838
839 Mutex::Autolock _l(mLock);
840
841 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
842 if (playbackThread != NULL) {
843 return playbackThread->getParameters(keys);
844 }
845 RecordThread *recordThread = checkRecordThread_l(ioHandle);
846 if (recordThread != NULL) {
847 return recordThread->getParameters(keys);
848 }
849 return String8("");
850}
851
Glenn Kastenf587ba52012-01-26 16:25:10 -0800852size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, audio_format_t format, int channelCount) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700853{
Eric Laurenta1884f92011-08-23 08:25:03 -0700854 status_t ret = initCheck();
855 if (ret != NO_ERROR) {
856 return 0;
857 }
858
Dima Zavin799a70e2011-04-18 16:57:27 -0700859 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700860}
861
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800862unsigned int AudioFlinger::getInputFramesLost(audio_io_handle_t ioHandle) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700863{
864 if (ioHandle == 0) {
865 return 0;
866 }
867
868 Mutex::Autolock _l(mLock);
869
870 RecordThread *recordThread = checkRecordThread_l(ioHandle);
871 if (recordThread != NULL) {
872 return recordThread->getInputFramesLost();
873 }
874 return 0;
875}
876
877status_t AudioFlinger::setVoiceVolume(float value)
878{
Eric Laurenta1884f92011-08-23 08:25:03 -0700879 status_t ret = initCheck();
880 if (ret != NO_ERROR) {
881 return ret;
882 }
883
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 // check calling permissions
885 if (!settingsAllowed()) {
886 return PERMISSION_DENIED;
887 }
888
889 AutoMutex lock(mHardwareLock);
890 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700891 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700892 mHardwareStatus = AUDIO_HW_IDLE;
893
894 return ret;
895}
896
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800897status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames,
898 audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700899{
900 status_t status;
901
902 Mutex::Autolock _l(mLock);
903
904 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
905 if (playbackThread != NULL) {
906 return playbackThread->getRenderPosition(halFrames, dspFrames);
907 }
908
909 return BAD_VALUE;
910}
911
912void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
913{
914
915 Mutex::Autolock _l(mLock);
916
Glenn Kastenbb001922012-02-03 11:10:26 -0800917 pid_t pid = IPCThreadState::self()->getCallingPid();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918 if (mNotificationClients.indexOfKey(pid) < 0) {
919 sp<NotificationClient> notificationClient = new NotificationClient(this,
920 client,
921 pid);
Steve Block3856b092011-10-20 11:56:00 +0100922 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700923
924 mNotificationClients.add(pid, notificationClient);
925
926 sp<IBinder> binder = client->asBinder();
927 binder->linkToDeath(notificationClient);
928
929 // the config change is always sent from playback or record threads to avoid deadlock
930 // with AudioSystem::gLock
931 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
932 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
933 }
934
935 for (size_t i = 0; i < mRecordThreads.size(); i++) {
936 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
937 }
938 }
939}
940
941void AudioFlinger::removeNotificationClient(pid_t pid)
942{
943 Mutex::Autolock _l(mLock);
944
945 int index = mNotificationClients.indexOfKey(pid);
946 if (index >= 0) {
947 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700949 mNotificationClients.removeItem(pid);
950 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700951
Steve Block3856b092011-10-20 11:56:00 +0100952 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700953 int num = mAudioSessionRefs.size();
954 bool removed = false;
955 for (int i = 0; i< num; i++) {
956 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100957 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700958 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100959 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700960 mAudioSessionRefs.removeAt(i);
961 delete ref;
962 removed = true;
963 i--;
964 num--;
965 }
966 }
967 if (removed) {
968 purgeStaleEffects_l();
969 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700970}
971
972// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800973void AudioFlinger::audioConfigChanged_l(int event, audio_io_handle_t ioHandle, void *param2)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974{
975 size_t size = mNotificationClients.size();
976 for (size_t i = 0; i < size; i++) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800977 mNotificationClients.valueAt(i)->audioFlingerClient()->ioConfigChanged(event, ioHandle,
978 param2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700979 }
980}
981
982// removeClient_l() must be called with AudioFlinger::mLock held
983void AudioFlinger::removeClient_l(pid_t pid)
984{
Steve Block3856b092011-10-20 11:56:00 +0100985 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986 mClients.removeItem(pid);
987}
988
989
990// ----------------------------------------------------------------------------
991
Glenn Kasten72ef00d2012-01-17 11:09:42 -0800992AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
993 uint32_t device, type_t type)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994 : Thread(false),
Glenn Kasten23bb8be2012-01-26 10:38:26 -0800995 mType(type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -0800996 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0),
997 // mChannelMask
998 mChannelCount(0),
999 mFrameSize(1), mFormat(AUDIO_FORMAT_INVALID),
1000 mParamStatus(NO_ERROR),
1001 mStandby(false), mId(id), mExiting(false),
1002 mDevice(device),
1003 mDeathRecipient(new PMDeathRecipient(this))
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004{
1005}
1006
1007AudioFlinger::ThreadBase::~ThreadBase()
1008{
1009 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001010 // do not lock the mutex in destructor
1011 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001012 if (mPowerManager != 0) {
1013 sp<IBinder> binder = mPowerManager->asBinder();
1014 binder->unlinkToDeath(mDeathRecipient);
1015 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001016}
1017
1018void AudioFlinger::ThreadBase::exit()
1019{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001020 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 // destroyed in the middle of requestExitAndWait()
1022 sp <ThreadBase> strongMe = this;
1023
Steve Block3856b092011-10-20 11:56:00 +01001024 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001025 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001026 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027 mExiting = true;
1028 requestExit();
1029 mWaitWorkCV.signal();
1030 }
1031 requestExitAndWait();
1032}
1033
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1035{
1036 status_t status;
1037
Steve Block3856b092011-10-20 11:56:00 +01001038 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001039 Mutex::Autolock _l(mLock);
1040
1041 mNewParameters.add(keyValuePairs);
1042 mWaitWorkCV.signal();
1043 // wait condition with timeout in case the thread loop has exited
1044 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001045 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 status = mParamStatus;
1047 mWaitWorkCV.signal();
1048 } else {
1049 status = TIMED_OUT;
1050 }
1051 return status;
1052}
1053
1054void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1055{
1056 Mutex::Autolock _l(mLock);
1057 sendConfigEvent_l(event, param);
1058}
1059
1060// sendConfigEvent_l() must be called with ThreadBase::mLock held
1061void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1062{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001063 ConfigEvent configEvent;
1064 configEvent.mEvent = event;
1065 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001066 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001067 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001068 mWaitWorkCV.signal();
1069}
1070
1071void AudioFlinger::ThreadBase::processConfigEvents()
1072{
1073 mLock.lock();
1074 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001076 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 mConfigEvents.removeAt(0);
1078 // release mLock before locking AudioFlinger mLock: lock order is always
1079 // AudioFlinger then ThreadBase to avoid cross deadlock
1080 mLock.unlock();
1081 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001082 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001084 mLock.lock();
1085 }
1086 mLock.unlock();
1087}
1088
1089status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1090{
1091 const size_t SIZE = 256;
1092 char buffer[SIZE];
1093 String8 result;
1094
1095 bool locked = tryLock(mLock);
1096 if (!locked) {
1097 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1098 write(fd, buffer, strlen(buffer));
1099 }
1100
1101 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1102 result.append(buffer);
1103 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1104 result.append(buffer);
1105 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1106 result.append(buffer);
1107 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1108 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001109 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1110 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001111 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1112 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001113 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 result.append(buffer);
1115
1116 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1117 result.append(buffer);
1118 result.append(" Index Command");
1119 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1120 snprintf(buffer, SIZE, "\n %02d ", i);
1121 result.append(buffer);
1122 result.append(mNewParameters[i]);
1123 }
1124
1125 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1126 result.append(buffer);
1127 snprintf(buffer, SIZE, " Index event param\n");
1128 result.append(buffer);
1129 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001130 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001131 result.append(buffer);
1132 }
1133 result.append("\n");
1134
1135 write(fd, result.string(), result.size());
1136
1137 if (locked) {
1138 mLock.unlock();
1139 }
1140 return NO_ERROR;
1141}
1142
Eric Laurent1d2bff02011-07-24 17:49:51 -07001143status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1144{
1145 const size_t SIZE = 256;
1146 char buffer[SIZE];
1147 String8 result;
1148
1149 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1150 write(fd, buffer, strlen(buffer));
1151
1152 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1153 sp<EffectChain> chain = mEffectChains[i];
1154 if (chain != 0) {
1155 chain->dump(fd, args);
1156 }
1157 }
1158 return NO_ERROR;
1159}
1160
Eric Laurentfeb0db62011-07-22 09:04:31 -07001161void AudioFlinger::ThreadBase::acquireWakeLock()
1162{
1163 Mutex::Autolock _l(mLock);
1164 acquireWakeLock_l();
1165}
1166
1167void AudioFlinger::ThreadBase::acquireWakeLock_l()
1168{
1169 if (mPowerManager == 0) {
1170 // use checkService() to avoid blocking if power service is not up yet
1171 sp<IBinder> binder =
1172 defaultServiceManager()->checkService(String16("power"));
1173 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001174 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001175 } else {
1176 mPowerManager = interface_cast<IPowerManager>(binder);
1177 binder->linkToDeath(mDeathRecipient);
1178 }
1179 }
1180 if (mPowerManager != 0) {
1181 sp<IBinder> binder = new BBinder();
1182 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1183 binder,
1184 String16(mName));
1185 if (status == NO_ERROR) {
1186 mWakeLockToken = binder;
1187 }
Steve Block3856b092011-10-20 11:56:00 +01001188 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001189 }
1190}
1191
1192void AudioFlinger::ThreadBase::releaseWakeLock()
1193{
1194 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001195 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001196}
1197
1198void AudioFlinger::ThreadBase::releaseWakeLock_l()
1199{
1200 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001201 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001202 if (mPowerManager != 0) {
1203 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1204 }
1205 mWakeLockToken.clear();
1206 }
1207}
1208
1209void AudioFlinger::ThreadBase::clearPowerManager()
1210{
1211 Mutex::Autolock _l(mLock);
1212 releaseWakeLock_l();
1213 mPowerManager.clear();
1214}
1215
1216void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1217{
1218 sp<ThreadBase> thread = mThread.promote();
1219 if (thread != 0) {
1220 thread->clearPowerManager();
1221 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001222 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001223}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001224
Eric Laurent59255e42011-07-27 19:49:51 -07001225void AudioFlinger::ThreadBase::setEffectSuspended(
1226 const effect_uuid_t *type, bool suspend, int sessionId)
1227{
1228 Mutex::Autolock _l(mLock);
1229 setEffectSuspended_l(type, suspend, sessionId);
1230}
1231
1232void AudioFlinger::ThreadBase::setEffectSuspended_l(
1233 const effect_uuid_t *type, bool suspend, int sessionId)
1234{
Glenn Kasten090f0192012-01-30 13:00:02 -08001235 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001236 if (chain != 0) {
1237 if (type != NULL) {
1238 chain->setEffectSuspended_l(type, suspend);
1239 } else {
1240 chain->setEffectSuspendedAll_l(suspend);
1241 }
1242 }
1243
1244 updateSuspendedSessions_l(type, suspend, sessionId);
1245}
1246
1247void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1248{
1249 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1250 if (index < 0) {
1251 return;
1252 }
1253
1254 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1255 mSuspendedSessions.editValueAt(index);
1256
1257 for (size_t i = 0; i < sessionEffects.size(); i++) {
1258 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1259 for (int j = 0; j < desc->mRefCount; j++) {
1260 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1261 chain->setEffectSuspendedAll_l(true);
1262 } else {
Steve Block3856b092011-10-20 11:56:00 +01001263 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001264 desc->mType.timeLow);
1265 chain->setEffectSuspended_l(&desc->mType, true);
1266 }
1267 }
1268 }
1269}
1270
Eric Laurent59255e42011-07-27 19:49:51 -07001271void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1272 bool suspend,
1273 int sessionId)
1274{
1275 int index = mSuspendedSessions.indexOfKey(sessionId);
1276
1277 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1278
1279 if (suspend) {
1280 if (index >= 0) {
1281 sessionEffects = mSuspendedSessions.editValueAt(index);
1282 } else {
1283 mSuspendedSessions.add(sessionId, sessionEffects);
1284 }
1285 } else {
1286 if (index < 0) {
1287 return;
1288 }
1289 sessionEffects = mSuspendedSessions.editValueAt(index);
1290 }
1291
1292
1293 int key = EffectChain::kKeyForSuspendAll;
1294 if (type != NULL) {
1295 key = type->timeLow;
1296 }
1297 index = sessionEffects.indexOfKey(key);
1298
1299 sp <SuspendedSessionDesc> desc;
1300 if (suspend) {
1301 if (index >= 0) {
1302 desc = sessionEffects.valueAt(index);
1303 } else {
1304 desc = new SuspendedSessionDesc();
1305 if (type != NULL) {
1306 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1307 }
1308 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001309 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001310 }
1311 desc->mRefCount++;
1312 } else {
1313 if (index < 0) {
1314 return;
1315 }
1316 desc = sessionEffects.valueAt(index);
1317 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001319 sessionEffects.removeItemsAt(index);
1320 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001321 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001322 sessionId);
1323 mSuspendedSessions.removeItem(sessionId);
1324 }
1325 }
1326 }
1327 if (!sessionEffects.isEmpty()) {
1328 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1329 }
1330}
1331
1332void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1333 bool enabled,
1334 int sessionId)
1335{
1336 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001337 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1338}
Eric Laurent59255e42011-07-27 19:49:51 -07001339
Eric Laurenta85a74a2011-10-19 11:44:54 -07001340void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1341 bool enabled,
1342 int sessionId)
1343{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001344 if (mType != RECORD) {
1345 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1346 // another session. This gives the priority to well behaved effect control panels
1347 // and applications not using global effects.
1348 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1349 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1350 }
1351 }
Eric Laurent59255e42011-07-27 19:49:51 -07001352
1353 sp<EffectChain> chain = getEffectChain_l(sessionId);
1354 if (chain != 0) {
1355 chain->checkSuspendOnEffectEnabled(effect, enabled);
1356 }
1357}
1358
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359// ----------------------------------------------------------------------------
1360
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001361AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1362 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001363 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001364 uint32_t device,
1365 type_t type)
1366 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001367 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1368 // Assumes constructor is called by AudioFlinger with it's mLock held,
1369 // but it would be safer to explicitly pass initial masterMute as parameter
1370 mMasterMute(audioFlinger->masterMute_l()),
1371 // mStreamTypes[] initialized in constructor body
1372 mOutput(output),
1373 // Assumes constructor is called by AudioFlinger with it's mLock held,
1374 // but it would be safer to explicitly pass initial masterVolume as parameter
1375 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 readOutputParameters();
1381
Glenn Kasten263709e2012-01-06 08:40:01 -08001382 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001383 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1384 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1385 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001388 // initialized by stream_type_t default constructor
1389 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390 }
1391}
1392
1393AudioFlinger::PlaybackThread::~PlaybackThread()
1394{
1395 delete [] mMixBuffer;
1396}
1397
1398status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1399{
1400 dumpInternals(fd, args);
1401 dumpTracks(fd, args);
1402 dumpEffectChains(fd, args);
1403 return NO_ERROR;
1404}
1405
1406status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1407{
1408 const size_t SIZE = 256;
1409 char buffer[SIZE];
1410 String8 result;
1411
1412 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1413 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001414 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 -07001415 for (size_t i = 0; i < mTracks.size(); ++i) {
1416 sp<Track> track = mTracks[i];
1417 if (track != 0) {
1418 track->dump(buffer, SIZE);
1419 result.append(buffer);
1420 }
1421 }
1422
1423 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1424 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001425 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 -07001426 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001427 sp<Track> track = mActiveTracks[i].promote();
1428 if (track != 0) {
1429 track->dump(buffer, SIZE);
1430 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 }
1432 }
1433 write(fd, result.string(), result.size());
1434 return NO_ERROR;
1435}
1436
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1438{
1439 const size_t SIZE = 256;
1440 char buffer[SIZE];
1441 String8 result;
1442
1443 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1444 result.append(buffer);
1445 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1456 result.append(buffer);
1457 write(fd, result.string(), result.size());
1458
1459 dumpBase(fd, args);
1460
1461 return NO_ERROR;
1462}
1463
1464// Thread virtuals
1465status_t AudioFlinger::PlaybackThread::readyToRun()
1466{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001467 status_t status = initCheck();
1468 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001469 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001470 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001471 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001473 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474}
1475
1476void AudioFlinger::PlaybackThread::onFirstRef()
1477{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001478 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479}
1480
1481// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1482sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1483 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001484 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001486 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001487 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 int frameCount,
1489 const sp<IMemory>& sharedBuffer,
1490 int sessionId,
1491 status_t *status)
1492{
1493 sp<Track> track;
1494 status_t lStatus;
1495
1496 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001497 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1498 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001499 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001500 "for output %p with format %d",
1501 sampleRate, format, channelMask, mOutput, mFormat);
1502 lStatus = BAD_VALUE;
1503 goto Exit;
1504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 }
1506 } else {
1507 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1508 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001509 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510 lStatus = BAD_VALUE;
1511 goto Exit;
1512 }
1513 }
1514
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001515 lStatus = initCheck();
1516 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001517 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 goto Exit;
1519 }
1520
1521 { // scope for mLock
1522 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001523
1524 // all tracks in same audio session must share the same routing strategy otherwise
1525 // conflicts will happen when tracks are moved from one output to another by audio policy
1526 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001527 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001528 for (size_t i = 0; i < mTracks.size(); ++i) {
1529 sp<Track> t = mTracks[i];
1530 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001531 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001532 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001533 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001534 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001535 lStatus = BAD_VALUE;
1536 goto Exit;
1537 }
1538 }
1539 }
1540
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001542 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001543 if (track->getCblk() == NULL || track->name() < 0) {
1544 lStatus = NO_MEMORY;
1545 goto Exit;
1546 }
1547 mTracks.add(track);
1548
1549 sp<EffectChain> chain = getEffectChain_l(sessionId);
1550 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001551 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001552 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001553 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001554 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001556
1557 // invalidate track immediately if the stream type was moved to another thread since
1558 // createTrack() was called by the client process.
1559 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001560 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001561 this, streamType);
1562 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1563 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 }
1565 lStatus = NO_ERROR;
1566
1567Exit:
1568 if(status) {
1569 *status = lStatus;
1570 }
1571 return track;
1572}
1573
1574uint32_t AudioFlinger::PlaybackThread::latency() const
1575{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001576 Mutex::Autolock _l(mLock);
1577 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001578 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001579 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 return 0;
1581 }
1582}
1583
1584status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1585{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 mMasterVolume = value;
1587 return NO_ERROR;
1588}
1589
1590status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1591{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 mMasterMute = muted;
1593 return NO_ERROR;
1594}
1595
Glenn Kastenfff6d712012-01-12 16:38:12 -08001596status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 mStreamTypes[stream].volume = value;
1599 return NO_ERROR;
1600}
1601
Glenn Kastenfff6d712012-01-12 16:38:12 -08001602status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 mStreamTypes[stream].mute = muted;
1605 return NO_ERROR;
1606}
1607
Glenn Kastenfff6d712012-01-12 16:38:12 -08001608float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609{
1610 return mStreamTypes[stream].volume;
1611}
1612
Glenn Kastenfff6d712012-01-12 16:38:12 -08001613bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614{
1615 return mStreamTypes[stream].mute;
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)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001783 return AudioSystem::getStrategyForStream(track->streamType());
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");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 setMasterMute(true);
1948 }
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() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002164 mStreamTypes[track->streamType()].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
Glenn Kasten02bbd202012-02-08 12:35:35 -08002172 float typeVolume = mStreamTypes[track->streamType()].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];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002333 if (t->streamType() == 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");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 setMasterMute(true);
2664 }
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() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002706 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 left = right = 0;
2708 if (track->isPausing()) {
2709 track->setPaused();
2710 }
2711 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002712 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002713 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");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 setMasterMute(true);
3060 }
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) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003430 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003431
3432 // to track the speaker usage
3433 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434 }
3435 AudioSystem::releaseOutput(thread->id());
3436 }
3437 Mutex::Autolock _l(thread->mLock);
3438 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3439 playbackThread->destroyTrack_l(this);
3440 }
3441 }
3442}
3443
3444void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3445{
Glenn Kasten83d86532012-01-17 14:39:34 -08003446 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003447 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 -07003448 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003449 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003450 mStreamType,
3451 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003452 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453 mSessionId,
3454 mFrameCount,
3455 mState,
3456 mMute,
3457 mFillingUpStatus,
3458 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003459 vlr & 0xFFFF,
3460 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 mCblk->server,
3462 mCblk->user,
3463 (int)mMainBuffer,
3464 (int)mAuxBuffer);
3465}
3466
3467status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3468{
3469 audio_track_cblk_t* cblk = this->cblk();
3470 uint32_t framesReady;
3471 uint32_t framesReq = buffer->frameCount;
3472
3473 // Check if last stepServer failed, try to step now
3474 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3475 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003476 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3478 }
3479
3480 framesReady = cblk->framesReady();
3481
Glenn Kastenf6b16782011-12-15 09:51:17 -08003482 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003483 uint32_t s = cblk->server;
3484 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3485
3486 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3487 if (framesReq > framesReady) {
3488 framesReq = framesReady;
3489 }
3490 if (s + framesReq > bufferEnd) {
3491 framesReq = bufferEnd - s;
3492 }
3493
3494 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003495 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496
3497 buffer->frameCount = framesReq;
3498 return NO_ERROR;
3499 }
3500
3501getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003502 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003504 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003505 return NOT_ENOUGH_DATA;
3506}
3507
3508bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003509 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510
3511 if (mCblk->framesReady() >= mCblk->frameCount ||
3512 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3513 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003514 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 return true;
3516 }
3517 return false;
3518}
3519
3520status_t AudioFlinger::PlaybackThread::Track::start()
3521{
3522 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003523 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003524 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 sp<ThreadBase> thread = mThread.promote();
3526 if (thread != 0) {
3527 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003528 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 // here the track could be either new, or restarted
3530 // in both cases "unstop" the track
3531 if (mState == PAUSED) {
3532 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003533 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 } else {
3535 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003536 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537 }
3538
3539 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3540 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003541 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003542 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003543
3544 // to track the speaker usage
3545 if (status == NO_ERROR) {
3546 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 }
3549 if (status == NO_ERROR) {
3550 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3551 playbackThread->addTrack_l(this);
3552 } else {
3553 mState = state;
3554 }
3555 } else {
3556 status = BAD_VALUE;
3557 }
3558 return status;
3559}
3560
3561void AudioFlinger::PlaybackThread::Track::stop()
3562{
Steve Block3856b092011-10-20 11:56:00 +01003563 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003564 sp<ThreadBase> thread = mThread.promote();
3565 if (thread != 0) {
3566 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003567 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 if (mState > STOPPED) {
3569 mState = STOPPED;
3570 // If the track is not active (PAUSED and buffers full), flush buffers
3571 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3572 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3573 reset();
3574 }
Steve Block3856b092011-10-20 11:56:00 +01003575 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 }
3577 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3578 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003579 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003581
3582 // to track the speaker usage
3583 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003584 }
3585 }
3586}
3587
3588void AudioFlinger::PlaybackThread::Track::pause()
3589{
Steve Block3856b092011-10-20 11:56:00 +01003590 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 sp<ThreadBase> thread = mThread.promote();
3592 if (thread != 0) {
3593 Mutex::Autolock _l(thread->mLock);
3594 if (mState == ACTIVE || mState == RESUMING) {
3595 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003596 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 if (!isOutputTrack()) {
3598 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003599 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003601
3602 // to track the speaker usage
3603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 }
3605 }
3606 }
3607}
3608
3609void AudioFlinger::PlaybackThread::Track::flush()
3610{
Steve Block3856b092011-10-20 11:56:00 +01003611 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 sp<ThreadBase> thread = mThread.promote();
3613 if (thread != 0) {
3614 Mutex::Autolock _l(thread->mLock);
3615 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3616 return;
3617 }
3618 // No point remaining in PAUSED state after a flush => go to
3619 // STOPPED state
3620 mState = STOPPED;
3621
Eric Laurent38ccae22011-03-28 18:37:07 -07003622 // do not reset the track if it is still in the process of being stopped or paused.
3623 // this will be done by prepareTracks_l() when the track is stopped.
3624 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3625 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3626 reset();
3627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 }
3629}
3630
3631void AudioFlinger::PlaybackThread::Track::reset()
3632{
3633 // Do not reset twice to avoid discarding data written just after a flush and before
3634 // the audioflinger thread detects the track is stopped.
3635 if (!mResetDone) {
3636 TrackBase::reset();
3637 // Force underrun condition to avoid false underrun callback until first data is
3638 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003639 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3640 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641 mFillingUpStatus = FS_FILLING;
3642 mResetDone = true;
3643 }
3644}
3645
3646void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3647{
3648 mMute = muted;
3649}
3650
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3652{
3653 status_t status = DEAD_OBJECT;
3654 sp<ThreadBase> thread = mThread.promote();
3655 if (thread != 0) {
3656 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3657 status = playbackThread->attachAuxEffect(this, EffectId);
3658 }
3659 return status;
3660}
3661
3662void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3663{
3664 mAuxEffectId = EffectId;
3665 mAuxBuffer = buffer;
3666}
3667
3668// ----------------------------------------------------------------------------
3669
3670// RecordTrack constructor must be called with AudioFlinger::mLock held
3671AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3672 const wp<ThreadBase>& thread,
3673 const sp<Client>& client,
3674 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003675 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003676 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003677 int frameCount,
3678 uint32_t flags,
3679 int sessionId)
3680 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003681 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003682 mOverflow(false)
3683{
3684 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003685 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003686 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003687 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003688 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003689 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 } else {
3691 mCblk->frameSize = sizeof(int8_t);
3692 }
3693 }
3694}
3695
3696AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3697{
3698 sp<ThreadBase> thread = mThread.promote();
3699 if (thread != 0) {
3700 AudioSystem::releaseInput(thread->id());
3701 }
3702}
3703
3704status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3705{
3706 audio_track_cblk_t* cblk = this->cblk();
3707 uint32_t framesAvail;
3708 uint32_t framesReq = buffer->frameCount;
3709
3710 // Check if last stepServer failed, try to step now
3711 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3712 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003713 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3715 }
3716
3717 framesAvail = cblk->framesAvailable_l();
3718
Glenn Kastenf6b16782011-12-15 09:51:17 -08003719 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720 uint32_t s = cblk->server;
3721 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3722
3723 if (framesReq > framesAvail) {
3724 framesReq = framesAvail;
3725 }
3726 if (s + framesReq > bufferEnd) {
3727 framesReq = bufferEnd - s;
3728 }
3729
3730 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003731 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003732
3733 buffer->frameCount = framesReq;
3734 return NO_ERROR;
3735 }
3736
3737getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003738 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003739 buffer->frameCount = 0;
3740 return NOT_ENOUGH_DATA;
3741}
3742
3743status_t AudioFlinger::RecordThread::RecordTrack::start()
3744{
3745 sp<ThreadBase> thread = mThread.promote();
3746 if (thread != 0) {
3747 RecordThread *recordThread = (RecordThread *)thread.get();
3748 return recordThread->start(this);
3749 } else {
3750 return BAD_VALUE;
3751 }
3752}
3753
3754void AudioFlinger::RecordThread::RecordTrack::stop()
3755{
3756 sp<ThreadBase> thread = mThread.promote();
3757 if (thread != 0) {
3758 RecordThread *recordThread = (RecordThread *)thread.get();
3759 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003760 TrackBase::reset();
3761 // Force overerrun condition to avoid false overrun callback until first data is
3762 // read from buffer
3763 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764 }
3765}
3766
3767void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3768{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003769 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003770 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003772 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773 mSessionId,
3774 mFrameCount,
3775 mState,
3776 mCblk->sampleRate,
3777 mCblk->server,
3778 mCblk->user);
3779}
3780
3781
3782// ----------------------------------------------------------------------------
3783
3784AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3785 const wp<ThreadBase>& thread,
3786 DuplicatingThread *sourceThread,
3787 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003788 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003789 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003791 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003792 mActive(false), mSourceThread(sourceThread)
3793{
3794
3795 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3796 if (mCblk != NULL) {
3797 mCblk->flags |= CBLK_DIRECTION_OUT;
3798 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 mOutBuffer.frameCount = 0;
3800 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003801 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003802 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3803 mCblk, mBuffer, mCblk->buffers,
3804 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003806 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003807 }
3808}
3809
3810AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3811{
3812 clearBufferQueue();
3813}
3814
3815status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3816{
3817 status_t status = Track::start();
3818 if (status != NO_ERROR) {
3819 return status;
3820 }
3821
3822 mActive = true;
3823 mRetryCount = 127;
3824 return status;
3825}
3826
3827void AudioFlinger::PlaybackThread::OutputTrack::stop()
3828{
3829 Track::stop();
3830 clearBufferQueue();
3831 mOutBuffer.frameCount = 0;
3832 mActive = false;
3833}
3834
3835bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3836{
3837 Buffer *pInBuffer;
3838 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003839 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840 bool outputBufferFull = false;
3841 inBuffer.frameCount = frames;
3842 inBuffer.i16 = data;
3843
3844 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3845
3846 if (!mActive && frames != 0) {
3847 start();
3848 sp<ThreadBase> thread = mThread.promote();
3849 if (thread != 0) {
3850 MixerThread *mixerThread = (MixerThread *)thread.get();
3851 if (mCblk->frameCount > frames){
3852 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3853 uint32_t startFrames = (mCblk->frameCount - frames);
3854 pInBuffer = new Buffer;
3855 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3856 pInBuffer->frameCount = startFrames;
3857 pInBuffer->i16 = pInBuffer->mBuffer;
3858 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3859 mBufferQueue.add(pInBuffer);
3860 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003861 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003862 }
3863 }
3864 }
3865 }
3866
3867 while (waitTimeLeftMs) {
3868 // First write pending buffers, then new data
3869 if (mBufferQueue.size()) {
3870 pInBuffer = mBufferQueue.itemAt(0);
3871 } else {
3872 pInBuffer = &inBuffer;
3873 }
3874
3875 if (pInBuffer->frameCount == 0) {
3876 break;
3877 }
3878
3879 if (mOutBuffer.frameCount == 0) {
3880 mOutBuffer.frameCount = pInBuffer->frameCount;
3881 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003882 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003883 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003884 outputBufferFull = true;
3885 break;
3886 }
3887 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3888 if (waitTimeLeftMs >= waitTimeMs) {
3889 waitTimeLeftMs -= waitTimeMs;
3890 } else {
3891 waitTimeLeftMs = 0;
3892 }
3893 }
3894
3895 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3896 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3897 mCblk->stepUser(outFrames);
3898 pInBuffer->frameCount -= outFrames;
3899 pInBuffer->i16 += outFrames * channelCount;
3900 mOutBuffer.frameCount -= outFrames;
3901 mOutBuffer.i16 += outFrames * channelCount;
3902
3903 if (pInBuffer->frameCount == 0) {
3904 if (mBufferQueue.size()) {
3905 mBufferQueue.removeAt(0);
3906 delete [] pInBuffer->mBuffer;
3907 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003908 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 } else {
3910 break;
3911 }
3912 }
3913 }
3914
3915 // If we could not write all frames, allocate a buffer and queue it for next time.
3916 if (inBuffer.frameCount) {
3917 sp<ThreadBase> thread = mThread.promote();
3918 if (thread != 0 && !thread->standby()) {
3919 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3920 pInBuffer = new Buffer;
3921 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3922 pInBuffer->frameCount = inBuffer.frameCount;
3923 pInBuffer->i16 = pInBuffer->mBuffer;
3924 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3925 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003926 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003928 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 }
3930 }
3931 }
3932
3933 // Calling write() with a 0 length buffer, means that no more data will be written:
3934 // If no more buffers are pending, fill output track buffer to make sure it is started
3935 // by output mixer.
3936 if (frames == 0 && mBufferQueue.size() == 0) {
3937 if (mCblk->user < mCblk->frameCount) {
3938 frames = mCblk->frameCount - mCblk->user;
3939 pInBuffer = new Buffer;
3940 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3941 pInBuffer->frameCount = frames;
3942 pInBuffer->i16 = pInBuffer->mBuffer;
3943 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3944 mBufferQueue.add(pInBuffer);
3945 } else if (mActive) {
3946 stop();
3947 }
3948 }
3949
3950 return outputBufferFull;
3951}
3952
3953status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3954{
3955 int active;
3956 status_t result;
3957 audio_track_cblk_t* cblk = mCblk;
3958 uint32_t framesReq = buffer->frameCount;
3959
Steve Block3856b092011-10-20 11:56:00 +01003960// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961 buffer->frameCount = 0;
3962
3963 uint32_t framesAvail = cblk->framesAvailable();
3964
3965
3966 if (framesAvail == 0) {
3967 Mutex::Autolock _l(cblk->lock);
3968 goto start_loop_here;
3969 while (framesAvail == 0) {
3970 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003971 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003972 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003973 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 }
3975 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3976 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003977 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 }
3979 // read the server count again
3980 start_loop_here:
3981 framesAvail = cblk->framesAvailable_l();
3982 }
3983 }
3984
3985// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003986// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987// }
3988
3989 if (framesReq > framesAvail) {
3990 framesReq = framesAvail;
3991 }
3992
3993 uint32_t u = cblk->user;
3994 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3995
3996 if (u + framesReq > bufferEnd) {
3997 framesReq = bufferEnd - u;
3998 }
3999
4000 buffer->frameCount = framesReq;
4001 buffer->raw = (void *)cblk->buffer(u);
4002 return NO_ERROR;
4003}
4004
4005
4006void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4007{
4008 size_t size = mBufferQueue.size();
4009 Buffer *pBuffer;
4010
4011 for (size_t i = 0; i < size; i++) {
4012 pBuffer = mBufferQueue.itemAt(i);
4013 delete [] pBuffer->mBuffer;
4014 delete pBuffer;
4015 }
4016 mBufferQueue.clear();
4017}
4018
4019// ----------------------------------------------------------------------------
4020
4021AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4022 : RefBase(),
4023 mAudioFlinger(audioFlinger),
4024 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4025 mPid(pid)
4026{
4027 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4028}
4029
4030// Client destructor must be called with AudioFlinger::mLock held
4031AudioFlinger::Client::~Client()
4032{
4033 mAudioFlinger->removeClient_l(mPid);
4034}
4035
Glenn Kasten435dbe62012-01-30 10:15:48 -08004036sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037{
4038 return mMemoryDealer;
4039}
4040
4041// ----------------------------------------------------------------------------
4042
4043AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4044 const sp<IAudioFlingerClient>& client,
4045 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004046 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047{
4048}
4049
4050AudioFlinger::NotificationClient::~NotificationClient()
4051{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052}
4053
4054void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4055{
4056 sp<NotificationClient> keep(this);
4057 {
4058 mAudioFlinger->removeNotificationClient(mPid);
4059 }
4060}
4061
4062// ----------------------------------------------------------------------------
4063
4064AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4065 : BnAudioTrack(),
4066 mTrack(track)
4067{
4068}
4069
4070AudioFlinger::TrackHandle::~TrackHandle() {
4071 // just stop the track on deletion, associated resources
4072 // will be freed from the main thread once all pending buffers have
4073 // been played. Unless it's not in the active track list, in which
4074 // case we free everything now...
4075 mTrack->destroy();
4076}
4077
Glenn Kasten90716c52012-01-26 13:40:12 -08004078sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4079 return mTrack->getCblk();
4080}
4081
Mathias Agopian65ab4712010-07-14 17:59:35 -07004082status_t AudioFlinger::TrackHandle::start() {
4083 return mTrack->start();
4084}
4085
4086void AudioFlinger::TrackHandle::stop() {
4087 mTrack->stop();
4088}
4089
4090void AudioFlinger::TrackHandle::flush() {
4091 mTrack->flush();
4092}
4093
4094void AudioFlinger::TrackHandle::mute(bool e) {
4095 mTrack->mute(e);
4096}
4097
4098void AudioFlinger::TrackHandle::pause() {
4099 mTrack->pause();
4100}
4101
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4103{
4104 return mTrack->attachAuxEffect(EffectId);
4105}
4106
4107status_t AudioFlinger::TrackHandle::onTransact(
4108 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4109{
4110 return BnAudioTrack::onTransact(code, data, reply, flags);
4111}
4112
4113// ----------------------------------------------------------------------------
4114
4115sp<IAudioRecord> AudioFlinger::openRecord(
4116 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004117 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004119 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004120 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004121 int frameCount,
4122 uint32_t flags,
4123 int *sessionId,
4124 status_t *status)
4125{
4126 sp<RecordThread::RecordTrack> recordTrack;
4127 sp<RecordHandle> recordHandle;
4128 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129 status_t lStatus;
4130 RecordThread *thread;
4131 size_t inFrameCount;
4132 int lSessionId;
4133
4134 // check calling permissions
4135 if (!recordingAllowed()) {
4136 lStatus = PERMISSION_DENIED;
4137 goto Exit;
4138 }
4139
4140 // add client to list
4141 { // scope for mLock
4142 Mutex::Autolock _l(mLock);
4143 thread = checkRecordThread_l(input);
4144 if (thread == NULL) {
4145 lStatus = BAD_VALUE;
4146 goto Exit;
4147 }
4148
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004149 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150
4151 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004152 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 lSessionId = *sessionId;
4154 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004155 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004156 if (sessionId != NULL) {
4157 *sessionId = lSessionId;
4158 }
4159 }
4160 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004161 recordTrack = thread->createRecordTrack_l(client,
4162 sampleRate,
4163 format,
4164 channelMask,
4165 frameCount,
4166 flags,
4167 lSessionId,
4168 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004169 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004170 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4172 // destructor is called by the TrackBase destructor with mLock held
4173 client.clear();
4174 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 goto Exit;
4176 }
4177
4178 // return to handle to client
4179 recordHandle = new RecordHandle(recordTrack);
4180 lStatus = NO_ERROR;
4181
4182Exit:
4183 if (status) {
4184 *status = lStatus;
4185 }
4186 return recordHandle;
4187}
4188
4189// ----------------------------------------------------------------------------
4190
4191AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4192 : BnAudioRecord(),
4193 mRecordTrack(recordTrack)
4194{
4195}
4196
4197AudioFlinger::RecordHandle::~RecordHandle() {
4198 stop();
4199}
4200
Glenn Kasten90716c52012-01-26 13:40:12 -08004201sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4202 return mRecordTrack->getCblk();
4203}
4204
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004206 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004207 return mRecordTrack->start();
4208}
4209
4210void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004211 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 mRecordTrack->stop();
4213}
4214
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215status_t AudioFlinger::RecordHandle::onTransact(
4216 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4217{
4218 return BnAudioRecord::onTransact(code, data, reply, flags);
4219}
4220
4221// ----------------------------------------------------------------------------
4222
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004223AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4224 AudioStreamIn *input,
4225 uint32_t sampleRate,
4226 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004227 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004228 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004229 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004230 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4231 // mRsmpInIndex and mInputBytes set by readInputParameters()
4232 mReqChannelCount(popcount(channels)),
4233 mReqSampleRate(sampleRate)
4234 // mBytesRead is only meaningful while active, and so is cleared in start()
4235 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004237 snprintf(mName, kNameLength, "AudioIn_%d", id);
4238
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 readInputParameters();
4240}
4241
4242
4243AudioFlinger::RecordThread::~RecordThread()
4244{
4245 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004246 delete mResampler;
4247 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248}
4249
4250void AudioFlinger::RecordThread::onFirstRef()
4251{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004252 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253}
4254
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004255status_t AudioFlinger::RecordThread::readyToRun()
4256{
4257 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004258 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004259 return status;
4260}
4261
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262bool AudioFlinger::RecordThread::threadLoop()
4263{
4264 AudioBufferProvider::Buffer buffer;
4265 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004266 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267
Eric Laurent44d98482010-09-30 16:12:31 -07004268 nsecs_t lastWarning = 0;
4269
Eric Laurentfeb0db62011-07-22 09:04:31 -07004270 acquireWakeLock();
4271
Mathias Agopian65ab4712010-07-14 17:59:35 -07004272 // start recording
4273 while (!exitPending()) {
4274
4275 processConfigEvents();
4276
4277 { // scope for mLock
4278 Mutex::Autolock _l(mLock);
4279 checkForNewParameters_l();
4280 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4281 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004282 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 mStandby = true;
4284 }
4285
4286 if (exitPending()) break;
4287
Eric Laurentfeb0db62011-07-22 09:04:31 -07004288 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004289 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 // go to sleep
4291 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004292 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004293 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 continue;
4295 }
4296 if (mActiveTrack != 0) {
4297 if (mActiveTrack->mState == TrackBase::PAUSING) {
4298 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004299 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004300 mStandby = true;
4301 }
4302 mActiveTrack.clear();
4303 mStartStopCond.broadcast();
4304 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4305 if (mReqChannelCount != mActiveTrack->channelCount()) {
4306 mActiveTrack.clear();
4307 mStartStopCond.broadcast();
4308 } else if (mBytesRead != 0) {
4309 // record start succeeds only if first read from audio input
4310 // succeeds
4311 if (mBytesRead > 0) {
4312 mActiveTrack->mState = TrackBase::ACTIVE;
4313 } else {
4314 mActiveTrack.clear();
4315 }
4316 mStartStopCond.broadcast();
4317 }
4318 mStandby = false;
4319 }
4320 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004321 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 }
4323
4324 if (mActiveTrack != 0) {
4325 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4326 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004327 unlockEffectChains(effectChains);
4328 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004329 continue;
4330 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004331 for (size_t i = 0; i < effectChains.size(); i ++) {
4332 effectChains[i]->process_l();
4333 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004334
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004336 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004338 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004339 // no resampling
4340 while (framesOut) {
4341 size_t framesIn = mFrameCount - mRsmpInIndex;
4342 if (framesIn) {
4343 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4344 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4345 if (framesIn > framesOut)
4346 framesIn = framesOut;
4347 mRsmpInIndex += framesIn;
4348 framesOut -= framesIn;
4349 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004350 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004351 memcpy(dst, src, framesIn * mFrameSize);
4352 } else {
4353 int16_t *src16 = (int16_t *)src;
4354 int16_t *dst16 = (int16_t *)dst;
4355 if (mChannelCount == 1) {
4356 while (framesIn--) {
4357 *dst16++ = *src16;
4358 *dst16++ = *src16++;
4359 }
4360 } else {
4361 while (framesIn--) {
4362 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4363 src16 += 2;
4364 }
4365 }
4366 }
4367 }
4368 if (framesOut && mFrameCount == mRsmpInIndex) {
4369 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004370 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004371 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004372 framesOut = 0;
4373 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004374 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 mRsmpInIndex = 0;
4376 }
4377 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004378 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4380 // Force input into standby so that it tries to
4381 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004382 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004383 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 }
4385 mRsmpInIndex = mFrameCount;
4386 framesOut = 0;
4387 buffer.frameCount = 0;
4388 }
4389 }
4390 }
4391 } else {
4392 // resampling
4393
4394 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4395 // alter output frame count as if we were expecting stereo samples
4396 if (mChannelCount == 1 && mReqChannelCount == 1) {
4397 framesOut >>= 1;
4398 }
4399 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4400 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4401 // are 32 bit aligned which should be always true.
4402 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004403 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 // the resampler always outputs stereo samples: do post stereo to mono conversion
4405 int16_t *src = (int16_t *)mRsmpOutBuffer;
4406 int16_t *dst = buffer.i16;
4407 while (framesOut--) {
4408 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4409 src += 2;
4410 }
4411 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004412 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 }
4414
4415 }
4416 mActiveTrack->releaseBuffer(&buffer);
4417 mActiveTrack->overflow();
4418 }
4419 // client isn't retrieving buffers fast enough
4420 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004421 if (!mActiveTrack->setOverflow()) {
4422 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004423 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004424 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004425 lastWarning = now;
4426 }
4427 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 // Release the processor for a while before asking for a new buffer.
4429 // This will give the application more chance to read from the buffer and
4430 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004431 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 }
4433 }
Eric Laurentec437d82011-07-26 20:54:46 -07004434 // enable changes in effect chain
4435 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004436 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 }
4438
4439 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004440 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 }
4442 mActiveTrack.clear();
4443
4444 mStartStopCond.broadcast();
4445
Eric Laurentfeb0db62011-07-22 09:04:31 -07004446 releaseWakeLock();
4447
Steve Block3856b092011-10-20 11:56:00 +01004448 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 return false;
4450}
4451
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004452
4453sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4454 const sp<AudioFlinger::Client>& client,
4455 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004456 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004457 int channelMask,
4458 int frameCount,
4459 uint32_t flags,
4460 int sessionId,
4461 status_t *status)
4462{
4463 sp<RecordTrack> track;
4464 status_t lStatus;
4465
4466 lStatus = initCheck();
4467 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004468 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004469 goto Exit;
4470 }
4471
4472 { // scope for mLock
4473 Mutex::Autolock _l(mLock);
4474
4475 track = new RecordTrack(this, client, sampleRate,
4476 format, channelMask, frameCount, flags, sessionId);
4477
Glenn Kasten7378ca52012-01-20 13:44:40 -08004478 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004479 lStatus = NO_MEMORY;
4480 goto Exit;
4481 }
4482
4483 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004484 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4485 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004486 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004487 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4488 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004489 }
4490 lStatus = NO_ERROR;
4491
4492Exit:
4493 if (status) {
4494 *status = lStatus;
4495 }
4496 return track;
4497}
4498
Mathias Agopian65ab4712010-07-14 17:59:35 -07004499status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4500{
Steve Block3856b092011-10-20 11:56:00 +01004501 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 sp <ThreadBase> strongMe = this;
4503 status_t status = NO_ERROR;
4504 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004505 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004506 if (mActiveTrack != 0) {
4507 if (recordTrack != mActiveTrack.get()) {
4508 status = -EBUSY;
4509 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4510 mActiveTrack->mState = TrackBase::ACTIVE;
4511 }
4512 return status;
4513 }
4514
4515 recordTrack->mState = TrackBase::IDLE;
4516 mActiveTrack = recordTrack;
4517 mLock.unlock();
4518 status_t status = AudioSystem::startInput(mId);
4519 mLock.lock();
4520 if (status != NO_ERROR) {
4521 mActiveTrack.clear();
4522 return status;
4523 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004524 mRsmpInIndex = mFrameCount;
4525 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004526 if (mResampler != NULL) {
4527 mResampler->reset();
4528 }
4529 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004531 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 mWaitWorkCV.signal();
4533 // do not wait for mStartStopCond if exiting
4534 if (mExiting) {
4535 mActiveTrack.clear();
4536 status = INVALID_OPERATION;
4537 goto startError;
4538 }
4539 mStartStopCond.wait(mLock);
4540 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004541 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 status = BAD_VALUE;
4543 goto startError;
4544 }
Steve Block3856b092011-10-20 11:56:00 +01004545 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 return status;
4547 }
4548startError:
4549 AudioSystem::stopInput(mId);
4550 return status;
4551}
4552
4553void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004554 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 sp <ThreadBase> strongMe = this;
4556 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004557 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4559 mActiveTrack->mState = TrackBase::PAUSING;
4560 // do not wait for mStartStopCond if exiting
4561 if (mExiting) {
4562 return;
4563 }
4564 mStartStopCond.wait(mLock);
4565 // if we have been restarted, recordTrack == mActiveTrack.get() here
4566 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4567 mLock.unlock();
4568 AudioSystem::stopInput(mId);
4569 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004570 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004571 }
4572 }
4573 }
4574}
4575
4576status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4577{
4578 const size_t SIZE = 256;
4579 char buffer[SIZE];
4580 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581
4582 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4583 result.append(buffer);
4584
4585 if (mActiveTrack != 0) {
4586 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004587 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004588 mActiveTrack->dump(buffer, SIZE);
4589 result.append(buffer);
4590
4591 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4592 result.append(buffer);
4593 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4594 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004595 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596 result.append(buffer);
4597 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4598 result.append(buffer);
4599 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4600 result.append(buffer);
4601
4602
4603 } else {
4604 result.append("No record client\n");
4605 }
4606 write(fd, result.string(), result.size());
4607
4608 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004609 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610
4611 return NO_ERROR;
4612}
4613
4614status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4615{
4616 size_t framesReq = buffer->frameCount;
4617 size_t framesReady = mFrameCount - mRsmpInIndex;
4618 int channelCount;
4619
4620 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004621 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004623 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4625 // Force input into standby so that it tries to
4626 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004627 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004628 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004629 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004630 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 buffer->frameCount = 0;
4632 return NOT_ENOUGH_DATA;
4633 }
4634 mRsmpInIndex = 0;
4635 framesReady = mFrameCount;
4636 }
4637
4638 if (framesReq > framesReady) {
4639 framesReq = framesReady;
4640 }
4641
4642 if (mChannelCount == 1 && mReqChannelCount == 2) {
4643 channelCount = 1;
4644 } else {
4645 channelCount = 2;
4646 }
4647 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4648 buffer->frameCount = framesReq;
4649 return NO_ERROR;
4650}
4651
4652void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4653{
4654 mRsmpInIndex += buffer->frameCount;
4655 buffer->frameCount = 0;
4656}
4657
4658bool AudioFlinger::RecordThread::checkForNewParameters_l()
4659{
4660 bool reconfig = false;
4661
4662 while (!mNewParameters.isEmpty()) {
4663 status_t status = NO_ERROR;
4664 String8 keyValuePair = mNewParameters[0];
4665 AudioParameter param = AudioParameter(keyValuePair);
4666 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004667 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004668 int reqSamplingRate = mReqSampleRate;
4669 int reqChannelCount = mReqChannelCount;
4670
4671 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4672 reqSamplingRate = value;
4673 reconfig = true;
4674 }
4675 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004676 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 reconfig = true;
4678 }
4679 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004680 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004681 reconfig = true;
4682 }
4683 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4684 // do not accept frame count changes if tracks are open as the track buffer
4685 // size depends on frame count and correct behavior would not be garantied
4686 // if frame count is changed after track creation
4687 if (mActiveTrack != 0) {
4688 status = INVALID_OPERATION;
4689 } else {
4690 reconfig = true;
4691 }
4692 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004693 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4694 // forward device change to effects that have requested to be
4695 // aware of attached audio device.
4696 for (size_t i = 0; i < mEffectChains.size(); i++) {
4697 mEffectChains[i]->setDevice_l(value);
4698 }
4699 // store input device and output device but do not forward output device to audio HAL.
4700 // Note that status is ignored by the caller for output device
4701 // (see AudioFlinger::setParameters()
4702 if (value & AUDIO_DEVICE_OUT_ALL) {
4703 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4704 status = BAD_VALUE;
4705 } else {
4706 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004707 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4708 if (mTrack != NULL) {
4709 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004710 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004711 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4712 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4713 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004714 }
4715 mDevice |= (uint32_t)value;
4716 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004718 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004720 mInput->stream->common.standby(&mInput->stream->common);
4721 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004722 }
4723 if (reconfig) {
4724 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004725 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004726 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004727 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4728 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004729 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730 status = NO_ERROR;
4731 }
4732 if (status == NO_ERROR) {
4733 readInputParameters();
4734 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4735 }
4736 }
4737 }
4738
4739 mNewParameters.removeAt(0);
4740
4741 mParamStatus = status;
4742 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004743 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4744 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004745 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746 }
4747 return reconfig;
4748}
4749
4750String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4751{
Dima Zavinfce7a472011-04-19 22:30:36 -07004752 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004753 String8 out_s8 = String8();
4754
4755 Mutex::Autolock _l(mLock);
4756 if (initCheck() != NO_ERROR) {
4757 return out_s8;
4758 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004759
Dima Zavin799a70e2011-04-18 16:57:27 -07004760 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004761 out_s8 = String8(s);
4762 free(s);
4763 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004764}
4765
4766void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4767 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004768 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004769
4770 switch (event) {
4771 case AudioSystem::INPUT_OPENED:
4772 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004773 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004774 desc.samplingRate = mSampleRate;
4775 desc.format = mFormat;
4776 desc.frameCount = mFrameCount;
4777 desc.latency = 0;
4778 param2 = &desc;
4779 break;
4780
4781 case AudioSystem::INPUT_CLOSED:
4782 default:
4783 break;
4784 }
4785 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4786}
4787
4788void AudioFlinger::RecordThread::readInputParameters()
4789{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004790 delete mRsmpInBuffer;
4791 // mRsmpInBuffer is always assigned a new[] below
4792 delete mRsmpOutBuffer;
4793 mRsmpOutBuffer = NULL;
4794 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004795 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004796
Dima Zavin799a70e2011-04-18 16:57:27 -07004797 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004798 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4799 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004800 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004801 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004802 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803 mFrameCount = mInputBytes / mFrameSize;
4804 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4805
4806 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4807 {
4808 int channelCount;
4809 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4810 // stereo to mono post process as the resampler always outputs stereo.
4811 if (mChannelCount == 1 && mReqChannelCount == 2) {
4812 channelCount = 1;
4813 } else {
4814 channelCount = 2;
4815 }
4816 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4817 mResampler->setSampleRate(mSampleRate);
4818 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4819 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4820
4821 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4822 if (mChannelCount == 1 && mReqChannelCount == 1) {
4823 mFrameCount >>= 1;
4824 }
4825
4826 }
4827 mRsmpInIndex = mFrameCount;
4828}
4829
4830unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4831{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004832 Mutex::Autolock _l(mLock);
4833 if (initCheck() != NO_ERROR) {
4834 return 0;
4835 }
4836
Dima Zavin799a70e2011-04-18 16:57:27 -07004837 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004838}
4839
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004840uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4841{
4842 Mutex::Autolock _l(mLock);
4843 uint32_t result = 0;
4844 if (getEffectChain_l(sessionId) != 0) {
4845 result = EFFECT_SESSION;
4846 }
4847
4848 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4849 result |= TRACK_SESSION;
4850 }
4851
4852 return result;
4853}
4854
Eric Laurent59bd0da2011-08-01 09:52:20 -07004855AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4856{
4857 Mutex::Autolock _l(mLock);
4858 return mTrack;
4859}
4860
Glenn Kastenaed850d2012-01-26 09:46:34 -08004861AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004862{
4863 Mutex::Autolock _l(mLock);
4864 return mInput;
4865}
4866
4867AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4868{
4869 Mutex::Autolock _l(mLock);
4870 AudioStreamIn *input = mInput;
4871 mInput = NULL;
4872 return input;
4873}
4874
4875// this method must always be called either with ThreadBase mLock held or inside the thread loop
4876audio_stream_t* AudioFlinger::RecordThread::stream()
4877{
4878 if (mInput == NULL) {
4879 return NULL;
4880 }
4881 return &mInput->stream->common;
4882}
4883
4884
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885// ----------------------------------------------------------------------------
4886
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004887audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004888 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004889 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890 uint32_t *pChannels,
4891 uint32_t *pLatencyMs,
4892 uint32_t flags)
4893{
4894 status_t status;
4895 PlaybackThread *thread = NULL;
4896 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4897 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004898 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899 uint32_t channels = pChannels ? *pChannels : 0;
4900 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004901 audio_stream_out_t *outStream;
4902 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004903
Steve Block3856b092011-10-20 11:56:00 +01004904 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905 pDevices ? *pDevices : 0,
4906 samplingRate,
4907 format,
4908 channels,
4909 flags);
4910
4911 if (pDevices == NULL || *pDevices == 0) {
4912 return 0;
4913 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004914
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915 Mutex::Autolock _l(mLock);
4916
Dima Zavin799a70e2011-04-18 16:57:27 -07004917 outHwDev = findSuitableHwDev_l(*pDevices);
4918 if (outHwDev == NULL)
4919 return 0;
4920
Glenn Kasten58f30212012-01-12 12:27:51 -08004921 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004922 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004923 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004924 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004925 samplingRate,
4926 format,
4927 channels,
4928 status);
4929
4930 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004931 if (outStream != NULL) {
4932 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004933 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004934
Dima Zavinfce7a472011-04-19 22:30:36 -07004935 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4936 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4937 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004939 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 } else {
4941 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004942 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004943 }
4944 mPlaybackThreads.add(id, thread);
4945
Glenn Kastena0d68332012-01-27 16:47:15 -08004946 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4947 if (pFormat != NULL) *pFormat = format;
4948 if (pChannels != NULL) *pChannels = channels;
4949 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950
4951 // notify client processes of the new output creation
4952 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4953 return id;
4954 }
4955
4956 return 0;
4957}
4958
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004959audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4960 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004961{
4962 Mutex::Autolock _l(mLock);
4963 MixerThread *thread1 = checkMixerThread_l(output1);
4964 MixerThread *thread2 = checkMixerThread_l(output2);
4965
4966 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004967 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968 return 0;
4969 }
4970
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004971 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4973 thread->addOutputTrack(thread2);
4974 mPlaybackThreads.add(id, thread);
4975 // notify client processes of the new output creation
4976 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4977 return id;
4978}
4979
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004980status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981{
4982 // keep strong reference on the playback thread so that
4983 // it is not destroyed while exit() is executed
4984 sp <PlaybackThread> thread;
4985 {
4986 Mutex::Autolock _l(mLock);
4987 thread = checkPlaybackThread_l(output);
4988 if (thread == NULL) {
4989 return BAD_VALUE;
4990 }
4991
Steve Block3856b092011-10-20 11:56:00 +01004992 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004994 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004995 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004996 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004997 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4998 dupThread->removeOutputTrack((MixerThread *)thread.get());
4999 }
5000 }
5001 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005002 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5004 mPlaybackThreads.removeItem(output);
5005 }
5006 thread->exit();
5007
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005008 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005009 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005010 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005011 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005012 out->hwDev->close_output_stream(out->hwDev, out->stream);
5013 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005014 }
5015 return NO_ERROR;
5016}
5017
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005018status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005019{
5020 Mutex::Autolock _l(mLock);
5021 PlaybackThread *thread = checkPlaybackThread_l(output);
5022
5023 if (thread == NULL) {
5024 return BAD_VALUE;
5025 }
5026
Steve Block3856b092011-10-20 11:56:00 +01005027 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005028 thread->suspend();
5029
5030 return NO_ERROR;
5031}
5032
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005033status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034{
5035 Mutex::Autolock _l(mLock);
5036 PlaybackThread *thread = checkPlaybackThread_l(output);
5037
5038 if (thread == NULL) {
5039 return BAD_VALUE;
5040 }
5041
Steve Block3856b092011-10-20 11:56:00 +01005042 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043
5044 thread->restore();
5045
5046 return NO_ERROR;
5047}
5048
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005049audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005051 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005053 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005054{
5055 status_t status;
5056 RecordThread *thread = NULL;
5057 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005058 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005059 uint32_t channels = pChannels ? *pChannels : 0;
5060 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005061 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005063 audio_stream_in_t *inStream;
5064 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065
5066 if (pDevices == NULL || *pDevices == 0) {
5067 return 0;
5068 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005069
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 Mutex::Autolock _l(mLock);
5071
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 inHwDev = findSuitableHwDev_l(*pDevices);
5073 if (inHwDev == NULL)
5074 return 0;
5075
Glenn Kasten58f30212012-01-12 12:27:51 -08005076 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005077 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005078 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005079 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005080 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 samplingRate,
5083 format,
5084 channels,
5085 acoustics,
5086 status);
5087
5088 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5089 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5090 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005091 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005092 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005094 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005095 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005096 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005097 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005098 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005099 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 }
5101
Dima Zavin799a70e2011-04-18 16:57:27 -07005102 if (inStream != NULL) {
5103 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5104
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005105 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005106 // Start record thread
5107 // RecorThread require both input and output device indication to forward to audio
5108 // pre processing modules
5109 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5110 thread = new RecordThread(this,
5111 input,
5112 reqSamplingRate,
5113 reqChannels,
5114 id,
5115 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005117 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005118 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5119 if (pFormat != NULL) *pFormat = format;
5120 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005121
Dima Zavin799a70e2011-04-18 16:57:27 -07005122 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123
5124 // notify client processes of the new input creation
5125 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5126 return id;
5127 }
5128
5129 return 0;
5130}
5131
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005132status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133{
5134 // keep strong reference on the record thread so that
5135 // it is not destroyed while exit() is executed
5136 sp <RecordThread> thread;
5137 {
5138 Mutex::Autolock _l(mLock);
5139 thread = checkRecordThread_l(input);
5140 if (thread == NULL) {
5141 return BAD_VALUE;
5142 }
5143
Steve Block3856b092011-10-20 11:56:00 +01005144 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005145 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5147 mRecordThreads.removeItem(input);
5148 }
5149 thread->exit();
5150
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005151 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005152 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005153 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005154 in->hwDev->close_input_stream(in->hwDev, in->stream);
5155 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005156
5157 return NO_ERROR;
5158}
5159
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005160status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161{
5162 Mutex::Autolock _l(mLock);
5163 MixerThread *dstThread = checkMixerThread_l(output);
5164 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005165 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 return BAD_VALUE;
5167 }
5168
Steve Block3856b092011-10-20 11:56:00 +01005169 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5171
Eric Laurent9f6530f2011-08-30 10:18:54 -07005172 dstThread->setStreamValid(stream, true);
5173
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5175 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5176 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005177 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005179 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005181 }
Eric Laurentde070132010-07-13 04:45:46 -07005182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183
5184 return NO_ERROR;
5185}
5186
5187
5188int AudioFlinger::newAudioSessionId()
5189{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005190 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191}
5192
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005193void AudioFlinger::acquireAudioSessionId(int audioSession)
5194{
5195 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005196 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005197 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005198 int num = mAudioSessionRefs.size();
5199 for (int i = 0; i< num; i++) {
5200 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5201 if (ref->sessionid == audioSession && ref->pid == caller) {
5202 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005203 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005204 return;
5205 }
5206 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005207 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5208 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005209}
5210
5211void AudioFlinger::releaseAudioSessionId(int audioSession)
5212{
5213 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005214 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005215 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005216 int num = mAudioSessionRefs.size();
5217 for (int i = 0; i< num; i++) {
5218 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5219 if (ref->sessionid == audioSession && ref->pid == caller) {
5220 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005221 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005222 if (ref->cnt == 0) {
5223 mAudioSessionRefs.removeAt(i);
5224 delete ref;
5225 purgeStaleEffects_l();
5226 }
5227 return;
5228 }
5229 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005230 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005231}
5232
5233void AudioFlinger::purgeStaleEffects_l() {
5234
Steve Block3856b092011-10-20 11:56:00 +01005235 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005236
5237 Vector< sp<EffectChain> > chains;
5238
5239 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5240 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5241 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5242 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005243 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5244 chains.push(ec);
5245 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005246 }
5247 }
5248 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5249 sp<RecordThread> t = mRecordThreads.valueAt(i);
5250 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5251 sp<EffectChain> ec = t->mEffectChains[j];
5252 chains.push(ec);
5253 }
5254 }
5255
5256 for (size_t i = 0; i < chains.size(); i++) {
5257 sp<EffectChain> ec = chains[i];
5258 int sessionid = ec->sessionId();
5259 sp<ThreadBase> t = ec->mThread.promote();
5260 if (t == 0) {
5261 continue;
5262 }
5263 size_t numsessionrefs = mAudioSessionRefs.size();
5264 bool found = false;
5265 for (size_t k = 0; k < numsessionrefs; k++) {
5266 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5267 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005268 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005269 sessionid, ref->pid, ref->cnt);
5270 found = true;
5271 break;
5272 }
5273 }
5274 if (!found) {
5275 // remove all effects from the chain
5276 while (ec->mEffects.size()) {
5277 sp<EffectModule> effect = ec->mEffects[0];
5278 effect->unPin();
5279 Mutex::Autolock _l (t->mLock);
5280 t->removeEffect_l(effect);
5281 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5282 sp<EffectHandle> handle = effect->mHandles[j].promote();
5283 if (handle != 0) {
5284 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005285 if (handle->mHasControl && handle->mEnabled) {
5286 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5287 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005288 }
5289 }
5290 AudioSystem::unregisterEffect(effect->id());
5291 }
5292 }
5293 }
5294 return;
5295}
5296
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005298AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299{
5300 PlaybackThread *thread = NULL;
5301 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5302 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5303 }
5304 return thread;
5305}
5306
5307// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005308AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309{
5310 PlaybackThread *thread = checkPlaybackThread_l(output);
5311 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005312 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313 thread = NULL;
5314 }
5315 }
5316 return (MixerThread *)thread;
5317}
5318
5319// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005320AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321{
5322 RecordThread *thread = NULL;
5323 if (mRecordThreads.indexOfKey(input) >= 0) {
5324 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5325 }
5326 return thread;
5327}
5328
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005329uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005331 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005332}
5333
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005334AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5335{
5336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5337 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005338 AudioStreamOut *output = thread->getOutput();
5339 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005340 return thread;
5341 }
5342 }
5343 return NULL;
5344}
5345
5346uint32_t AudioFlinger::primaryOutputDevice_l()
5347{
5348 PlaybackThread *thread = primaryPlaybackThread_l();
5349
5350 if (thread == NULL) {
5351 return 0;
5352 }
5353
5354 return thread->device();
5355}
5356
5357
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358// ----------------------------------------------------------------------------
5359// Effect management
5360// ----------------------------------------------------------------------------
5361
5362
Glenn Kastenf587ba52012-01-26 16:25:10 -08005363status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364{
5365 Mutex::Autolock _l(mLock);
5366 return EffectQueryNumberEffects(numEffects);
5367}
5368
Glenn Kastenf587ba52012-01-26 16:25:10 -08005369status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370{
5371 Mutex::Autolock _l(mLock);
5372 return EffectQueryEffect(index, descriptor);
5373}
5374
Glenn Kasten5e92a782012-01-30 07:40:52 -08005375status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005376 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377{
5378 Mutex::Autolock _l(mLock);
5379 return EffectGetDescriptor(pUuid, descriptor);
5380}
5381
5382
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5384 effect_descriptor_t *pDesc,
5385 const sp<IEffectClient>& effectClient,
5386 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005387 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005388 int sessionId,
5389 status_t *status,
5390 int *id,
5391 int *enabled)
5392{
5393 status_t lStatus = NO_ERROR;
5394 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005395 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005397 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005398 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399
5400 if (pDesc == NULL) {
5401 lStatus = BAD_VALUE;
5402 goto Exit;
5403 }
5404
Eric Laurent84e9a102010-09-23 16:10:16 -07005405 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005406 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005407 lStatus = PERMISSION_DENIED;
5408 goto Exit;
5409 }
5410
Dima Zavinfce7a472011-04-19 22:30:36 -07005411 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005412 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005414 lStatus = PERMISSION_DENIED;
5415 goto Exit;
5416 }
5417
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005418 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005419 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005420 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 lStatus = BAD_VALUE;
5423 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005424 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005425 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005426 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005427 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005428 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005429 }
5430 }
5431
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432 {
5433 Mutex::Autolock _l(mLock);
5434
Mathias Agopian65ab4712010-07-14 17:59:35 -07005435
5436 if (!EffectIsNullUuid(&pDesc->uuid)) {
5437 // if uuid is specified, request effect descriptor
5438 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5439 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005440 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 goto Exit;
5442 }
5443 } else {
5444 // if uuid is not specified, look for an available implementation
5445 // of the required type in effect factory
5446 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005447 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 lStatus = BAD_VALUE;
5449 goto Exit;
5450 }
5451 uint32_t numEffects = 0;
5452 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005453 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 bool found = false;
5455
5456 lStatus = EffectQueryNumberEffects(&numEffects);
5457 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005458 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 goto Exit;
5460 }
5461 for (uint32_t i = 0; i < numEffects; i++) {
5462 lStatus = EffectQueryEffect(i, &desc);
5463 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005464 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 continue;
5466 }
5467 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5468 // If matching type found save effect descriptor. If the session is
5469 // 0 and the effect is not auxiliary, continue enumeration in case
5470 // an auxiliary version of this effect type is available
5471 found = true;
5472 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005473 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5475 break;
5476 }
5477 }
5478 }
5479 if (!found) {
5480 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005481 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 goto Exit;
5483 }
5484 // For same effect type, chose auxiliary version over insert version if
5485 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005486 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5488 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5489 }
5490 }
5491
5492 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005493 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005494 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5495 lStatus = INVALID_OPERATION;
5496 goto Exit;
5497 }
5498
Eric Laurent59255e42011-07-27 19:49:51 -07005499 // check recording permission for visualizer
5500 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5501 !recordingAllowed()) {
5502 lStatus = PERMISSION_DENIED;
5503 goto Exit;
5504 }
5505
Mathias Agopian65ab4712010-07-14 17:59:35 -07005506 // return effect descriptor
5507 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5508
5509 // If output is not specified try to find a matching audio session ID in one of the
5510 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005511 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5512 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005513 // Note: io is never 0 when creating an effect on an input
5514 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005515 // look for the thread where the specified audio session is present
5516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5517 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005518 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005519 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005520 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005522 if (io == 0) {
5523 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5524 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5525 io = mRecordThreads.keyAt(i);
5526 break;
5527 }
5528 }
5529 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005530 // If no output thread contains the requested session ID, default to
5531 // first output. The effect chain will be moved to the correct output
5532 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005533 if (io == 0 && mPlaybackThreads.size()) {
5534 io = mPlaybackThreads.keyAt(0);
5535 }
Steve Block3856b092011-10-20 11:56:00 +01005536 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005537 }
5538 ThreadBase *thread = checkRecordThread_l(io);
5539 if (thread == NULL) {
5540 thread = checkPlaybackThread_l(io);
5541 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005542 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005543 lStatus = BAD_VALUE;
5544 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005547
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005548 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005549
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005550 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005551 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5552 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005553 if (handle != 0 && id != NULL) {
5554 *id = handle->id();
5555 }
5556 }
5557
5558Exit:
5559 if(status) {
5560 *status = lStatus;
5561 }
5562 return handle;
5563}
5564
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005565status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5566 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005567{
Steve Block3856b092011-10-20 11:56:00 +01005568 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005569 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005570 Mutex::Autolock _l(mLock);
5571 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005572 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005573 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574 }
Eric Laurentde070132010-07-13 04:45:46 -07005575 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5576 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005577 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005578 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 }
Eric Laurentde070132010-07-13 04:45:46 -07005580 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5581 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005582 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005583 return BAD_VALUE;
5584 }
5585
5586 Mutex::Autolock _dl(dstThread->mLock);
5587 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005588 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005589
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 return NO_ERROR;
5591}
5592
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005593// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005594status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005595 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005596 AudioFlinger::PlaybackThread *dstThread,
5597 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005598{
Steve Block3856b092011-10-20 11:56:00 +01005599 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005600 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005601
Eric Laurent59255e42011-07-27 19:49:51 -07005602 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005603 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005604 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005605 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005606 return INVALID_OPERATION;
5607 }
5608
Eric Laurent39e94f82010-07-28 01:32:47 -07005609 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005610 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005611 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005612 // removed.
5613 srcThread->removeEffectChain_l(chain);
5614
5615 // transfer all effects one by one so that new effect chain is created on new thread with
5616 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005617 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005618 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005619 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005620 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5621 while (effect != 0) {
5622 srcThread->removeEffect_l(effect);
5623 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005624 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5625 if (effect->state() == EffectModule::ACTIVE ||
5626 effect->state() == EffectModule::STOPPING) {
5627 effect->start();
5628 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005629 // if the move request is not received from audio policy manager, the effect must be
5630 // re-registered with the new strategy and output
5631 if (dstChain == 0) {
5632 dstChain = effect->chain().promote();
5633 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005634 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005635 srcThread->addEffect_l(effect);
5636 return NO_INIT;
5637 }
5638 strategy = dstChain->strategy();
5639 }
5640 if (reRegister) {
5641 AudioSystem::unregisterEffect(effect->id());
5642 AudioSystem::registerEffect(&effect->desc(),
5643 dstOutput,
5644 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005645 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005646 effect->id());
5647 }
Eric Laurentde070132010-07-13 04:45:46 -07005648 effect = chain->getEffectFromId_l(0);
5649 }
5650
5651 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652}
5653
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005654
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005656sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 const sp<AudioFlinger::Client>& client,
5658 const sp<IEffectClient>& effectClient,
5659 int32_t priority,
5660 int sessionId,
5661 effect_descriptor_t *desc,
5662 int *enabled,
5663 status_t *status
5664 )
5665{
5666 sp<EffectModule> effect;
5667 sp<EffectHandle> handle;
5668 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005670 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671 bool effectCreated = false;
5672 bool effectRegistered = false;
5673
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005674 lStatus = initCheck();
5675 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005676 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 goto Exit;
5678 }
5679
5680 // Do not allow effects with session ID 0 on direct output or duplicating threads
5681 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005682 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005683 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005684 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 lStatus = BAD_VALUE;
5686 goto Exit;
5687 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005688 // Only Pre processor effects are allowed on input threads and only on input threads
5689 if ((mType == RECORD &&
5690 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5691 (mType != RECORD &&
5692 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005693 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005694 desc->name, desc->flags, mType);
5695 lStatus = BAD_VALUE;
5696 goto Exit;
5697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698
Steve Block3856b092011-10-20 11:56:00 +01005699 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700
5701 { // scope for mLock
5702 Mutex::Autolock _l(mLock);
5703
5704 // check for existing effect chain with the requested audio session
5705 chain = getEffectChain_l(sessionId);
5706 if (chain == 0) {
5707 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005708 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 chain = new EffectChain(this, sessionId);
5710 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005711 chain->setStrategy(getStrategyForSession_l(sessionId));
5712 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005714 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 }
5716
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005717 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718
5719 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005720 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005722 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 if (lStatus != NO_ERROR) {
5724 goto Exit;
5725 }
5726 effectRegistered = true;
5727 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005728 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 lStatus = effect->status();
5730 if (lStatus != NO_ERROR) {
5731 goto Exit;
5732 }
Eric Laurentcab11242010-07-15 12:50:15 -07005733 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 if (lStatus != NO_ERROR) {
5735 goto Exit;
5736 }
5737 effectCreated = true;
5738
5739 effect->setDevice(mDevice);
5740 effect->setMode(mAudioFlinger->getMode());
5741 }
5742 // create effect handle and connect it to effect module
5743 handle = new EffectHandle(effect, client, effectClient, priority);
5744 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005745 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 *enabled = (int)effect->isEnabled();
5747 }
5748 }
5749
5750Exit:
5751 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005752 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005754 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 }
5756 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005757 AudioSystem::unregisterEffect(effect->id());
5758 }
5759 if (chainCreated) {
5760 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 }
5762 handle.clear();
5763 }
5764
5765 if(status) {
5766 *status = lStatus;
5767 }
5768 return handle;
5769}
5770
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005771sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5772{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005773 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005774 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005775}
5776
Eric Laurentde070132010-07-13 04:45:46 -07005777// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5778// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005779status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005780{
5781 // check for existing effect chain with the requested audio session
5782 int sessionId = effect->sessionId();
5783 sp<EffectChain> chain = getEffectChain_l(sessionId);
5784 bool chainCreated = false;
5785
5786 if (chain == 0) {
5787 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005788 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005789 chain = new EffectChain(this, sessionId);
5790 addEffectChain_l(chain);
5791 chain->setStrategy(getStrategyForSession_l(sessionId));
5792 chainCreated = true;
5793 }
Steve Block3856b092011-10-20 11:56:00 +01005794 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005795
5796 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005797 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005798 this, effect->desc().name, chain.get());
5799 return BAD_VALUE;
5800 }
5801
5802 status_t status = chain->addEffect_l(effect);
5803 if (status != NO_ERROR) {
5804 if (chainCreated) {
5805 removeEffectChain_l(chain);
5806 }
5807 return status;
5808 }
5809
5810 effect->setDevice(mDevice);
5811 effect->setMode(mAudioFlinger->getMode());
5812 return NO_ERROR;
5813}
5814
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005815void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005816
Steve Block3856b092011-10-20 11:56:00 +01005817 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005819 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5820 detachAuxEffect_l(effect->id());
5821 }
5822
5823 sp<EffectChain> chain = effect->chain().promote();
5824 if (chain != 0) {
5825 // remove effect chain if removing last effect
5826 if (chain->removeEffect_l(effect) == 0) {
5827 removeEffectChain_l(chain);
5828 }
5829 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005830 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005831 }
5832}
5833
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005834void AudioFlinger::ThreadBase::lockEffectChains_l(
5835 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5836{
5837 effectChains = mEffectChains;
5838 for (size_t i = 0; i < mEffectChains.size(); i++) {
5839 mEffectChains[i]->lock();
5840 }
5841}
5842
5843void AudioFlinger::ThreadBase::unlockEffectChains(
5844 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5845{
5846 for (size_t i = 0; i < effectChains.size(); i++) {
5847 effectChains[i]->unlock();
5848 }
5849}
5850
5851sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5852{
5853 Mutex::Autolock _l(mLock);
5854 return getEffectChain_l(sessionId);
5855}
5856
5857sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5858{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005859 size_t size = mEffectChains.size();
5860 for (size_t i = 0; i < size; i++) {
5861 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005862 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005863 }
5864 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005865 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005866}
5867
Glenn Kastenf78aee72012-01-04 11:00:47 -08005868void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005869{
5870 Mutex::Autolock _l(mLock);
5871 size_t size = mEffectChains.size();
5872 for (size_t i = 0; i < size; i++) {
5873 mEffectChains[i]->setMode_l(mode);
5874 }
5875}
5876
5877void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005878 const wp<EffectHandle>& handle,
5879 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005880
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005882 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883 // delete the effect module if removing last handle on it
5884 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005885 if (!effect->isPinned() || unpiniflast) {
5886 removeEffect_l(effect);
5887 AudioSystem::unregisterEffect(effect->id());
5888 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 }
5890}
5891
5892status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5893{
5894 int session = chain->sessionId();
5895 int16_t *buffer = mMixBuffer;
5896 bool ownsBuffer = false;
5897
Steve Block3856b092011-10-20 11:56:00 +01005898 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 if (session > 0) {
5900 // Only one effect chain can be present in direct output thread and it uses
5901 // the mix buffer as input
5902 if (mType != DIRECT) {
5903 size_t numSamples = mFrameCount * mChannelCount;
5904 buffer = new int16_t[numSamples];
5905 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 ownsBuffer = true;
5908 }
5909
5910 // Attach all tracks with same session ID to this chain.
5911 for (size_t i = 0; i < mTracks.size(); ++i) {
5912 sp<Track> track = mTracks[i];
5913 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005916 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 }
5918 }
5919
5920 // indicate all active tracks in the chain
5921 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5922 sp<Track> track = mActiveTracks[i].promote();
5923 if (track == 0) continue;
5924 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005926 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 }
5928 }
5929 }
5930
5931 chain->setInBuffer(buffer, ownsBuffer);
5932 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005933 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005934 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005935 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5936 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005938 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5939 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005940 // Effect chain for other sessions are inserted at beginning of effect
5941 // chains list to be processed before output mix effects. Relative order between other
5942 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 size_t size = mEffectChains.size();
5944 size_t i = 0;
5945 for (i = 0; i < size; i++) {
5946 if (mEffectChains[i]->sessionId() < session) break;
5947 }
5948 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005949 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950
5951 return NO_ERROR;
5952}
5953
5954size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5955{
5956 int session = chain->sessionId();
5957
Steve Block3856b092011-10-20 11:56:00 +01005958 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959
5960 for (size_t i = 0; i < mEffectChains.size(); i++) {
5961 if (chain == mEffectChains[i]) {
5962 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005963 // detach all active tracks from the chain
5964 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5965 sp<Track> track = mActiveTracks[i].promote();
5966 if (track == 0) continue;
5967 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005968 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005969 chain.get(), session);
5970 chain->decActiveTrackCnt();
5971 }
5972 }
5973
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 // detach all tracks with same session ID from this chain
5975 for (size_t i = 0; i < mTracks.size(); ++i) {
5976 sp<Track> track = mTracks[i];
5977 if (session == track->sessionId()) {
5978 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005979 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 }
5981 }
Eric Laurentde070132010-07-13 04:45:46 -07005982 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 }
5984 }
5985 return mEffectChains.size();
5986}
5987
Eric Laurentde070132010-07-13 04:45:46 -07005988status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5989 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990{
5991 Mutex::Autolock _l(mLock);
5992 return attachAuxEffect_l(track, EffectId);
5993}
5994
Eric Laurentde070132010-07-13 04:45:46 -07005995status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5996 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997{
5998 status_t status = NO_ERROR;
5999
6000 if (EffectId == 0) {
6001 track->setAuxBuffer(0, NULL);
6002 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006003 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6004 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 if (effect != 0) {
6006 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6007 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6008 } else {
6009 status = INVALID_OPERATION;
6010 }
6011 } else {
6012 status = BAD_VALUE;
6013 }
6014 }
6015 return status;
6016}
6017
6018void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6019{
6020 for (size_t i = 0; i < mTracks.size(); ++i) {
6021 sp<Track> track = mTracks[i];
6022 if (track->auxEffectId() == effectId) {
6023 attachAuxEffect_l(track, 0);
6024 }
6025 }
6026}
6027
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006028status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6029{
6030 // only one chain per input thread
6031 if (mEffectChains.size() != 0) {
6032 return INVALID_OPERATION;
6033 }
Steve Block3856b092011-10-20 11:56:00 +01006034 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006035
6036 chain->setInBuffer(NULL);
6037 chain->setOutBuffer(NULL);
6038
Eric Laurent59255e42011-07-27 19:49:51 -07006039 checkSuspendOnAddEffectChain_l(chain);
6040
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041 mEffectChains.add(chain);
6042
6043 return NO_ERROR;
6044}
6045
6046size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6047{
Steve Block3856b092011-10-20 11:56:00 +01006048 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006049 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006050 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6051 chain.get(), mEffectChains.size(), this);
6052 if (mEffectChains.size() == 1) {
6053 mEffectChains.removeAt(0);
6054 }
6055 return 0;
6056}
6057
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058// ----------------------------------------------------------------------------
6059// EffectModule implementation
6060// ----------------------------------------------------------------------------
6061
6062#undef LOG_TAG
6063#define LOG_TAG "AudioFlinger::EffectModule"
6064
6065AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6066 const wp<AudioFlinger::EffectChain>& chain,
6067 effect_descriptor_t *desc,
6068 int id,
6069 int sessionId)
6070 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006071 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072{
Steve Block3856b092011-10-20 11:56:00 +01006073 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 int lStatus;
6075 sp<ThreadBase> thread = mThread.promote();
6076 if (thread == 0) {
6077 return;
6078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079
6080 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6081
6082 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006083 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084
6085 if (mStatus != NO_ERROR) {
6086 return;
6087 }
6088 lStatus = init();
6089 if (lStatus < 0) {
6090 mStatus = lStatus;
6091 goto Error;
6092 }
6093
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006094 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6095 mPinned = true;
6096 }
Steve Block3856b092011-10-20 11:56:00 +01006097 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 return;
6099Error:
6100 EffectRelease(mEffectInterface);
6101 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006102 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103}
6104
6105AudioFlinger::EffectModule::~EffectModule()
6106{
Steve Block3856b092011-10-20 11:56:00 +01006107 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006109 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6110 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6111 sp<ThreadBase> thread = mThread.promote();
6112 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006113 audio_stream_t *stream = thread->stream();
6114 if (stream != NULL) {
6115 stream->remove_audio_effect(stream, mEffectInterface);
6116 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 }
6118 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 // release effect engine
6120 EffectRelease(mEffectInterface);
6121 }
6122}
6123
Glenn Kasten435dbe62012-01-30 10:15:48 -08006124status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125{
6126 status_t status;
6127
6128 Mutex::Autolock _l(mLock);
6129 // First handle in mHandles has highest priority and controls the effect module
6130 int priority = handle->priority();
6131 size_t size = mHandles.size();
6132 sp<EffectHandle> h;
6133 size_t i;
6134 for (i = 0; i < size; i++) {
6135 h = mHandles[i].promote();
6136 if (h == 0) continue;
6137 if (h->priority() <= priority) break;
6138 }
6139 // if inserted in first place, move effect control from previous owner to this handle
6140 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006141 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006143 enabled = h->enabled();
6144 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 }
Eric Laurent59255e42011-07-27 19:49:51 -07006146 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147 status = NO_ERROR;
6148 } else {
6149 status = ALREADY_EXISTS;
6150 }
Steve Block3856b092011-10-20 11:56:00 +01006151 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152 mHandles.insertAt(handle, i);
6153 return status;
6154}
6155
6156size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6157{
6158 Mutex::Autolock _l(mLock);
6159 size_t size = mHandles.size();
6160 size_t i;
6161 for (i = 0; i < size; i++) {
6162 if (mHandles[i] == handle) break;
6163 }
6164 if (i == size) {
6165 return size;
6166 }
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006168
6169 bool enabled = false;
6170 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006171 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006172 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006173 enabled = hdl->enabled();
6174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175 mHandles.removeAt(i);
6176 size = mHandles.size();
6177 // if removed from first place, move effect control from this handle to next in line
6178 if (i == 0 && size != 0) {
6179 sp<EffectHandle> h = mHandles[0].promote();
6180 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006181 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 }
6183 }
6184
Eric Laurentec437d82011-07-26 20:54:46 -07006185 // Prevent calls to process() and other functions on effect interface from now on.
6186 // The effect engine will be released by the destructor when the last strong reference on
6187 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006188 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006189 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006190 }
6191
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 return size;
6193}
6194
Eric Laurent59255e42011-07-27 19:49:51 -07006195sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6196{
6197 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006198 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006199}
6200
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006201void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202{
Steve Block3856b092011-10-20 11:56:00 +01006203 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006204 // keep a strong reference on this EffectModule to avoid calling the
6205 // destructor before we exit
6206 sp<EffectModule> keep(this);
6207 {
6208 sp<ThreadBase> thread = mThread.promote();
6209 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006210 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211 }
6212 }
6213}
6214
6215void AudioFlinger::EffectModule::updateState() {
6216 Mutex::Autolock _l(mLock);
6217
6218 switch (mState) {
6219 case RESTART:
6220 reset_l();
6221 // FALL THROUGH
6222
6223 case STARTING:
6224 // clear auxiliary effect input buffer for next accumulation
6225 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6226 memset(mConfig.inputCfg.buffer.raw,
6227 0,
6228 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6229 }
6230 start_l();
6231 mState = ACTIVE;
6232 break;
6233 case STOPPING:
6234 stop_l();
6235 mDisableWaitCnt = mMaxDisableWaitCnt;
6236 mState = STOPPED;
6237 break;
6238 case STOPPED:
6239 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6240 // turn off sequence.
6241 if (--mDisableWaitCnt == 0) {
6242 reset_l();
6243 mState = IDLE;
6244 }
6245 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006246 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247 break;
6248 }
6249}
6250
6251void AudioFlinger::EffectModule::process()
6252{
6253 Mutex::Autolock _l(mLock);
6254
Eric Laurentec437d82011-07-26 20:54:46 -07006255 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 mConfig.inputCfg.buffer.raw == NULL ||
6257 mConfig.outputCfg.buffer.raw == NULL) {
6258 return;
6259 }
6260
Eric Laurent8f45bd72010-08-31 13:50:07 -07006261 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6263 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006264 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006266 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 }
6268
6269 // do the actual processing in the effect engine
6270 int ret = (*mEffectInterface)->process(mEffectInterface,
6271 &mConfig.inputCfg.buffer,
6272 &mConfig.outputCfg.buffer);
6273
6274 // force transition to IDLE state when engine is ready
6275 if (mState == STOPPED && ret == -ENODATA) {
6276 mDisableWaitCnt = 1;
6277 }
6278
6279 // clear auxiliary effect input buffer for next accumulation
6280 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006281 memset(mConfig.inputCfg.buffer.raw, 0,
6282 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 }
6284 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006285 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6286 // If an insert effect is idle and input buffer is different from output buffer,
6287 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006289 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006290 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6291 int16_t *in = mConfig.inputCfg.buffer.s16;
6292 int16_t *out = mConfig.outputCfg.buffer.s16;
6293 for (size_t i = 0; i < frameCnt; i++) {
6294 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 }
6297 }
6298}
6299
6300void AudioFlinger::EffectModule::reset_l()
6301{
6302 if (mEffectInterface == NULL) {
6303 return;
6304 }
6305 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6306}
6307
6308status_t AudioFlinger::EffectModule::configure()
6309{
6310 uint32_t channels;
6311 if (mEffectInterface == NULL) {
6312 return NO_INIT;
6313 }
6314
6315 sp<ThreadBase> thread = mThread.promote();
6316 if (thread == 0) {
6317 return DEAD_OBJECT;
6318 }
6319
6320 // TODO: handle configuration of effects replacing track process
6321 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006322 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006324 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006325 }
6326
6327 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006328 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 } else {
6330 mConfig.inputCfg.channels = channels;
6331 }
6332 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006333 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6334 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 mConfig.inputCfg.samplingRate = thread->sampleRate();
6336 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6337 mConfig.inputCfg.bufferProvider.cookie = NULL;
6338 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6339 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6340 mConfig.outputCfg.bufferProvider.cookie = NULL;
6341 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6342 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6343 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6344 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006345 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006346 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 // - in other sessions:
6348 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6349 // other effect: overwrites output buffer: input buffer == output buffer
6350 // Auxiliary effect:
6351 // accumulates in output buffer: input buffer != output buffer
6352 // Therefore: accumulate <=> input buffer != output buffer
6353 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6354 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6355 } else {
6356 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6357 }
6358 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6359 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6360 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6361 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6362
Steve Block3856b092011-10-20 11:56:00 +01006363 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006364 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6365
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006367 uint32_t size = sizeof(int);
6368 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006369 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006370 sizeof(effect_config_t),
6371 &mConfig,
6372 &size,
6373 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 if (status == 0) {
6375 status = cmdStatus;
6376 }
6377
6378 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6379 (1000 * mConfig.outputCfg.buffer.frameCount);
6380
6381 return status;
6382}
6383
6384status_t AudioFlinger::EffectModule::init()
6385{
6386 Mutex::Autolock _l(mLock);
6387 if (mEffectInterface == NULL) {
6388 return NO_INIT;
6389 }
6390 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006391 uint32_t size = sizeof(status_t);
6392 status_t status = (*mEffectInterface)->command(mEffectInterface,
6393 EFFECT_CMD_INIT,
6394 0,
6395 NULL,
6396 &size,
6397 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 if (status == 0) {
6399 status = cmdStatus;
6400 }
6401 return status;
6402}
6403
Eric Laurentec35a142011-10-05 17:42:25 -07006404status_t AudioFlinger::EffectModule::start()
6405{
6406 Mutex::Autolock _l(mLock);
6407 return start_l();
6408}
6409
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410status_t AudioFlinger::EffectModule::start_l()
6411{
6412 if (mEffectInterface == NULL) {
6413 return NO_INIT;
6414 }
6415 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006416 uint32_t size = sizeof(status_t);
6417 status_t status = (*mEffectInterface)->command(mEffectInterface,
6418 EFFECT_CMD_ENABLE,
6419 0,
6420 NULL,
6421 &size,
6422 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423 if (status == 0) {
6424 status = cmdStatus;
6425 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006426 if (status == 0 &&
6427 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6428 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6429 sp<ThreadBase> thread = mThread.promote();
6430 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006431 audio_stream_t *stream = thread->stream();
6432 if (stream != NULL) {
6433 stream->add_audio_effect(stream, mEffectInterface);
6434 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006435 }
6436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 return status;
6438}
6439
Eric Laurentec437d82011-07-26 20:54:46 -07006440status_t AudioFlinger::EffectModule::stop()
6441{
6442 Mutex::Autolock _l(mLock);
6443 return stop_l();
6444}
6445
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446status_t AudioFlinger::EffectModule::stop_l()
6447{
6448 if (mEffectInterface == NULL) {
6449 return NO_INIT;
6450 }
6451 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006452 uint32_t size = sizeof(status_t);
6453 status_t status = (*mEffectInterface)->command(mEffectInterface,
6454 EFFECT_CMD_DISABLE,
6455 0,
6456 NULL,
6457 &size,
6458 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459 if (status == 0) {
6460 status = cmdStatus;
6461 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006462 if (status == 0 &&
6463 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6464 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6465 sp<ThreadBase> thread = mThread.promote();
6466 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006467 audio_stream_t *stream = thread->stream();
6468 if (stream != NULL) {
6469 stream->remove_audio_effect(stream, mEffectInterface);
6470 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006471 }
6472 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006473 return status;
6474}
6475
Eric Laurent25f43952010-07-28 05:40:18 -07006476status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6477 uint32_t cmdSize,
6478 void *pCmdData,
6479 uint32_t *replySize,
6480 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481{
6482 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006483// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484
Eric Laurentec437d82011-07-26 20:54:46 -07006485 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006486 return NO_INIT;
6487 }
Eric Laurent25f43952010-07-28 05:40:18 -07006488 status_t status = (*mEffectInterface)->command(mEffectInterface,
6489 cmdCode,
6490 cmdSize,
6491 pCmdData,
6492 replySize,
6493 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006494 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006495 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496 for (size_t i = 1; i < mHandles.size(); i++) {
6497 sp<EffectHandle> h = mHandles[i].promote();
6498 if (h != 0) {
6499 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6500 }
6501 }
6502 }
6503 return status;
6504}
6505
6506status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6507{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006508
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006510 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511
6512 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006513 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6514 if (enabled && status != NO_ERROR) {
6515 return status;
6516 }
6517
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 switch (mState) {
6519 // going from disabled to enabled
6520 case IDLE:
6521 mState = STARTING;
6522 break;
6523 case STOPPED:
6524 mState = RESTART;
6525 break;
6526 case STOPPING:
6527 mState = ACTIVE;
6528 break;
6529
6530 // going from enabled to disabled
6531 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006532 mState = STOPPED;
6533 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534 case STARTING:
6535 mState = IDLE;
6536 break;
6537 case ACTIVE:
6538 mState = STOPPING;
6539 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006540 case DESTROYED:
6541 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006542 }
6543 for (size_t i = 1; i < mHandles.size(); i++) {
6544 sp<EffectHandle> h = mHandles[i].promote();
6545 if (h != 0) {
6546 h->setEnabled(enabled);
6547 }
6548 }
6549 }
6550 return NO_ERROR;
6551}
6552
Glenn Kastenc59c0042012-02-02 14:06:11 -08006553bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554{
6555 switch (mState) {
6556 case RESTART:
6557 case STARTING:
6558 case ACTIVE:
6559 return true;
6560 case IDLE:
6561 case STOPPING:
6562 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006563 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006564 default:
6565 return false;
6566 }
6567}
6568
Glenn Kastenc59c0042012-02-02 14:06:11 -08006569bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006570{
6571 switch (mState) {
6572 case RESTART:
6573 case ACTIVE:
6574 case STOPPING:
6575 case STOPPED:
6576 return true;
6577 case IDLE:
6578 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006579 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006580 default:
6581 return false;
6582 }
6583}
6584
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6586{
6587 Mutex::Autolock _l(mLock);
6588 status_t status = NO_ERROR;
6589
6590 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6591 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006592 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006593 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6594 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595 status_t cmdStatus;
6596 uint32_t volume[2];
6597 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006598 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 volume[0] = *left;
6600 volume[1] = *right;
6601 if (controller) {
6602 pVolume = volume;
6603 }
Eric Laurent25f43952010-07-28 05:40:18 -07006604 status = (*mEffectInterface)->command(mEffectInterface,
6605 EFFECT_CMD_SET_VOLUME,
6606 size,
6607 volume,
6608 &size,
6609 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6611 *left = volume[0];
6612 *right = volume[1];
6613 }
6614 }
6615 return status;
6616}
6617
6618status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6619{
6620 Mutex::Autolock _l(mLock);
6621 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006622 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6623 // audio pre processing modules on RecordThread can receive both output and
6624 // input device indication in the same call
6625 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6626 if (dev) {
6627 status_t cmdStatus;
6628 uint32_t size = sizeof(status_t);
6629
6630 status = (*mEffectInterface)->command(mEffectInterface,
6631 EFFECT_CMD_SET_DEVICE,
6632 sizeof(uint32_t),
6633 &dev,
6634 &size,
6635 &cmdStatus);
6636 if (status == NO_ERROR) {
6637 status = cmdStatus;
6638 }
6639 }
6640 dev = device & AUDIO_DEVICE_IN_ALL;
6641 if (dev) {
6642 status_t cmdStatus;
6643 uint32_t size = sizeof(status_t);
6644
6645 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6646 EFFECT_CMD_SET_INPUT_DEVICE,
6647 sizeof(uint32_t),
6648 &dev,
6649 &size,
6650 &cmdStatus);
6651 if (status2 == NO_ERROR) {
6652 status2 = cmdStatus;
6653 }
6654 if (status == NO_ERROR) {
6655 status = status2;
6656 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006657 }
6658 }
6659 return status;
6660}
6661
Glenn Kastenf78aee72012-01-04 11:00:47 -08006662status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663{
6664 Mutex::Autolock _l(mLock);
6665 status_t status = NO_ERROR;
6666 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006668 uint32_t size = sizeof(status_t);
6669 status = (*mEffectInterface)->command(mEffectInterface,
6670 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006671 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006672 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006673 &size,
6674 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006675 if (status == NO_ERROR) {
6676 status = cmdStatus;
6677 }
6678 }
6679 return status;
6680}
6681
Eric Laurent59255e42011-07-27 19:49:51 -07006682void AudioFlinger::EffectModule::setSuspended(bool suspended)
6683{
6684 Mutex::Autolock _l(mLock);
6685 mSuspended = suspended;
6686}
Glenn Kastena3a85482012-01-04 11:01:11 -08006687
6688bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006689{
6690 Mutex::Autolock _l(mLock);
6691 return mSuspended;
6692}
6693
Mathias Agopian65ab4712010-07-14 17:59:35 -07006694status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6695{
6696 const size_t SIZE = 256;
6697 char buffer[SIZE];
6698 String8 result;
6699
6700 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6701 result.append(buffer);
6702
6703 bool locked = tryLock(mLock);
6704 // failed to lock - AudioFlinger is probably deadlocked
6705 if (!locked) {
6706 result.append("\t\tCould not lock Fx mutex:\n");
6707 }
6708
6709 result.append("\t\tSession Status State Engine:\n");
6710 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6711 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6712 result.append(buffer);
6713
6714 result.append("\t\tDescriptor:\n");
6715 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6716 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6717 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6718 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6719 result.append(buffer);
6720 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6721 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6722 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6723 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6724 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006725 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006726 mDescriptor.apiVersion,
6727 mDescriptor.flags);
6728 result.append(buffer);
6729 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6730 mDescriptor.name);
6731 result.append(buffer);
6732 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6733 mDescriptor.implementor);
6734 result.append(buffer);
6735
6736 result.append("\t\t- Input configuration:\n");
6737 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6738 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6739 (uint32_t)mConfig.inputCfg.buffer.raw,
6740 mConfig.inputCfg.buffer.frameCount,
6741 mConfig.inputCfg.samplingRate,
6742 mConfig.inputCfg.channels,
6743 mConfig.inputCfg.format);
6744 result.append(buffer);
6745
6746 result.append("\t\t- Output configuration:\n");
6747 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6748 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6749 (uint32_t)mConfig.outputCfg.buffer.raw,
6750 mConfig.outputCfg.buffer.frameCount,
6751 mConfig.outputCfg.samplingRate,
6752 mConfig.outputCfg.channels,
6753 mConfig.outputCfg.format);
6754 result.append(buffer);
6755
6756 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6757 result.append(buffer);
6758 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6759 for (size_t i = 0; i < mHandles.size(); ++i) {
6760 sp<EffectHandle> handle = mHandles[i].promote();
6761 if (handle != 0) {
6762 handle->dump(buffer, SIZE);
6763 result.append(buffer);
6764 }
6765 }
6766
6767 result.append("\n");
6768
6769 write(fd, result.string(), result.length());
6770
6771 if (locked) {
6772 mLock.unlock();
6773 }
6774
6775 return NO_ERROR;
6776}
6777
6778// ----------------------------------------------------------------------------
6779// EffectHandle implementation
6780// ----------------------------------------------------------------------------
6781
6782#undef LOG_TAG
6783#define LOG_TAG "AudioFlinger::EffectHandle"
6784
6785AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6786 const sp<AudioFlinger::Client>& client,
6787 const sp<IEffectClient>& effectClient,
6788 int32_t priority)
6789 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006790 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006791 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792{
Steve Block3856b092011-10-20 11:56:00 +01006793 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006794
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006795 if (client == 0) {
6796 return;
6797 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6799 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6800 if (mCblkMemory != 0) {
6801 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6802
Glenn Kastena0d68332012-01-27 16:47:15 -08006803 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 new(mCblk) effect_param_cblk_t();
6805 mBuffer = (uint8_t *)mCblk + bufOffset;
6806 }
6807 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006808 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 return;
6810 }
6811}
6812
6813AudioFlinger::EffectHandle::~EffectHandle()
6814{
Steve Block3856b092011-10-20 11:56:00 +01006815 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006816 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006817 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818}
6819
6820status_t AudioFlinger::EffectHandle::enable()
6821{
Steve Block3856b092011-10-20 11:56:00 +01006822 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823 if (!mHasControl) return INVALID_OPERATION;
6824 if (mEffect == 0) return DEAD_OBJECT;
6825
Eric Laurentdb7c0792011-08-10 10:37:50 -07006826 if (mEnabled) {
6827 return NO_ERROR;
6828 }
6829
Eric Laurent59255e42011-07-27 19:49:51 -07006830 mEnabled = true;
6831
6832 sp<ThreadBase> thread = mEffect->thread().promote();
6833 if (thread != 0) {
6834 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6835 }
6836
6837 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6838 if (mEffect->suspended()) {
6839 return NO_ERROR;
6840 }
6841
Eric Laurentdb7c0792011-08-10 10:37:50 -07006842 status_t status = mEffect->setEnabled(true);
6843 if (status != NO_ERROR) {
6844 if (thread != 0) {
6845 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6846 }
6847 mEnabled = false;
6848 }
6849 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850}
6851
6852status_t AudioFlinger::EffectHandle::disable()
6853{
Steve Block3856b092011-10-20 11:56:00 +01006854 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006856 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857
Eric Laurentdb7c0792011-08-10 10:37:50 -07006858 if (!mEnabled) {
6859 return NO_ERROR;
6860 }
Eric Laurent59255e42011-07-27 19:49:51 -07006861 mEnabled = false;
6862
6863 if (mEffect->suspended()) {
6864 return NO_ERROR;
6865 }
6866
6867 status_t status = mEffect->setEnabled(false);
6868
6869 sp<ThreadBase> thread = mEffect->thread().promote();
6870 if (thread != 0) {
6871 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6872 }
6873
6874 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006875}
6876
6877void AudioFlinger::EffectHandle::disconnect()
6878{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006879 disconnect(true);
6880}
6881
6882void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6883{
Steve Block3856b092011-10-20 11:56:00 +01006884 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885 if (mEffect == 0) {
6886 return;
6887 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006888 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006889
Eric Laurenta85a74a2011-10-19 11:44:54 -07006890 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006891 sp<ThreadBase> thread = mEffect->thread().promote();
6892 if (thread != 0) {
6893 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6894 }
Eric Laurent59255e42011-07-27 19:49:51 -07006895 }
6896
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 // release sp on module => module destructor can be called now
6898 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006900 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006901 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006902 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6903 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006904 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006905 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6907 mClient.clear();
6908 }
6909}
6910
Eric Laurent25f43952010-07-28 05:40:18 -07006911status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6912 uint32_t cmdSize,
6913 void *pCmdData,
6914 uint32_t *replySize,
6915 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916{
Steve Block3856b092011-10-20 11:56:00 +01006917// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006918// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919
6920 // only get parameter command is permitted for applications not controlling the effect
6921 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6922 return INVALID_OPERATION;
6923 }
6924 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006925 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006926
6927 // handle commands that are not forwarded transparently to effect engine
6928 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6929 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6930 // no risk to block the whole media server process or mixer threads is we are stuck here
6931 Mutex::Autolock _l(mCblk->lock);
6932 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6933 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6934 mCblk->serverIndex = 0;
6935 mCblk->clientIndex = 0;
6936 return BAD_VALUE;
6937 }
6938 status_t status = NO_ERROR;
6939 while (mCblk->serverIndex < mCblk->clientIndex) {
6940 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006941 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 int *p = (int *)(mBuffer + mCblk->serverIndex);
6943 int size = *p++;
6944 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006945 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946 break;
6947 }
6948 effect_param_t *param = (effect_param_t *)p;
6949 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006950 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 mCblk->serverIndex += size;
6952 continue;
6953 }
Eric Laurent25f43952010-07-28 05:40:18 -07006954 uint32_t psize = sizeof(effect_param_t) +
6955 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6956 param->vsize;
6957 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6958 psize,
6959 p,
6960 &rsize,
6961 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006962 // stop at first error encountered
6963 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006964 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006965 *(int *)pReplyData = reply;
6966 break;
6967 } else if (reply != NO_ERROR) {
6968 *(int *)pReplyData = reply;
6969 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006970 }
6971 mCblk->serverIndex += size;
6972 }
6973 mCblk->serverIndex = 0;
6974 mCblk->clientIndex = 0;
6975 return status;
6976 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006977 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 return enable();
6979 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006980 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 return disable();
6982 }
6983
6984 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6985}
6986
Eric Laurent59255e42011-07-27 19:49:51 -07006987void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988{
Steve Block3856b092011-10-20 11:56:00 +01006989 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990
6991 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006992 mEnabled = enabled;
6993
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 if (signal && mEffectClient != 0) {
6995 mEffectClient->controlStatusChanged(hasControl);
6996 }
6997}
6998
Eric Laurent25f43952010-07-28 05:40:18 -07006999void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7000 uint32_t cmdSize,
7001 void *pCmdData,
7002 uint32_t replySize,
7003 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004{
7005 if (mEffectClient != 0) {
7006 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7007 }
7008}
7009
7010
7011
7012void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7013{
7014 if (mEffectClient != 0) {
7015 mEffectClient->enableStatusChanged(enabled);
7016 }
7017}
7018
7019status_t AudioFlinger::EffectHandle::onTransact(
7020 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7021{
7022 return BnEffect::onTransact(code, data, reply, flags);
7023}
7024
7025
7026void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7027{
Glenn Kastena0d68332012-01-27 16:47:15 -08007028 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029
7030 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007031 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 mPriority,
7033 mHasControl,
7034 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007035 mCblk ? mCblk->clientIndex : 0,
7036 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037 );
7038
7039 if (locked) {
7040 mCblk->lock.unlock();
7041 }
7042}
7043
7044#undef LOG_TAG
7045#define LOG_TAG "AudioFlinger::EffectChain"
7046
7047AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7048 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007049 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007050 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7051 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052{
Dima Zavinfce7a472011-04-19 22:30:36 -07007053 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007054 sp<ThreadBase> thread = mThread.promote();
7055 if (thread == 0) {
7056 return;
7057 }
7058 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7059 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007060}
7061
7062AudioFlinger::EffectChain::~EffectChain()
7063{
7064 if (mOwnInBuffer) {
7065 delete mInBuffer;
7066 }
7067
7068}
7069
Eric Laurent59255e42011-07-27 19:49:51 -07007070// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007071sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007072{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 size_t size = mEffects.size();
7074
7075 for (size_t i = 0; i < size; i++) {
7076 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007077 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 }
7079 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007080 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081}
7082
Eric Laurent59255e42011-07-27 19:49:51 -07007083// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007084sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007086 size_t size = mEffects.size();
7087
7088 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007089 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7090 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007091 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092 }
7093 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007094 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095}
7096
Eric Laurent59255e42011-07-27 19:49:51 -07007097// getEffectFromType_l() must be called with ThreadBase::mLock held
7098sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7099 const effect_uuid_t *type)
7100{
Eric Laurent59255e42011-07-27 19:49:51 -07007101 size_t size = mEffects.size();
7102
7103 for (size_t i = 0; i < size; i++) {
7104 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007105 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007106 }
7107 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007108 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007109}
7110
Mathias Agopian65ab4712010-07-14 17:59:35 -07007111// Must be called with EffectChain::mLock locked
7112void AudioFlinger::EffectChain::process_l()
7113{
Eric Laurentdac69112010-09-28 14:09:57 -07007114 sp<ThreadBase> thread = mThread.promote();
7115 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007116 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007117 return;
7118 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007119 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7120 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007121 // always process effects unless no more tracks are on the session and the effect tail
7122 // has been rendered
7123 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007124 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007125 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007126
Eric Laurent544fe9b2011-11-11 15:42:52 -08007127 if (!tracksOnSession && mTailBufferCount == 0) {
7128 doProcess = false;
7129 }
7130
7131 if (activeTrackCnt() == 0) {
7132 // if no track is active and the effect tail has not been rendered,
7133 // the input buffer must be cleared here as the mixer process will not do it
7134 if (tracksOnSession || mTailBufferCount > 0) {
7135 size_t numSamples = thread->frameCount() * thread->channelCount();
7136 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7137 if (mTailBufferCount > 0) {
7138 mTailBufferCount--;
7139 }
7140 }
7141 }
Eric Laurentdac69112010-09-28 14:09:57 -07007142 }
7143
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007145 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007146 for (size_t i = 0; i < size; i++) {
7147 mEffects[i]->process();
7148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149 }
7150 for (size_t i = 0; i < size; i++) {
7151 mEffects[i]->updateState();
7152 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153}
7154
Eric Laurentcab11242010-07-15 12:50:15 -07007155// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007156status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007157{
7158 effect_descriptor_t desc = effect->desc();
7159 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7160
7161 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007162 effect->setChain(this);
7163 sp<ThreadBase> thread = mThread.promote();
7164 if (thread == 0) {
7165 return NO_INIT;
7166 }
7167 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168
7169 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7170 // Auxiliary effects are inserted at the beginning of mEffects vector as
7171 // they are processed first and accumulated in chain input buffer
7172 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007173
Mathias Agopian65ab4712010-07-14 17:59:35 -07007174 // the input buffer for auxiliary effect contains mono samples in
7175 // 32 bit format. This is to avoid saturation in AudoMixer
7176 // accumulation stage. Saturation is done in EffectModule::process() before
7177 // calling the process in effect engine
7178 size_t numSamples = thread->frameCount();
7179 int32_t *buffer = new int32_t[numSamples];
7180 memset(buffer, 0, numSamples * sizeof(int32_t));
7181 effect->setInBuffer((int16_t *)buffer);
7182 // auxiliary effects output samples to chain input buffer for further processing
7183 // by insert effects
7184 effect->setOutBuffer(mInBuffer);
7185 } else {
7186 // Insert effects are inserted at the end of mEffects vector as they are processed
7187 // after track and auxiliary effects.
7188 // Insert effect order as a function of indicated preference:
7189 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7190 // another effect is present
7191 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7192 // last effect claiming first position
7193 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7194 // first effect claiming last position
7195 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7196 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7197 // already present
7198
7199 int size = (int)mEffects.size();
7200 int idx_insert = size;
7201 int idx_insert_first = -1;
7202 int idx_insert_last = -1;
7203
7204 for (int i = 0; i < size; i++) {
7205 effect_descriptor_t d = mEffects[i]->desc();
7206 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7207 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7208 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7209 // check invalid effect chaining combinations
7210 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7211 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007212 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007213 return INVALID_OPERATION;
7214 }
7215 // remember position of first insert effect and by default
7216 // select this as insert position for new effect
7217 if (idx_insert == size) {
7218 idx_insert = i;
7219 }
7220 // remember position of last insert effect claiming
7221 // first position
7222 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7223 idx_insert_first = i;
7224 }
7225 // remember position of first insert effect claiming
7226 // last position
7227 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7228 idx_insert_last == -1) {
7229 idx_insert_last = i;
7230 }
7231 }
7232 }
7233
7234 // modify idx_insert from first position if needed
7235 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7236 if (idx_insert_last != -1) {
7237 idx_insert = idx_insert_last;
7238 } else {
7239 idx_insert = size;
7240 }
7241 } else {
7242 if (idx_insert_first != -1) {
7243 idx_insert = idx_insert_first + 1;
7244 }
7245 }
7246
7247 // always read samples from chain input buffer
7248 effect->setInBuffer(mInBuffer);
7249
7250 // if last effect in the chain, output samples to chain
7251 // output buffer, otherwise to chain input buffer
7252 if (idx_insert == size) {
7253 if (idx_insert != 0) {
7254 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7255 mEffects[idx_insert-1]->configure();
7256 }
7257 effect->setOutBuffer(mOutBuffer);
7258 } else {
7259 effect->setOutBuffer(mInBuffer);
7260 }
7261 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007262
Steve Block3856b092011-10-20 11:56:00 +01007263 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264 }
7265 effect->configure();
7266 return NO_ERROR;
7267}
7268
Eric Laurentcab11242010-07-15 12:50:15 -07007269// removeEffect_l() must be called with PlaybackThread::mLock held
7270size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271{
7272 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 int size = (int)mEffects.size();
7274 int i;
7275 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7276
7277 for (i = 0; i < size; i++) {
7278 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007279 // calling stop here will remove pre-processing effect from the audio HAL.
7280 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7281 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007282 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7283 mEffects[i]->state() == EffectModule::STOPPING) {
7284 mEffects[i]->stop();
7285 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7287 delete[] effect->inBuffer();
7288 } else {
7289 if (i == size - 1 && i != 0) {
7290 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7291 mEffects[i - 1]->configure();
7292 }
7293 }
7294 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007295 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 break;
7297 }
7298 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007299
7300 return mEffects.size();
7301}
7302
Eric Laurentcab11242010-07-15 12:50:15 -07007303// setDevice_l() must be called with PlaybackThread::mLock held
7304void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305{
7306 size_t size = mEffects.size();
7307 for (size_t i = 0; i < size; i++) {
7308 mEffects[i]->setDevice(device);
7309 }
7310}
7311
Eric Laurentcab11242010-07-15 12:50:15 -07007312// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007313void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314{
7315 size_t size = mEffects.size();
7316 for (size_t i = 0; i < size; i++) {
7317 mEffects[i]->setMode(mode);
7318 }
7319}
7320
Eric Laurentcab11242010-07-15 12:50:15 -07007321// setVolume_l() must be called with PlaybackThread::mLock held
7322bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323{
7324 uint32_t newLeft = *left;
7325 uint32_t newRight = *right;
7326 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007327 int ctrlIdx = -1;
7328 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329
Eric Laurentcab11242010-07-15 12:50:15 -07007330 // first update volume controller
7331 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007332 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007333 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7334 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007335 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007336 break;
7337 }
7338 }
7339
7340 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007341 if (hasControl) {
7342 *left = mNewLeftVolume;
7343 *right = mNewRightVolume;
7344 }
7345 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007346 }
7347
7348 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007349 mLeftVolume = newLeft;
7350 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007351
7352 // second get volume update from volume controller
7353 if (ctrlIdx >= 0) {
7354 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007355 mNewLeftVolume = newLeft;
7356 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007357 }
7358 // then indicate volume to all other effects in chain.
7359 // Pass altered volume to effects before volume controller
7360 // and requested volume to effects after controller
7361 uint32_t lVol = newLeft;
7362 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007363
Mathias Agopian65ab4712010-07-14 17:59:35 -07007364 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007365 if ((int)i == ctrlIdx) continue;
7366 // this also works for ctrlIdx == -1 when there is no volume controller
7367 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 lVol = *left;
7369 rVol = *right;
7370 }
7371 mEffects[i]->setVolume(&lVol, &rVol, false);
7372 }
7373 *left = newLeft;
7374 *right = newRight;
7375
7376 return hasControl;
7377}
7378
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7380{
7381 const size_t SIZE = 256;
7382 char buffer[SIZE];
7383 String8 result;
7384
7385 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7386 result.append(buffer);
7387
7388 bool locked = tryLock(mLock);
7389 // failed to lock - AudioFlinger is probably deadlocked
7390 if (!locked) {
7391 result.append("\tCould not lock mutex:\n");
7392 }
7393
Eric Laurentcab11242010-07-15 12:50:15 -07007394 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7395 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396 mEffects.size(),
7397 (uint32_t)mInBuffer,
7398 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007399 mActiveTrackCnt);
7400 result.append(buffer);
7401 write(fd, result.string(), result.size());
7402
7403 for (size_t i = 0; i < mEffects.size(); ++i) {
7404 sp<EffectModule> effect = mEffects[i];
7405 if (effect != 0) {
7406 effect->dump(fd, args);
7407 }
7408 }
7409
7410 if (locked) {
7411 mLock.unlock();
7412 }
7413
7414 return NO_ERROR;
7415}
7416
Eric Laurent59255e42011-07-27 19:49:51 -07007417// must be called with ThreadBase::mLock held
7418void AudioFlinger::EffectChain::setEffectSuspended_l(
7419 const effect_uuid_t *type, bool suspend)
7420{
7421 sp<SuspendedEffectDesc> desc;
7422 // use effect type UUID timelow as key as there is no real risk of identical
7423 // timeLow fields among effect type UUIDs.
7424 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7425 if (suspend) {
7426 if (index >= 0) {
7427 desc = mSuspendedEffects.valueAt(index);
7428 } else {
7429 desc = new SuspendedEffectDesc();
7430 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7431 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007432 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007433 }
7434 if (desc->mRefCount++ == 0) {
7435 sp<EffectModule> effect = getEffectIfEnabled(type);
7436 if (effect != 0) {
7437 desc->mEffect = effect;
7438 effect->setSuspended(true);
7439 effect->setEnabled(false);
7440 }
7441 }
7442 } else {
7443 if (index < 0) {
7444 return;
7445 }
7446 desc = mSuspendedEffects.valueAt(index);
7447 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007448 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007449 desc->mRefCount = 1;
7450 }
7451 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007452 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007453 if (desc->mEffect != 0) {
7454 sp<EffectModule> effect = desc->mEffect.promote();
7455 if (effect != 0) {
7456 effect->setSuspended(false);
7457 sp<EffectHandle> handle = effect->controlHandle();
7458 if (handle != 0) {
7459 effect->setEnabled(handle->enabled());
7460 }
7461 }
7462 desc->mEffect.clear();
7463 }
7464 mSuspendedEffects.removeItemsAt(index);
7465 }
7466 }
7467}
7468
7469// must be called with ThreadBase::mLock held
7470void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7471{
7472 sp<SuspendedEffectDesc> desc;
7473
7474 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7475 if (suspend) {
7476 if (index >= 0) {
7477 desc = mSuspendedEffects.valueAt(index);
7478 } else {
7479 desc = new SuspendedEffectDesc();
7480 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007481 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007482 }
7483 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007484 Vector< sp<EffectModule> > effects;
7485 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007486 for (size_t i = 0; i < effects.size(); i++) {
7487 setEffectSuspended_l(&effects[i]->desc().type, true);
7488 }
7489 }
7490 } else {
7491 if (index < 0) {
7492 return;
7493 }
7494 desc = mSuspendedEffects.valueAt(index);
7495 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007496 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007497 desc->mRefCount = 1;
7498 }
7499 if (--desc->mRefCount == 0) {
7500 Vector<const effect_uuid_t *> types;
7501 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7502 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7503 continue;
7504 }
7505 types.add(&mSuspendedEffects.valueAt(i)->mType);
7506 }
7507 for (size_t i = 0; i < types.size(); i++) {
7508 setEffectSuspended_l(types[i], false);
7509 }
Steve Block3856b092011-10-20 11:56:00 +01007510 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007511 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7512 }
7513 }
7514}
7515
Eric Laurent6bffdb82011-09-23 08:40:41 -07007516
7517// The volume effect is used for automated tests only
7518#ifndef OPENSL_ES_H_
7519static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7520 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7521const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7522#endif //OPENSL_ES_H_
7523
Eric Laurentdb7c0792011-08-10 10:37:50 -07007524bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7525{
7526 // auxiliary effects and visualizer are never suspended on output mix
7527 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7528 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007529 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7530 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007531 return false;
7532 }
7533 return true;
7534}
7535
Glenn Kastend0539712012-01-30 12:56:03 -08007536void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007537{
Glenn Kastend0539712012-01-30 12:56:03 -08007538 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007539 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007540 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7541 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007542 }
Eric Laurent59255e42011-07-27 19:49:51 -07007543 }
Eric Laurent59255e42011-07-27 19:49:51 -07007544}
7545
7546sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7547 const effect_uuid_t *type)
7548{
Glenn Kasten090f0192012-01-30 13:00:02 -08007549 sp<EffectModule> effect = getEffectFromType_l(type);
7550 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007551}
7552
7553void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7554 bool enabled)
7555{
7556 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7557 if (enabled) {
7558 if (index < 0) {
7559 // if the effect is not suspend check if all effects are suspended
7560 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7561 if (index < 0) {
7562 return;
7563 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007564 if (!isEffectEligibleForSuspend(effect->desc())) {
7565 return;
7566 }
Eric Laurent59255e42011-07-27 19:49:51 -07007567 setEffectSuspended_l(&effect->desc().type, enabled);
7568 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007569 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007570 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007571 return;
7572 }
Eric Laurent59255e42011-07-27 19:49:51 -07007573 }
Steve Block3856b092011-10-20 11:56:00 +01007574 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007575 effect->desc().type.timeLow);
7576 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7577 // if effect is requested to suspended but was not yet enabled, supend it now.
7578 if (desc->mEffect == 0) {
7579 desc->mEffect = effect;
7580 effect->setEnabled(false);
7581 effect->setSuspended(true);
7582 }
7583 } else {
7584 if (index < 0) {
7585 return;
7586 }
Steve Block3856b092011-10-20 11:56:00 +01007587 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007588 effect->desc().type.timeLow);
7589 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7590 desc->mEffect.clear();
7591 effect->setSuspended(false);
7592 }
7593}
7594
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595#undef LOG_TAG
7596#define LOG_TAG "AudioFlinger"
7597
7598// ----------------------------------------------------------------------------
7599
7600status_t AudioFlinger::onTransact(
7601 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7602{
7603 return BnAudioFlinger::onTransact(code, data, reply, flags);
7604}
7605
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606}; // namespace android