blob: 779c4f5c381d49bd49a02fc6aa9037ab9b6af1e4 [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
1527 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001528 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001529 for (size_t i = 0; i < mTracks.size(); ++i) {
1530 sp<Track> t = mTracks[i];
1531 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001532 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1533 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001534 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001535 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001536 lStatus = BAD_VALUE;
1537 goto Exit;
1538 }
1539 }
1540 }
1541
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001543 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 if (track->getCblk() == NULL || track->name() < 0) {
1545 lStatus = NO_MEMORY;
1546 goto Exit;
1547 }
1548 mTracks.add(track);
1549
1550 sp<EffectChain> chain = getEffectChain_l(sessionId);
1551 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001552 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001554 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001555 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001557
1558 // invalidate track immediately if the stream type was moved to another thread since
1559 // createTrack() was called by the client process.
1560 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001561 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001562 this, streamType);
1563 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 }
1566 lStatus = NO_ERROR;
1567
1568Exit:
1569 if(status) {
1570 *status = lStatus;
1571 }
1572 return track;
1573}
1574
1575uint32_t AudioFlinger::PlaybackThread::latency() const
1576{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001577 Mutex::Autolock _l(mLock);
1578 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001579 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001580 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 return 0;
1582 }
1583}
1584
1585status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1586{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 mMasterVolume = value;
1588 return NO_ERROR;
1589}
1590
1591status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1592{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 mMasterMute = muted;
1594 return NO_ERROR;
1595}
1596
Glenn Kastenfff6d712012-01-12 16:38:12 -08001597status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599 mStreamTypes[stream].volume = value;
1600 return NO_ERROR;
1601}
1602
Glenn Kastenfff6d712012-01-12 16:38:12 -08001603status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 mStreamTypes[stream].mute = muted;
1606 return NO_ERROR;
1607}
1608
Glenn Kastenfff6d712012-01-12 16:38:12 -08001609float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610{
1611 return mStreamTypes[stream].volume;
1612}
1613
Glenn Kastenfff6d712012-01-12 16:38:12 -08001614bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615{
1616 return mStreamTypes[stream].mute;
1617}
1618
Mathias Agopian65ab4712010-07-14 17:59:35 -07001619// addTrack_l() must be called with ThreadBase::mLock held
1620status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1621{
1622 status_t status = ALREADY_EXISTS;
1623
1624 // set retry count for buffer fill
1625 track->mRetryCount = kMaxTrackStartupRetries;
1626 if (mActiveTracks.indexOf(track) < 0) {
1627 // the track is newly added, make sure it fills up all its
1628 // buffers before playing. This is to ensure the client will
1629 // effectively get the latency it requested.
1630 track->mFillingUpStatus = Track::FS_FILLING;
1631 track->mResetDone = false;
1632 mActiveTracks.add(track);
1633 if (track->mainBuffer() != mMixBuffer) {
1634 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1635 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001636 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001637 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 }
1639 }
1640
1641 status = NO_ERROR;
1642 }
1643
Steve Block3856b092011-10-20 11:56:00 +01001644 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 mWaitWorkCV.broadcast();
1646
1647 return status;
1648}
1649
1650// destroyTrack_l() must be called with ThreadBase::mLock held
1651void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1652{
1653 track->mState = TrackBase::TERMINATED;
1654 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001655 removeTrack_l(track);
1656 }
1657}
1658
1659void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1660{
1661 mTracks.remove(track);
1662 deleteTrackName_l(track->name());
1663 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1664 if (chain != 0) {
1665 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 }
1667}
1668
1669String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1670{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001671 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001672 char *s;
1673
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001674 Mutex::Autolock _l(mLock);
1675 if (initCheck() != NO_ERROR) {
1676 return out_s8;
1677 }
1678
Dima Zavin799a70e2011-04-18 16:57:27 -07001679 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001680 out_s8 = String8(s);
1681 free(s);
1682 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683}
1684
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001685// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001686void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1687 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001688 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689
Steve Block3856b092011-10-20 11:56:00 +01001690 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691
1692 switch (event) {
1693 case AudioSystem::OUTPUT_OPENED:
1694 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001695 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696 desc.samplingRate = mSampleRate;
1697 desc.format = mFormat;
1698 desc.frameCount = mFrameCount;
1699 desc.latency = latency();
1700 param2 = &desc;
1701 break;
1702
1703 case AudioSystem::STREAM_CONFIG_CHANGED:
1704 param2 = &param;
1705 case AudioSystem::OUTPUT_CLOSED:
1706 default:
1707 break;
1708 }
1709 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1710}
1711
1712void AudioFlinger::PlaybackThread::readOutputParameters()
1713{
Dima Zavin799a70e2011-04-18 16:57:27 -07001714 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001715 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1716 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001717 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001718 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001719 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720
1721 // FIXME - Current mixer implementation only supports stereo output: Always
1722 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001723 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 mMixBuffer = new int16_t[mFrameCount * 2];
1725 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1726
Eric Laurentde070132010-07-13 04:45:46 -07001727 // force reconfiguration of effect chains and engines to take new buffer size and audio
1728 // parameters into account
1729 // Note that mLock is not held when readOutputParameters() is called from the constructor
1730 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1731 // matter.
1732 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1733 Vector< sp<EffectChain> > effectChains = mEffectChains;
1734 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001735 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001736 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001737}
1738
1739status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1740{
Glenn Kastena0d68332012-01-27 16:47:15 -08001741 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 return BAD_VALUE;
1743 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001744 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001745 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 return INVALID_OPERATION;
1747 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001748 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749
Dima Zavin799a70e2011-04-18 16:57:27 -07001750 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751}
1752
Eric Laurent39e94f82010-07-28 01:32:47 -07001753uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754{
1755 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001756 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001757 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001758 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 }
1760
1761 for (size_t i = 0; i < mTracks.size(); ++i) {
1762 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001763 if (sessionId == track->sessionId() &&
1764 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001765 result |= TRACK_SESSION;
1766 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 }
1768 }
1769
Eric Laurent39e94f82010-07-28 01:32:47 -07001770 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771}
1772
Eric Laurentde070132010-07-13 04:45:46 -07001773uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1774{
Dima Zavinfce7a472011-04-19 22:30:36 -07001775 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001776 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001777 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1778 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001779 }
1780 for (size_t i = 0; i < mTracks.size(); i++) {
1781 sp<Track> track = mTracks[i];
1782 if (sessionId == track->sessionId() &&
1783 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001784 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001785 }
1786 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001787 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001788}
1789
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790
Glenn Kastenaed850d2012-01-26 09:46:34 -08001791AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001792{
1793 Mutex::Autolock _l(mLock);
1794 return mOutput;
1795}
1796
1797AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1798{
1799 Mutex::Autolock _l(mLock);
1800 AudioStreamOut *output = mOutput;
1801 mOutput = NULL;
1802 return output;
1803}
1804
1805// this method must always be called either with ThreadBase mLock held or inside the thread loop
1806audio_stream_t* AudioFlinger::PlaybackThread::stream()
1807{
1808 if (mOutput == NULL) {
1809 return NULL;
1810 }
1811 return &mOutput->stream->common;
1812}
1813
Eric Laurent162b40b2011-12-05 09:47:19 -08001814uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1815{
1816 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1817 // decoding and transfer time. So sleeping for half of the latency would likely cause
1818 // underruns
1819 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1820 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1821 } else {
1822 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1823 }
1824}
1825
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826// ----------------------------------------------------------------------------
1827
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001828AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001829 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001830 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001831 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1832 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 // FIXME - Current mixer implementation only supports stereo output
1835 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001836 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837 }
1838}
1839
1840AudioFlinger::MixerThread::~MixerThread()
1841{
1842 delete mAudioMixer;
1843}
1844
1845bool AudioFlinger::MixerThread::threadLoop()
1846{
1847 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001848 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 nsecs_t standbyTime = systemTime();
1850 size_t mixBufferSize = mFrameCount * mFrameSize;
1851 // FIXME: Relaxed timing because of a certain device that can't meet latency
1852 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001853 // increase threshold again due to low power audio mode. The way this warning threshold is
1854 // calculated and its usefulness should be reconsidered anyway.
1855 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 nsecs_t lastWarning = 0;
1857 bool longStandbyExit = false;
1858 uint32_t activeSleepTime = activeSleepTimeUs();
1859 uint32_t idleSleepTime = idleSleepTimeUs();
1860 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001861 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001863#ifdef DEBUG_CPU_USAGE
1864 ThreadCpuUsage cpu;
1865 const CentralTendencyStatistics& stats = cpu.statistics();
1866#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867
Eric Laurentfeb0db62011-07-22 09:04:31 -07001868 acquireWakeLock();
1869
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 while (!exitPending())
1871 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001872#ifdef DEBUG_CPU_USAGE
1873 cpu.sampleAndEnable();
1874 unsigned n = stats.n();
1875 // cpu.elapsed() is expensive, so don't call it every loop
1876 if ((n & 127) == 1) {
1877 long long elapsed = cpu.elapsed();
1878 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1879 double perLoop = elapsed / (double) n;
1880 double perLoop100 = perLoop * 0.01;
1881 double mean = stats.mean();
1882 double stddev = stats.stddev();
1883 double minimum = stats.minimum();
1884 double maximum = stats.maximum();
1885 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001886 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 -07001887 elapsed * .000000001, n, perLoop * .000001,
1888 mean * .001,
1889 stddev * .001,
1890 minimum * .001,
1891 maximum * .001,
1892 mean / perLoop100,
1893 stddev / perLoop100,
1894 minimum / perLoop100,
1895 maximum / perLoop100);
1896 }
1897 }
1898#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 processConfigEvents();
1900
1901 mixerStatus = MIXER_IDLE;
1902 { // scope for mLock
1903
1904 Mutex::Autolock _l(mLock);
1905
1906 if (checkForNewParameters_l()) {
1907 mixBufferSize = mFrameCount * mFrameSize;
1908 // FIXME: Relaxed timing because of a certain device that can't meet latency
1909 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001910 // increase threshold again due to low power audio mode. The way this warning
1911 // threshold is calculated and its usefulness should be reconsidered anyway.
1912 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 activeSleepTime = activeSleepTimeUs();
1914 idleSleepTime = idleSleepTimeUs();
1915 }
1916
1917 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1918
1919 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001920 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1921 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001923 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001924 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001925 mStandby = true;
1926 mBytesWritten = 0;
1927 }
1928
1929 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1930 // we're about to wait, flush the binder command buffer
1931 IPCThreadState::self()->flushCommands();
1932
1933 if (exitPending()) break;
1934
Eric Laurentfeb0db62011-07-22 09:04:31 -07001935 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001937 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001939 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001940 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941
Eric Laurent27741442012-01-17 19:20:12 -08001942 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001943 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 char value[PROPERTY_VALUE_MAX];
1945 property_get("ro.audio.silent", value, "0");
1946 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001947 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 setMasterMute(true);
1949 }
1950 }
1951
1952 standbyTime = systemTime() + kStandbyTimeInNsecs;
1953 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001954 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 continue;
1956 }
1957 }
1958
1959 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1960
1961 // prevent any changes in effect chain list and in each effect chain
1962 // during mixing and effect process as the audio buffers could be deleted
1963 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001964 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966
Glenn Kastenf6b16782011-12-15 09:51:17 -08001967 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 // mix buffers...
1969 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001970 // increase sleep time progressively when application underrun condition clears.
1971 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1972 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1973 // such that we would underrun the audio HAL.
1974 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001975 sleepTimeShift--;
1976 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001977 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 standbyTime = systemTime() + kStandbyTimeInNsecs;
1979 //TODO: delay standby when effects have a tail
1980 } else {
1981 // If no tracks are ready, sleep once for the duration of an output
1982 // buffer size, then write 0s to the output
1983 if (sleepTime == 0) {
1984 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001985 sleepTime = activeSleepTime >> sleepTimeShift;
1986 if (sleepTime < kMinThreadSleepTimeUs) {
1987 sleepTime = kMinThreadSleepTimeUs;
1988 }
1989 // reduce sleep time in case of consecutive application underruns to avoid
1990 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1991 // duration we would end up writing less data than needed by the audio HAL if
1992 // the condition persists.
1993 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1994 sleepTimeShift++;
1995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996 } else {
1997 sleepTime = idleSleepTime;
1998 }
1999 } else if (mBytesWritten != 0 ||
2000 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2001 memset (mMixBuffer, 0, mixBufferSize);
2002 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002003 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 }
2005 // TODO add standby time extension fct of effect tail
2006 }
2007
2008 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002009 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 }
2011 // sleepTime == 0 means we must write to audio hardware
2012 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002013 for (size_t i = 0; i < effectChains.size(); i ++) {
2014 effectChains[i]->process_l();
2015 }
2016 // enable changes in effect chain
2017 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002018 mLastWriteTime = systemTime();
2019 mInWrite = true;
2020 mBytesWritten += mixBufferSize;
2021
Dima Zavin799a70e2011-04-18 16:57:27 -07002022 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2024 mNumWrites++;
2025 mInWrite = false;
2026 nsecs_t now = systemTime();
2027 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002028 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002030 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002031 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 ns2ms(delta), mNumDelayedWrites, this);
2033 lastWarning = now;
2034 }
2035 if (mStandby) {
2036 longStandbyExit = true;
2037 }
2038 }
2039 mStandby = false;
2040 } else {
2041 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002042 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002043 usleep(sleepTime);
2044 }
2045
2046 // finally let go of all our tracks, without the lock held
2047 // since we can't guarantee the destructors won't acquire that
2048 // same lock.
2049 tracksToRemove.clear();
2050
2051 // Effect chains will be actually deleted here if they were removed from
2052 // mEffectChains list during mixing or effects processing
2053 effectChains.clear();
2054 }
2055
2056 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002057 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 }
2059
Eric Laurentfeb0db62011-07-22 09:04:31 -07002060 releaseWakeLock();
2061
Steve Block3856b092011-10-20 11:56:00 +01002062 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 return false;
2064}
2065
2066// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002067AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2068 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002069{
2070
Glenn Kasten29c23c32012-01-26 13:37:52 -08002071 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 // find out which tracks need to be processed
2073 size_t count = activeTracks.size();
2074 size_t mixedTracks = 0;
2075 size_t tracksWithEffect = 0;
2076
2077 float masterVolume = mMasterVolume;
2078 bool masterMute = mMasterMute;
2079
Eric Laurent571d49c2010-08-11 05:20:11 -07002080 if (masterMute) {
2081 masterVolume = 0;
2082 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002084 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002086 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002087 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 masterVolume = (float)((v + (1 << 23)) >> 24);
2089 chain.clear();
2090 }
2091
2092 for (size_t i=0 ; i<count ; i++) {
2093 sp<Track> t = activeTracks[i].promote();
2094 if (t == 0) continue;
2095
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002096 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 Track* const track = t.get();
2098 audio_track_cblk_t* cblk = track->cblk();
2099
2100 // The first time a track is added we wait
2101 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002102 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002103 // make sure that we have enough frames to mix one full buffer.
2104 // enforce this condition only once to enable draining the buffer in case the client
2105 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002106 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002107 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002108 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002109 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002110 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002111 if (t->sampleRate() == (int)mSampleRate) {
2112 minFrames = mFrameCount;
2113 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002114 // +1 for rounding and +1 for additional sample needed for interpolation
2115 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2116 // add frames already consumed but not yet released by the resampler
2117 // because cblk->framesReady() will include these frames
2118 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2119 // the minimum track buffer size is normally twice the number of frames necessary
2120 // to fill one buffer and the resampler should not leave more than one buffer worth
2121 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002122 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002123 }
2124 }
2125 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 !track->isPaused() && !track->isTerminated())
2127 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002128 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129
2130 mixedTracks++;
2131
2132 // track->mainBuffer() != mMixBuffer means there is an effect chain
2133 // connected to the track
2134 chain.clear();
2135 if (track->mainBuffer() != mMixBuffer) {
2136 chain = getEffectChain_l(track->sessionId());
2137 // Delegate volume control to effect in track effect chain if needed
2138 if (chain != 0) {
2139 tracksWithEffect++;
2140 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002141 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002142 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 }
2144 }
2145
2146
2147 int param = AudioMixer::VOLUME;
2148 if (track->mFillingUpStatus == Track::FS_FILLED) {
2149 // no ramp for the first volume setting
2150 track->mFillingUpStatus = Track::FS_ACTIVE;
2151 if (track->mState == TrackBase::RESUMING) {
2152 track->mState = TrackBase::ACTIVE;
2153 param = AudioMixer::RAMP_VOLUME;
2154 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002155 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156 } else if (cblk->server != 0) {
2157 // If the track is stopped before the first frame was mixed,
2158 // do not apply ramp
2159 param = AudioMixer::RAMP_VOLUME;
2160 }
2161
2162 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002163 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002164 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002166 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 if (track->isPausing()) {
2168 track->setPaused();
2169 }
2170 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002171
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 // read original volumes with volume control
2173 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002175 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002176 vl = vlr & 0xFFFF;
2177 vr = vlr >> 16;
2178 // track volumes come from shared memory, so can't be trusted and must be clamped
2179 if (vl > MAX_GAIN_INT) {
2180 ALOGV("Track left volume out of range: %04X", vl);
2181 vl = MAX_GAIN_INT;
2182 }
2183 if (vr > MAX_GAIN_INT) {
2184 ALOGV("Track right volume out of range: %04X", vr);
2185 vr = MAX_GAIN_INT;
2186 }
2187 // now apply the master volume and stream type volume
2188 vl = (uint32_t)(v * vl) << 12;
2189 vr = (uint32_t)(v * vr) << 12;
2190 // assuming master volume and stream type volume each go up to 1.0,
2191 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192
Glenn Kasten05632a52012-01-03 14:22:33 -08002193 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2194 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002195 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002196 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002197 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002198 }
2199 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002201 // Delegate volume control to effect in track effect chain if needed
2202 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2203 // Do not ramp volume if volume is controlled by effect
2204 param = AudioMixer::VOLUME;
2205 track->mHasVolumeController = true;
2206 } else {
2207 // force no volume ramp when volume controller was just disabled or removed
2208 // from effect chain to avoid volume spike
2209 if (track->mHasVolumeController) {
2210 param = AudioMixer::VOLUME;
2211 }
2212 track->mHasVolumeController = false;
2213 }
2214
2215 // Convert volumes from 8.24 to 4.12 format
2216 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002217 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002218 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2219 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2220 left = int16_t(v_clamped);
2221 v_clamped = (vr + (1 << 11)) >> 12;
2222 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2223 right = int16_t(v_clamped);
2224
2225 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2226 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002229 mAudioMixer->setBufferProvider(name, track);
2230 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002232 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2233 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2234 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002235 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002236 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 AudioMixer::TRACK,
2238 AudioMixer::FORMAT, (void *)track->format());
2239 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002240 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002242 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002244 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 AudioMixer::RESAMPLE,
2246 AudioMixer::SAMPLE_RATE,
2247 (void *)(cblk->sampleRate));
2248 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002249 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 AudioMixer::TRACK,
2251 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2252 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002253 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254 AudioMixer::TRACK,
2255 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2256
2257 // reset retry count
2258 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002259 // If one track is ready, set the mixer ready if:
2260 // - the mixer was not ready during previous round OR
2261 // - no other track is not ready
2262 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2263 mixerStatus != MIXER_TRACKS_ENABLED) {
2264 mixerStatus = MIXER_TRACKS_READY;
2265 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002267 //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 -07002268 if (track->isStopped()) {
2269 track->reset();
2270 }
2271 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2272 // We have consumed all the buffers of this track.
2273 // Remove it from the list of active tracks.
2274 tracksToRemove->add(track);
2275 } else {
2276 // No buffers for this track. Give it a few chances to
2277 // fill a buffer, then remove it from active list.
2278 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002279 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002281 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002282 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002283 // If one track is not ready, mark the mixer also not ready if:
2284 // - the mixer was ready during previous round OR
2285 // - no other track is ready
2286 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2287 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 mixerStatus = MIXER_TRACKS_ENABLED;
2289 }
2290 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002291 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 }
2293 }
2294
2295 // remove all the tracks that need to be...
2296 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002297 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 for (size_t i=0 ; i<count ; i++) {
2299 const sp<Track>& track = tracksToRemove->itemAt(i);
2300 mActiveTracks.remove(track);
2301 if (track->mainBuffer() != mMixBuffer) {
2302 chain = getEffectChain_l(track->sessionId());
2303 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002304 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002305 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 }
2307 }
2308 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002309 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310 }
2311 }
2312 }
2313
2314 // mix buffer must be cleared if all tracks are connected to an
2315 // effect chain as in this case the mixer will not write to
2316 // mix buffer and track effects will accumulate into it
2317 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2318 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2319 }
2320
Eric Laurent27741442012-01-17 19:20:12 -08002321 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 return mixerStatus;
2323}
2324
Glenn Kastenfff6d712012-01-12 16:38:12 -08002325void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326{
Steve Block3856b092011-10-20 11:56:00 +01002327 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002328 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002330
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 size_t size = mTracks.size();
2332 for (size_t i = 0; i < size; i++) {
2333 sp<Track> t = mTracks[i];
2334 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002335 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337 }
2338 }
2339}
2340
Glenn Kastenfff6d712012-01-12 16:38:12 -08002341void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002342{
Steve Block3856b092011-10-20 11:56:00 +01002343 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002344 this, streamType, valid);
2345 Mutex::Autolock _l(mLock);
2346
2347 mStreamTypes[streamType].valid = valid;
2348}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349
2350// getTrackName_l() must be called with ThreadBase::mLock held
2351int AudioFlinger::MixerThread::getTrackName_l()
2352{
2353 return mAudioMixer->getTrackName();
2354}
2355
2356// deleteTrackName_l() must be called with ThreadBase::mLock held
2357void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2358{
Steve Block3856b092011-10-20 11:56:00 +01002359 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 mAudioMixer->deleteTrackName(name);
2361}
2362
2363// checkForNewParameters_l() must be called with ThreadBase::mLock held
2364bool AudioFlinger::MixerThread::checkForNewParameters_l()
2365{
2366 bool reconfig = false;
2367
2368 while (!mNewParameters.isEmpty()) {
2369 status_t status = NO_ERROR;
2370 String8 keyValuePair = mNewParameters[0];
2371 AudioParameter param = AudioParameter(keyValuePair);
2372 int value;
2373
2374 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2375 reconfig = true;
2376 }
2377 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002378 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 status = BAD_VALUE;
2380 } else {
2381 reconfig = true;
2382 }
2383 }
2384 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002385 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 status = BAD_VALUE;
2387 } else {
2388 reconfig = true;
2389 }
2390 }
2391 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2392 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002393 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394 // if frame count is changed after track creation
2395 if (!mTracks.isEmpty()) {
2396 status = INVALID_OPERATION;
2397 } else {
2398 reconfig = true;
2399 }
2400 }
2401 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002402 // when changing the audio output device, call addBatteryData to notify
2403 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002404 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002405 uint32_t params = 0;
2406 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002407 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002408 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2409 }
2410
2411 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002412 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002413 // check if any other device (except speaker) is on
2414 if (value & deviceWithoutSpeaker ) {
2415 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2416 }
2417
2418 if (params != 0) {
2419 addBatteryData(params);
2420 }
2421 }
2422
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423 // forward device change to effects that have requested to be
2424 // aware of attached audio device.
2425 mDevice = (uint32_t)value;
2426 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002427 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 }
2429 }
2430
2431 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002432 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002433 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002435 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 mStandby = true;
2437 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002438 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002439 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 }
2441 if (status == NO_ERROR && reconfig) {
2442 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002443 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2444 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445 readOutputParameters();
2446 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2447 for (size_t i = 0; i < mTracks.size() ; i++) {
2448 int name = getTrackName_l();
2449 if (name < 0) break;
2450 mTracks[i]->mName = name;
2451 // limit track sample rate to 2 x new output sample rate
2452 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2453 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2454 }
2455 }
2456 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2457 }
2458 }
2459
2460 mNewParameters.removeAt(0);
2461
2462 mParamStatus = status;
2463 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002464 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2465 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002466 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467 }
2468 return reconfig;
2469}
2470
2471status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2472{
2473 const size_t SIZE = 256;
2474 char buffer[SIZE];
2475 String8 result;
2476
2477 PlaybackThread::dumpInternals(fd, args);
2478
2479 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2480 result.append(buffer);
2481 write(fd, result.string(), result.size());
2482 return NO_ERROR;
2483}
2484
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2486{
Eric Laurent60e18242010-07-29 06:50:24 -07002487 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002488}
2489
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002490uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2491{
2492 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2493}
2494
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002496AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2497 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002498 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002499 // mLeftVolFloat, mRightVolFloat
2500 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502}
2503
2504AudioFlinger::DirectOutputThread::~DirectOutputThread()
2505{
2506}
2507
Mathias Agopian65ab4712010-07-14 17:59:35 -07002508static inline
2509int32_t mul(int16_t in, int16_t v)
2510{
2511#if defined(__arm__) && !defined(__thumb__)
2512 int32_t out;
2513 asm( "smulbb %[out], %[in], %[v] \n"
2514 : [out]"=r"(out)
2515 : [in]"%r"(in), [v]"r"(v)
2516 : );
2517 return out;
2518#else
2519 return in * int32_t(v);
2520#endif
2521}
2522
2523void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2524{
2525 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002526 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527 return;
2528 }
2529
2530 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002531 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002532 size_t count = mFrameCount * mChannelCount;
2533 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2534 int16_t *dst = mMixBuffer + count-1;
2535 while(count--) {
2536 *dst-- = (int16_t)(*src--^0x80) << 8;
2537 }
2538 }
2539
2540 size_t frameCount = mFrameCount;
2541 int16_t *out = mMixBuffer;
2542 if (ramp) {
2543 if (mChannelCount == 1) {
2544 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2545 int32_t vlInc = d / (int32_t)frameCount;
2546 int32_t vl = ((int32_t)mLeftVolShort << 16);
2547 do {
2548 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2549 out++;
2550 vl += vlInc;
2551 } while (--frameCount);
2552
2553 } else {
2554 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2555 int32_t vlInc = d / (int32_t)frameCount;
2556 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2557 int32_t vrInc = d / (int32_t)frameCount;
2558 int32_t vl = ((int32_t)mLeftVolShort << 16);
2559 int32_t vr = ((int32_t)mRightVolShort << 16);
2560 do {
2561 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2562 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2563 out += 2;
2564 vl += vlInc;
2565 vr += vrInc;
2566 } while (--frameCount);
2567 }
2568 } else {
2569 if (mChannelCount == 1) {
2570 do {
2571 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2572 out++;
2573 } while (--frameCount);
2574 } else {
2575 do {
2576 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2577 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2578 out += 2;
2579 } while (--frameCount);
2580 }
2581 }
2582
2583 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002584 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002585 size_t count = mFrameCount * mChannelCount;
2586 int16_t *src = mMixBuffer;
2587 uint8_t *dst = (uint8_t *)mMixBuffer;
2588 while(count--) {
2589 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2590 }
2591 }
2592
2593 mLeftVolShort = leftVol;
2594 mRightVolShort = rightVol;
2595}
2596
2597bool AudioFlinger::DirectOutputThread::threadLoop()
2598{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002599 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002600 sp<Track> trackToRemove;
2601 sp<Track> activeTrack;
2602 nsecs_t standbyTime = systemTime();
2603 int8_t *curBuf;
2604 size_t mixBufferSize = mFrameCount*mFrameSize;
2605 uint32_t activeSleepTime = activeSleepTimeUs();
2606 uint32_t idleSleepTime = idleSleepTimeUs();
2607 uint32_t sleepTime = idleSleepTime;
2608 // use shorter standby delay as on normal output to release
2609 // hardware resources as soon as possible
2610 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2611
Eric Laurentfeb0db62011-07-22 09:04:31 -07002612 acquireWakeLock();
2613
Mathias Agopian65ab4712010-07-14 17:59:35 -07002614 while (!exitPending())
2615 {
2616 bool rampVolume;
2617 uint16_t leftVol;
2618 uint16_t rightVol;
2619 Vector< sp<EffectChain> > effectChains;
2620
2621 processConfigEvents();
2622
2623 mixerStatus = MIXER_IDLE;
2624
2625 { // scope for the mLock
2626
2627 Mutex::Autolock _l(mLock);
2628
2629 if (checkForNewParameters_l()) {
2630 mixBufferSize = mFrameCount*mFrameSize;
2631 activeSleepTime = activeSleepTimeUs();
2632 idleSleepTime = idleSleepTimeUs();
2633 standbyDelay = microseconds(activeSleepTime*2);
2634 }
2635
2636 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002637 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2638 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 // wait until we have something to do...
2640 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002641 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002642 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643 mStandby = true;
2644 mBytesWritten = 0;
2645 }
2646
2647 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2648 // we're about to wait, flush the binder command buffer
2649 IPCThreadState::self()->flushCommands();
2650
2651 if (exitPending()) break;
2652
Eric Laurentfeb0db62011-07-22 09:04:31 -07002653 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002654 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002655 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002656 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002657 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658
Glenn Kastenf1d45922012-01-13 15:54:24 -08002659 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002660 char value[PROPERTY_VALUE_MAX];
2661 property_get("ro.audio.silent", value, "0");
2662 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002663 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 setMasterMute(true);
2665 }
2666 }
2667
2668 standbyTime = systemTime() + standbyDelay;
2669 sleepTime = idleSleepTime;
2670 continue;
2671 }
2672 }
2673
2674 effectChains = mEffectChains;
2675
2676 // find out which tracks need to be processed
2677 if (mActiveTracks.size() != 0) {
2678 sp<Track> t = mActiveTracks[0].promote();
2679 if (t == 0) continue;
2680
2681 Track* const track = t.get();
2682 audio_track_cblk_t* cblk = track->cblk();
2683
2684 // The first time a track is added we wait
2685 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002686 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002687 !track->isPaused() && !track->isTerminated())
2688 {
Steve Block3856b092011-10-20 11:56:00 +01002689 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690
2691 if (track->mFillingUpStatus == Track::FS_FILLED) {
2692 track->mFillingUpStatus = Track::FS_ACTIVE;
2693 mLeftVolFloat = mRightVolFloat = 0;
2694 mLeftVolShort = mRightVolShort = 0;
2695 if (track->mState == TrackBase::RESUMING) {
2696 track->mState = TrackBase::ACTIVE;
2697 rampVolume = true;
2698 }
2699 } else if (cblk->server != 0) {
2700 // If the track is stopped before the first frame was mixed,
2701 // do not apply ramp
2702 rampVolume = true;
2703 }
2704 // compute volume for this track
2705 float left, right;
2706 if (track->isMuted() || mMasterMute || track->isPausing() ||
2707 mStreamTypes[track->type()].mute) {
2708 left = right = 0;
2709 if (track->isPausing()) {
2710 track->setPaused();
2711 }
2712 } else {
2713 float typeVolume = mStreamTypes[track->type()].volume;
2714 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002715 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002716 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2718 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002719 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2721 right = v_clamped/MAX_GAIN;
2722 }
2723
2724 if (left != mLeftVolFloat || right != mRightVolFloat) {
2725 mLeftVolFloat = left;
2726 mRightVolFloat = right;
2727
2728 // If audio HAL implements volume control,
2729 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002730 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 left = 1.0f;
2732 right = 1.0f;
2733 }
2734
2735 // Convert volumes from float to 8.24
2736 uint32_t vl = (uint32_t)(left * (1 << 24));
2737 uint32_t vr = (uint32_t)(right * (1 << 24));
2738
2739 // Delegate volume control to effect in track effect chain if needed
2740 // only one effect chain can be present on DirectOutputThread, so if
2741 // there is one, the track is connected to it
2742 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002743 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002744 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 rampVolume = false;
2746 }
2747 }
2748
2749 // Convert volumes from 8.24 to 4.12 format
2750 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2751 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2752 leftVol = (uint16_t)v_clamped;
2753 v_clamped = (vr + (1 << 11)) >> 12;
2754 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2755 rightVol = (uint16_t)v_clamped;
2756 } else {
2757 leftVol = mLeftVolShort;
2758 rightVol = mRightVolShort;
2759 rampVolume = false;
2760 }
2761
2762 // reset retry count
2763 track->mRetryCount = kMaxTrackRetriesDirect;
2764 activeTrack = t;
2765 mixerStatus = MIXER_TRACKS_READY;
2766 } else {
Steve Block3856b092011-10-20 11:56:00 +01002767 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768 if (track->isStopped()) {
2769 track->reset();
2770 }
2771 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2772 // We have consumed all the buffers of this track.
2773 // Remove it from the list of active tracks.
2774 trackToRemove = track;
2775 } else {
2776 // No buffers for this track. Give it a few chances to
2777 // fill a buffer, then remove it from active list.
2778 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002779 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 trackToRemove = track;
2781 } else {
2782 mixerStatus = MIXER_TRACKS_ENABLED;
2783 }
2784 }
2785 }
2786 }
2787
2788 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002789 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790 mActiveTracks.remove(trackToRemove);
2791 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002792 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002793 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002794 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 }
2796 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002797 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 }
2799 }
2800
Eric Laurentde070132010-07-13 04:45:46 -07002801 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 }
2803
Glenn Kastenf6b16782011-12-15 09:51:17 -08002804 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 AudioBufferProvider::Buffer buffer;
2806 size_t frameCount = mFrameCount;
2807 curBuf = (int8_t *)mMixBuffer;
2808 // output audio to hardware
2809 while (frameCount) {
2810 buffer.frameCount = frameCount;
2811 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002812 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813 memset(curBuf, 0, frameCount * mFrameSize);
2814 break;
2815 }
2816 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2817 frameCount -= buffer.frameCount;
2818 curBuf += buffer.frameCount * mFrameSize;
2819 activeTrack->releaseBuffer(&buffer);
2820 }
2821 sleepTime = 0;
2822 standbyTime = systemTime() + standbyDelay;
2823 } else {
2824 if (sleepTime == 0) {
2825 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2826 sleepTime = activeSleepTime;
2827 } else {
2828 sleepTime = idleSleepTime;
2829 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002830 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2832 sleepTime = 0;
2833 }
2834 }
2835
2836 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002837 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 }
2839 // sleepTime == 0 means we must write to audio hardware
2840 if (sleepTime == 0) {
2841 if (mixerStatus == MIXER_TRACKS_READY) {
2842 applyVolume(leftVol, rightVol, rampVolume);
2843 }
2844 for (size_t i = 0; i < effectChains.size(); i ++) {
2845 effectChains[i]->process_l();
2846 }
Eric Laurentde070132010-07-13 04:45:46 -07002847 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848
2849 mLastWriteTime = systemTime();
2850 mInWrite = true;
2851 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002852 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2854 mNumWrites++;
2855 mInWrite = false;
2856 mStandby = false;
2857 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002858 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002859 usleep(sleepTime);
2860 }
2861
2862 // finally let go of removed track, without the lock held
2863 // since we can't guarantee the destructors won't acquire that
2864 // same lock.
2865 trackToRemove.clear();
2866 activeTrack.clear();
2867
2868 // Effect chains will be actually deleted here if they were removed from
2869 // mEffectChains list during mixing or effects processing
2870 effectChains.clear();
2871 }
2872
2873 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002874 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 }
2876
Eric Laurentfeb0db62011-07-22 09:04:31 -07002877 releaseWakeLock();
2878
Steve Block3856b092011-10-20 11:56:00 +01002879 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 return false;
2881}
2882
2883// getTrackName_l() must be called with ThreadBase::mLock held
2884int AudioFlinger::DirectOutputThread::getTrackName_l()
2885{
2886 return 0;
2887}
2888
2889// deleteTrackName_l() must be called with ThreadBase::mLock held
2890void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2891{
2892}
2893
2894// checkForNewParameters_l() must be called with ThreadBase::mLock held
2895bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2896{
2897 bool reconfig = false;
2898
2899 while (!mNewParameters.isEmpty()) {
2900 status_t status = NO_ERROR;
2901 String8 keyValuePair = mNewParameters[0];
2902 AudioParameter param = AudioParameter(keyValuePair);
2903 int value;
2904
2905 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2906 // do not accept frame count changes if tracks are open as the track buffer
2907 // size depends on frame count and correct behavior would not be garantied
2908 // if frame count is changed after track creation
2909 if (!mTracks.isEmpty()) {
2910 status = INVALID_OPERATION;
2911 } else {
2912 reconfig = true;
2913 }
2914 }
2915 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002916 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002917 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002919 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 mStandby = true;
2921 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002922 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002923 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 }
2925 if (status == NO_ERROR && reconfig) {
2926 readOutputParameters();
2927 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2928 }
2929 }
2930
2931 mNewParameters.removeAt(0);
2932
2933 mParamStatus = status;
2934 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002935 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2936 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002937 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938 }
2939 return reconfig;
2940}
2941
2942uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2943{
2944 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002945 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002946 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 } else {
2948 time = 10000;
2949 }
2950 return time;
2951}
2952
2953uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2954{
2955 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002956 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002957 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 } else {
2959 time = 10000;
2960 }
2961 return time;
2962}
2963
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002964uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2965{
2966 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002967 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002968 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2969 } else {
2970 time = 10000;
2971 }
2972 return time;
2973}
2974
2975
Mathias Agopian65ab4712010-07-14 17:59:35 -07002976// ----------------------------------------------------------------------------
2977
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002978AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002979 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002980 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2981 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983 addOutputTrack(mainThread);
2984}
2985
2986AudioFlinger::DuplicatingThread::~DuplicatingThread()
2987{
2988 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2989 mOutputTracks[i]->destroy();
2990 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991}
2992
2993bool AudioFlinger::DuplicatingThread::threadLoop()
2994{
2995 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002996 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002997 nsecs_t standbyTime = systemTime();
2998 size_t mixBufferSize = mFrameCount*mFrameSize;
2999 SortedVector< sp<OutputTrack> > outputTracks;
3000 uint32_t writeFrames = 0;
3001 uint32_t activeSleepTime = activeSleepTimeUs();
3002 uint32_t idleSleepTime = idleSleepTimeUs();
3003 uint32_t sleepTime = idleSleepTime;
3004 Vector< sp<EffectChain> > effectChains;
3005
Eric Laurentfeb0db62011-07-22 09:04:31 -07003006 acquireWakeLock();
3007
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 while (!exitPending())
3009 {
3010 processConfigEvents();
3011
3012 mixerStatus = MIXER_IDLE;
3013 { // scope for the mLock
3014
3015 Mutex::Autolock _l(mLock);
3016
3017 if (checkForNewParameters_l()) {
3018 mixBufferSize = mFrameCount*mFrameSize;
3019 updateWaitTime();
3020 activeSleepTime = activeSleepTimeUs();
3021 idleSleepTime = idleSleepTimeUs();
3022 }
3023
3024 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3025
3026 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3027 outputTracks.add(mOutputTracks[i]);
3028 }
3029
3030 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003031 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3032 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003033 if (!mStandby) {
3034 for (size_t i = 0; i < outputTracks.size(); i++) {
3035 outputTracks[i]->stop();
3036 }
3037 mStandby = true;
3038 mBytesWritten = 0;
3039 }
3040
3041 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3042 // we're about to wait, flush the binder command buffer
3043 IPCThreadState::self()->flushCommands();
3044 outputTracks.clear();
3045
3046 if (exitPending()) break;
3047
Eric Laurentfeb0db62011-07-22 09:04:31 -07003048 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003049 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003051 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003052 acquireWakeLock_l();
3053
Eric Laurent27741442012-01-17 19:20:12 -08003054 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003055 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 char value[PROPERTY_VALUE_MAX];
3057 property_get("ro.audio.silent", value, "0");
3058 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003059 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 setMasterMute(true);
3061 }
3062 }
3063
3064 standbyTime = systemTime() + kStandbyTimeInNsecs;
3065 sleepTime = idleSleepTime;
3066 continue;
3067 }
3068 }
3069
3070 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3071
3072 // prevent any changes in effect chain list and in each effect chain
3073 // during mixing and effect process as the audio buffers could be deleted
3074 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003075 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 }
3077
Glenn Kastenf6b16782011-12-15 09:51:17 -08003078 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003079 // mix buffers...
3080 if (outputsReady(outputTracks)) {
3081 mAudioMixer->process();
3082 } else {
3083 memset(mMixBuffer, 0, mixBufferSize);
3084 }
3085 sleepTime = 0;
3086 writeFrames = mFrameCount;
3087 } else {
3088 if (sleepTime == 0) {
3089 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3090 sleepTime = activeSleepTime;
3091 } else {
3092 sleepTime = idleSleepTime;
3093 }
3094 } else if (mBytesWritten != 0) {
3095 // flush remaining overflow buffers in output tracks
3096 for (size_t i = 0; i < outputTracks.size(); i++) {
3097 if (outputTracks[i]->isActive()) {
3098 sleepTime = 0;
3099 writeFrames = 0;
3100 memset(mMixBuffer, 0, mixBufferSize);
3101 break;
3102 }
3103 }
3104 }
3105 }
3106
3107 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003108 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 }
3110 // sleepTime == 0 means we must write to audio hardware
3111 if (sleepTime == 0) {
3112 for (size_t i = 0; i < effectChains.size(); i ++) {
3113 effectChains[i]->process_l();
3114 }
3115 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003116 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117
3118 standbyTime = systemTime() + kStandbyTimeInNsecs;
3119 for (size_t i = 0; i < outputTracks.size(); i++) {
3120 outputTracks[i]->write(mMixBuffer, writeFrames);
3121 }
3122 mStandby = false;
3123 mBytesWritten += mixBufferSize;
3124 } else {
3125 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003126 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003127 usleep(sleepTime);
3128 }
3129
3130 // finally let go of all our tracks, without the lock held
3131 // since we can't guarantee the destructors won't acquire that
3132 // same lock.
3133 tracksToRemove.clear();
3134 outputTracks.clear();
3135
3136 // Effect chains will be actually deleted here if they were removed from
3137 // mEffectChains list during mixing or effects processing
3138 effectChains.clear();
3139 }
3140
Eric Laurentfeb0db62011-07-22 09:04:31 -07003141 releaseWakeLock();
3142
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 return false;
3144}
3145
3146void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3147{
3148 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3149 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3150 this,
3151 mSampleRate,
3152 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003153 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003154 frameCount);
3155 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003156 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003158 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 updateWaitTime();
3160 }
3161}
3162
3163void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3164{
3165 Mutex::Autolock _l(mLock);
3166 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3167 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3168 mOutputTracks[i]->destroy();
3169 mOutputTracks.removeAt(i);
3170 updateWaitTime();
3171 return;
3172 }
3173 }
Steve Block3856b092011-10-20 11:56:00 +01003174 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003175}
3176
3177void AudioFlinger::DuplicatingThread::updateWaitTime()
3178{
3179 mWaitTimeMs = UINT_MAX;
3180 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3181 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003182 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3184 if (waitTimeMs < mWaitTimeMs) {
3185 mWaitTimeMs = waitTimeMs;
3186 }
3187 }
3188 }
3189}
3190
3191
3192bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3193{
3194 for (size_t i = 0; i < outputTracks.size(); i++) {
3195 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3196 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003197 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003198 return false;
3199 }
3200 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3201 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003202 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203 return false;
3204 }
3205 }
3206 return true;
3207}
3208
3209uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3210{
3211 return (mWaitTimeMs * 1000) / 2;
3212}
3213
3214// ----------------------------------------------------------------------------
3215
3216// TrackBase constructor must be called with AudioFlinger::mLock held
3217AudioFlinger::ThreadBase::TrackBase::TrackBase(
3218 const wp<ThreadBase>& thread,
3219 const sp<Client>& client,
3220 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003221 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003222 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 int frameCount,
3224 uint32_t flags,
3225 const sp<IMemory>& sharedBuffer,
3226 int sessionId)
3227 : RefBase(),
3228 mThread(thread),
3229 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003230 mCblk(NULL),
3231 // mBuffer
3232 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003233 mFrameCount(0),
3234 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 mFormat(format),
3236 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3237 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003238 // mChannelCount
3239 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003240{
Steve Block3856b092011-10-20 11:56:00 +01003241 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242
Steve Blockb8a80522011-12-20 16:23:08 +00003243 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003245 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3247 if (sharedBuffer == 0) {
3248 size += bufferSize;
3249 }
3250
3251 if (client != NULL) {
3252 mCblkMemory = client->heap()->allocate(size);
3253 if (mCblkMemory != 0) {
3254 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003255 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003256 new(mCblk) audio_track_cblk_t();
3257 // clear all buffers
3258 mCblk->frameCount = frameCount;
3259 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003260 mChannelCount = channelCount;
3261 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262 if (sharedBuffer == 0) {
3263 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3264 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3265 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003266 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 mCblk->flags = CBLK_UNDERRUN_ON;
3268 } else {
3269 mBuffer = sharedBuffer->pointer();
3270 }
3271 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3272 }
3273 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003274 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 client->heap()->dump("AudioTrack");
3276 return;
3277 }
3278 } else {
3279 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003280 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 new(mCblk) audio_track_cblk_t();
3282 // clear all buffers
3283 mCblk->frameCount = frameCount;
3284 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003285 mChannelCount = channelCount;
3286 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3288 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3289 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003290 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003291 mCblk->flags = CBLK_UNDERRUN_ON;
3292 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 }
3294}
3295
3296AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3297{
Glenn Kastena0d68332012-01-27 16:47:15 -08003298 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003299 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003300 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003301 } else {
3302 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003303 }
3304 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003305 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003306 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003307 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003309 // If the client's reference count drops to zero, the associated destructor
3310 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3311 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 mClient.clear();
3313 }
3314}
3315
3316void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3317{
Glenn Kastene0feee32011-12-13 11:53:26 -08003318 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 mFrameCount = buffer->frameCount;
3320 step();
3321 buffer->frameCount = 0;
3322}
3323
3324bool AudioFlinger::ThreadBase::TrackBase::step() {
3325 bool result;
3326 audio_track_cblk_t* cblk = this->cblk();
3327
3328 result = cblk->stepServer(mFrameCount);
3329 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003330 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003331 mFlags |= STEPSERVER_FAILED;
3332 }
3333 return result;
3334}
3335
3336void AudioFlinger::ThreadBase::TrackBase::reset() {
3337 audio_track_cblk_t* cblk = this->cblk();
3338
3339 cblk->user = 0;
3340 cblk->server = 0;
3341 cblk->userBase = 0;
3342 cblk->serverBase = 0;
3343 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003344 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345}
3346
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3348 return (int)mCblk->sampleRate;
3349}
3350
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3352 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003353 size_t frameSize = cblk->frameSize;
3354 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3355 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356
3357 // Check validity of returned pointer in case the track control block would have been corrupted.
3358 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003359 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003360 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 -07003361 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003363 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003364 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 }
3366
3367 return bufferStart;
3368}
3369
3370// ----------------------------------------------------------------------------
3371
3372// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3373AudioFlinger::PlaybackThread::Track::Track(
3374 const wp<ThreadBase>& thread,
3375 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003376 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003378 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003379 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 int frameCount,
3381 const sp<IMemory>& sharedBuffer,
3382 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003383 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003384 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3385 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386{
3387 if (mCblk != NULL) {
3388 sp<ThreadBase> baseThread = thread.promote();
3389 if (baseThread != 0) {
3390 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3391 mName = playbackThread->getTrackName_l();
3392 mMainBuffer = playbackThread->mixBuffer();
3393 }
Steve Block3856b092011-10-20 11:56:00 +01003394 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003395 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003396 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 mStreamType = streamType;
3399 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3400 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003401 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 }
3403}
3404
3405AudioFlinger::PlaybackThread::Track::~Track()
3406{
Steve Block3856b092011-10-20 11:56:00 +01003407 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003408 sp<ThreadBase> thread = mThread.promote();
3409 if (thread != 0) {
3410 Mutex::Autolock _l(thread->mLock);
3411 mState = TERMINATED;
3412 }
3413}
3414
3415void AudioFlinger::PlaybackThread::Track::destroy()
3416{
3417 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3418 // by removing it from mTracks vector, so there is a risk that this Tracks's
3419 // desctructor is called. As the destructor needs to lock mLock,
3420 // we must acquire a strong reference on this Track before locking mLock
3421 // here so that the destructor is called only when exiting this function.
3422 // On the other hand, as long as Track::destroy() is only called by
3423 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3424 // this Track with its member mTrack.
3425 sp<Track> keep(this);
3426 { // scope for mLock
3427 sp<ThreadBase> thread = mThread.promote();
3428 if (thread != 0) {
3429 if (!isOutputTrack()) {
3430 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003431 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003432 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003433 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003434
3435 // to track the speaker usage
3436 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 }
3438 AudioSystem::releaseOutput(thread->id());
3439 }
3440 Mutex::Autolock _l(thread->mLock);
3441 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3442 playbackThread->destroyTrack_l(this);
3443 }
3444 }
3445}
3446
3447void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3448{
Glenn Kasten83d86532012-01-17 14:39:34 -08003449 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003450 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 -07003451 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003452 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003453 mStreamType,
3454 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003455 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 mSessionId,
3457 mFrameCount,
3458 mState,
3459 mMute,
3460 mFillingUpStatus,
3461 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003462 vlr & 0xFFFF,
3463 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 mCblk->server,
3465 mCblk->user,
3466 (int)mMainBuffer,
3467 (int)mAuxBuffer);
3468}
3469
3470status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3471{
3472 audio_track_cblk_t* cblk = this->cblk();
3473 uint32_t framesReady;
3474 uint32_t framesReq = buffer->frameCount;
3475
3476 // Check if last stepServer failed, try to step now
3477 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3478 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003479 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3481 }
3482
3483 framesReady = cblk->framesReady();
3484
Glenn Kastenf6b16782011-12-15 09:51:17 -08003485 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486 uint32_t s = cblk->server;
3487 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3488
3489 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3490 if (framesReq > framesReady) {
3491 framesReq = framesReady;
3492 }
3493 if (s + framesReq > bufferEnd) {
3494 framesReq = bufferEnd - s;
3495 }
3496
3497 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003498 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499
3500 buffer->frameCount = framesReq;
3501 return NO_ERROR;
3502 }
3503
3504getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003505 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003507 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003508 return NOT_ENOUGH_DATA;
3509}
3510
3511bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003512 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513
3514 if (mCblk->framesReady() >= mCblk->frameCount ||
3515 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3516 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003517 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518 return true;
3519 }
3520 return false;
3521}
3522
3523status_t AudioFlinger::PlaybackThread::Track::start()
3524{
3525 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003526 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003527 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003528 sp<ThreadBase> thread = mThread.promote();
3529 if (thread != 0) {
3530 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003531 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532 // here the track could be either new, or restarted
3533 // in both cases "unstop" the track
3534 if (mState == PAUSED) {
3535 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003536 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537 } else {
3538 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003539 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003540 }
3541
3542 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3543 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003544 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003545 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003546 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003548
3549 // to track the speaker usage
3550 if (status == NO_ERROR) {
3551 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 }
3554 if (status == NO_ERROR) {
3555 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3556 playbackThread->addTrack_l(this);
3557 } else {
3558 mState = state;
3559 }
3560 } else {
3561 status = BAD_VALUE;
3562 }
3563 return status;
3564}
3565
3566void AudioFlinger::PlaybackThread::Track::stop()
3567{
Steve Block3856b092011-10-20 11:56:00 +01003568 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 sp<ThreadBase> thread = mThread.promote();
3570 if (thread != 0) {
3571 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003572 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 if (mState > STOPPED) {
3574 mState = STOPPED;
3575 // If the track is not active (PAUSED and buffers full), flush buffers
3576 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3577 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3578 reset();
3579 }
Steve Block3856b092011-10-20 11:56:00 +01003580 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 }
3582 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3583 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003584 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003585 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003586 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003587 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003588
3589 // to track the speaker usage
3590 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 }
3592 }
3593}
3594
3595void AudioFlinger::PlaybackThread::Track::pause()
3596{
Steve Block3856b092011-10-20 11:56:00 +01003597 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 sp<ThreadBase> thread = mThread.promote();
3599 if (thread != 0) {
3600 Mutex::Autolock _l(thread->mLock);
3601 if (mState == ACTIVE || mState == RESUMING) {
3602 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003603 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 if (!isOutputTrack()) {
3605 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003606 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003607 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003608 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003609 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003610
3611 // to track the speaker usage
3612 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003613 }
3614 }
3615 }
3616}
3617
3618void AudioFlinger::PlaybackThread::Track::flush()
3619{
Steve Block3856b092011-10-20 11:56:00 +01003620 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003621 sp<ThreadBase> thread = mThread.promote();
3622 if (thread != 0) {
3623 Mutex::Autolock _l(thread->mLock);
3624 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3625 return;
3626 }
3627 // No point remaining in PAUSED state after a flush => go to
3628 // STOPPED state
3629 mState = STOPPED;
3630
Eric Laurent38ccae22011-03-28 18:37:07 -07003631 // do not reset the track if it is still in the process of being stopped or paused.
3632 // this will be done by prepareTracks_l() when the track is stopped.
3633 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3634 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3635 reset();
3636 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003637 }
3638}
3639
3640void AudioFlinger::PlaybackThread::Track::reset()
3641{
3642 // Do not reset twice to avoid discarding data written just after a flush and before
3643 // the audioflinger thread detects the track is stopped.
3644 if (!mResetDone) {
3645 TrackBase::reset();
3646 // Force underrun condition to avoid false underrun callback until first data is
3647 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003648 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3649 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003650 mFillingUpStatus = FS_FILLING;
3651 mResetDone = true;
3652 }
3653}
3654
3655void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3656{
3657 mMute = muted;
3658}
3659
Mathias Agopian65ab4712010-07-14 17:59:35 -07003660status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3661{
3662 status_t status = DEAD_OBJECT;
3663 sp<ThreadBase> thread = mThread.promote();
3664 if (thread != 0) {
3665 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3666 status = playbackThread->attachAuxEffect(this, EffectId);
3667 }
3668 return status;
3669}
3670
3671void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3672{
3673 mAuxEffectId = EffectId;
3674 mAuxBuffer = buffer;
3675}
3676
3677// ----------------------------------------------------------------------------
3678
3679// RecordTrack constructor must be called with AudioFlinger::mLock held
3680AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3681 const wp<ThreadBase>& thread,
3682 const sp<Client>& client,
3683 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003684 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003685 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686 int frameCount,
3687 uint32_t flags,
3688 int sessionId)
3689 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003690 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003691 mOverflow(false)
3692{
3693 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003694 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003695 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003696 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003697 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003698 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003699 } else {
3700 mCblk->frameSize = sizeof(int8_t);
3701 }
3702 }
3703}
3704
3705AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3706{
3707 sp<ThreadBase> thread = mThread.promote();
3708 if (thread != 0) {
3709 AudioSystem::releaseInput(thread->id());
3710 }
3711}
3712
3713status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3714{
3715 audio_track_cblk_t* cblk = this->cblk();
3716 uint32_t framesAvail;
3717 uint32_t framesReq = buffer->frameCount;
3718
3719 // Check if last stepServer failed, try to step now
3720 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3721 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003722 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3724 }
3725
3726 framesAvail = cblk->framesAvailable_l();
3727
Glenn Kastenf6b16782011-12-15 09:51:17 -08003728 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003729 uint32_t s = cblk->server;
3730 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3731
3732 if (framesReq > framesAvail) {
3733 framesReq = framesAvail;
3734 }
3735 if (s + framesReq > bufferEnd) {
3736 framesReq = bufferEnd - s;
3737 }
3738
3739 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003740 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741
3742 buffer->frameCount = framesReq;
3743 return NO_ERROR;
3744 }
3745
3746getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003747 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748 buffer->frameCount = 0;
3749 return NOT_ENOUGH_DATA;
3750}
3751
3752status_t AudioFlinger::RecordThread::RecordTrack::start()
3753{
3754 sp<ThreadBase> thread = mThread.promote();
3755 if (thread != 0) {
3756 RecordThread *recordThread = (RecordThread *)thread.get();
3757 return recordThread->start(this);
3758 } else {
3759 return BAD_VALUE;
3760 }
3761}
3762
3763void AudioFlinger::RecordThread::RecordTrack::stop()
3764{
3765 sp<ThreadBase> thread = mThread.promote();
3766 if (thread != 0) {
3767 RecordThread *recordThread = (RecordThread *)thread.get();
3768 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003769 TrackBase::reset();
3770 // Force overerrun condition to avoid false overrun callback until first data is
3771 // read from buffer
3772 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773 }
3774}
3775
3776void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3777{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003778 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003779 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003781 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782 mSessionId,
3783 mFrameCount,
3784 mState,
3785 mCblk->sampleRate,
3786 mCblk->server,
3787 mCblk->user);
3788}
3789
3790
3791// ----------------------------------------------------------------------------
3792
3793AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3794 const wp<ThreadBase>& thread,
3795 DuplicatingThread *sourceThread,
3796 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003797 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003798 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003799 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003800 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003801 mActive(false), mSourceThread(sourceThread)
3802{
3803
3804 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3805 if (mCblk != NULL) {
3806 mCblk->flags |= CBLK_DIRECTION_OUT;
3807 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 mOutBuffer.frameCount = 0;
3809 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003810 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003811 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3812 mCblk, mBuffer, mCblk->buffers,
3813 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003815 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816 }
3817}
3818
3819AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3820{
3821 clearBufferQueue();
3822}
3823
3824status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3825{
3826 status_t status = Track::start();
3827 if (status != NO_ERROR) {
3828 return status;
3829 }
3830
3831 mActive = true;
3832 mRetryCount = 127;
3833 return status;
3834}
3835
3836void AudioFlinger::PlaybackThread::OutputTrack::stop()
3837{
3838 Track::stop();
3839 clearBufferQueue();
3840 mOutBuffer.frameCount = 0;
3841 mActive = false;
3842}
3843
3844bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3845{
3846 Buffer *pInBuffer;
3847 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003848 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003849 bool outputBufferFull = false;
3850 inBuffer.frameCount = frames;
3851 inBuffer.i16 = data;
3852
3853 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3854
3855 if (!mActive && frames != 0) {
3856 start();
3857 sp<ThreadBase> thread = mThread.promote();
3858 if (thread != 0) {
3859 MixerThread *mixerThread = (MixerThread *)thread.get();
3860 if (mCblk->frameCount > frames){
3861 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3862 uint32_t startFrames = (mCblk->frameCount - frames);
3863 pInBuffer = new Buffer;
3864 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3865 pInBuffer->frameCount = startFrames;
3866 pInBuffer->i16 = pInBuffer->mBuffer;
3867 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3868 mBufferQueue.add(pInBuffer);
3869 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003870 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003871 }
3872 }
3873 }
3874 }
3875
3876 while (waitTimeLeftMs) {
3877 // First write pending buffers, then new data
3878 if (mBufferQueue.size()) {
3879 pInBuffer = mBufferQueue.itemAt(0);
3880 } else {
3881 pInBuffer = &inBuffer;
3882 }
3883
3884 if (pInBuffer->frameCount == 0) {
3885 break;
3886 }
3887
3888 if (mOutBuffer.frameCount == 0) {
3889 mOutBuffer.frameCount = pInBuffer->frameCount;
3890 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003891 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003892 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003893 outputBufferFull = true;
3894 break;
3895 }
3896 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3897 if (waitTimeLeftMs >= waitTimeMs) {
3898 waitTimeLeftMs -= waitTimeMs;
3899 } else {
3900 waitTimeLeftMs = 0;
3901 }
3902 }
3903
3904 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3905 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3906 mCblk->stepUser(outFrames);
3907 pInBuffer->frameCount -= outFrames;
3908 pInBuffer->i16 += outFrames * channelCount;
3909 mOutBuffer.frameCount -= outFrames;
3910 mOutBuffer.i16 += outFrames * channelCount;
3911
3912 if (pInBuffer->frameCount == 0) {
3913 if (mBufferQueue.size()) {
3914 mBufferQueue.removeAt(0);
3915 delete [] pInBuffer->mBuffer;
3916 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003917 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918 } else {
3919 break;
3920 }
3921 }
3922 }
3923
3924 // If we could not write all frames, allocate a buffer and queue it for next time.
3925 if (inBuffer.frameCount) {
3926 sp<ThreadBase> thread = mThread.promote();
3927 if (thread != 0 && !thread->standby()) {
3928 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3929 pInBuffer = new Buffer;
3930 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3931 pInBuffer->frameCount = inBuffer.frameCount;
3932 pInBuffer->i16 = pInBuffer->mBuffer;
3933 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3934 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003935 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003937 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003938 }
3939 }
3940 }
3941
3942 // Calling write() with a 0 length buffer, means that no more data will be written:
3943 // If no more buffers are pending, fill output track buffer to make sure it is started
3944 // by output mixer.
3945 if (frames == 0 && mBufferQueue.size() == 0) {
3946 if (mCblk->user < mCblk->frameCount) {
3947 frames = mCblk->frameCount - mCblk->user;
3948 pInBuffer = new Buffer;
3949 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3950 pInBuffer->frameCount = frames;
3951 pInBuffer->i16 = pInBuffer->mBuffer;
3952 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3953 mBufferQueue.add(pInBuffer);
3954 } else if (mActive) {
3955 stop();
3956 }
3957 }
3958
3959 return outputBufferFull;
3960}
3961
3962status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3963{
3964 int active;
3965 status_t result;
3966 audio_track_cblk_t* cblk = mCblk;
3967 uint32_t framesReq = buffer->frameCount;
3968
Steve Block3856b092011-10-20 11:56:00 +01003969// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003970 buffer->frameCount = 0;
3971
3972 uint32_t framesAvail = cblk->framesAvailable();
3973
3974
3975 if (framesAvail == 0) {
3976 Mutex::Autolock _l(cblk->lock);
3977 goto start_loop_here;
3978 while (framesAvail == 0) {
3979 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003980 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003981 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003982 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 }
3984 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3985 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003986 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003987 }
3988 // read the server count again
3989 start_loop_here:
3990 framesAvail = cblk->framesAvailable_l();
3991 }
3992 }
3993
3994// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003995// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003996// }
3997
3998 if (framesReq > framesAvail) {
3999 framesReq = framesAvail;
4000 }
4001
4002 uint32_t u = cblk->user;
4003 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4004
4005 if (u + framesReq > bufferEnd) {
4006 framesReq = bufferEnd - u;
4007 }
4008
4009 buffer->frameCount = framesReq;
4010 buffer->raw = (void *)cblk->buffer(u);
4011 return NO_ERROR;
4012}
4013
4014
4015void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4016{
4017 size_t size = mBufferQueue.size();
4018 Buffer *pBuffer;
4019
4020 for (size_t i = 0; i < size; i++) {
4021 pBuffer = mBufferQueue.itemAt(i);
4022 delete [] pBuffer->mBuffer;
4023 delete pBuffer;
4024 }
4025 mBufferQueue.clear();
4026}
4027
4028// ----------------------------------------------------------------------------
4029
4030AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4031 : RefBase(),
4032 mAudioFlinger(audioFlinger),
4033 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4034 mPid(pid)
4035{
4036 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4037}
4038
4039// Client destructor must be called with AudioFlinger::mLock held
4040AudioFlinger::Client::~Client()
4041{
4042 mAudioFlinger->removeClient_l(mPid);
4043}
4044
Glenn Kasten435dbe62012-01-30 10:15:48 -08004045sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046{
4047 return mMemoryDealer;
4048}
4049
4050// ----------------------------------------------------------------------------
4051
4052AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4053 const sp<IAudioFlingerClient>& client,
4054 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004055 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056{
4057}
4058
4059AudioFlinger::NotificationClient::~NotificationClient()
4060{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061}
4062
4063void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4064{
4065 sp<NotificationClient> keep(this);
4066 {
4067 mAudioFlinger->removeNotificationClient(mPid);
4068 }
4069}
4070
4071// ----------------------------------------------------------------------------
4072
4073AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4074 : BnAudioTrack(),
4075 mTrack(track)
4076{
4077}
4078
4079AudioFlinger::TrackHandle::~TrackHandle() {
4080 // just stop the track on deletion, associated resources
4081 // will be freed from the main thread once all pending buffers have
4082 // been played. Unless it's not in the active track list, in which
4083 // case we free everything now...
4084 mTrack->destroy();
4085}
4086
Glenn Kasten90716c52012-01-26 13:40:12 -08004087sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4088 return mTrack->getCblk();
4089}
4090
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091status_t AudioFlinger::TrackHandle::start() {
4092 return mTrack->start();
4093}
4094
4095void AudioFlinger::TrackHandle::stop() {
4096 mTrack->stop();
4097}
4098
4099void AudioFlinger::TrackHandle::flush() {
4100 mTrack->flush();
4101}
4102
4103void AudioFlinger::TrackHandle::mute(bool e) {
4104 mTrack->mute(e);
4105}
4106
4107void AudioFlinger::TrackHandle::pause() {
4108 mTrack->pause();
4109}
4110
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4112{
4113 return mTrack->attachAuxEffect(EffectId);
4114}
4115
4116status_t AudioFlinger::TrackHandle::onTransact(
4117 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4118{
4119 return BnAudioTrack::onTransact(code, data, reply, flags);
4120}
4121
4122// ----------------------------------------------------------------------------
4123
4124sp<IAudioRecord> AudioFlinger::openRecord(
4125 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004126 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004127 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004128 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004129 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004130 int frameCount,
4131 uint32_t flags,
4132 int *sessionId,
4133 status_t *status)
4134{
4135 sp<RecordThread::RecordTrack> recordTrack;
4136 sp<RecordHandle> recordHandle;
4137 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 status_t lStatus;
4139 RecordThread *thread;
4140 size_t inFrameCount;
4141 int lSessionId;
4142
4143 // check calling permissions
4144 if (!recordingAllowed()) {
4145 lStatus = PERMISSION_DENIED;
4146 goto Exit;
4147 }
4148
4149 // add client to list
4150 { // scope for mLock
4151 Mutex::Autolock _l(mLock);
4152 thread = checkRecordThread_l(input);
4153 if (thread == NULL) {
4154 lStatus = BAD_VALUE;
4155 goto Exit;
4156 }
4157
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004158 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159
4160 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004161 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 lSessionId = *sessionId;
4163 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004164 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004165 if (sessionId != NULL) {
4166 *sessionId = lSessionId;
4167 }
4168 }
4169 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004170 recordTrack = thread->createRecordTrack_l(client,
4171 sampleRate,
4172 format,
4173 channelMask,
4174 frameCount,
4175 flags,
4176 lSessionId,
4177 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004179 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4181 // destructor is called by the TrackBase destructor with mLock held
4182 client.clear();
4183 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 goto Exit;
4185 }
4186
4187 // return to handle to client
4188 recordHandle = new RecordHandle(recordTrack);
4189 lStatus = NO_ERROR;
4190
4191Exit:
4192 if (status) {
4193 *status = lStatus;
4194 }
4195 return recordHandle;
4196}
4197
4198// ----------------------------------------------------------------------------
4199
4200AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4201 : BnAudioRecord(),
4202 mRecordTrack(recordTrack)
4203{
4204}
4205
4206AudioFlinger::RecordHandle::~RecordHandle() {
4207 stop();
4208}
4209
Glenn Kasten90716c52012-01-26 13:40:12 -08004210sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4211 return mRecordTrack->getCblk();
4212}
4213
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004215 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 return mRecordTrack->start();
4217}
4218
4219void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004220 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221 mRecordTrack->stop();
4222}
4223
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224status_t AudioFlinger::RecordHandle::onTransact(
4225 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4226{
4227 return BnAudioRecord::onTransact(code, data, reply, flags);
4228}
4229
4230// ----------------------------------------------------------------------------
4231
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004232AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4233 AudioStreamIn *input,
4234 uint32_t sampleRate,
4235 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004236 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004237 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004238 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004239 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4240 // mRsmpInIndex and mInputBytes set by readInputParameters()
4241 mReqChannelCount(popcount(channels)),
4242 mReqSampleRate(sampleRate)
4243 // mBytesRead is only meaningful while active, and so is cleared in start()
4244 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004246 snprintf(mName, kNameLength, "AudioIn_%d", id);
4247
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248 readInputParameters();
4249}
4250
4251
4252AudioFlinger::RecordThread::~RecordThread()
4253{
4254 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004255 delete mResampler;
4256 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257}
4258
4259void AudioFlinger::RecordThread::onFirstRef()
4260{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004261 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262}
4263
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004264status_t AudioFlinger::RecordThread::readyToRun()
4265{
4266 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004267 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004268 return status;
4269}
4270
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271bool AudioFlinger::RecordThread::threadLoop()
4272{
4273 AudioBufferProvider::Buffer buffer;
4274 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004275 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276
Eric Laurent44d98482010-09-30 16:12:31 -07004277 nsecs_t lastWarning = 0;
4278
Eric Laurentfeb0db62011-07-22 09:04:31 -07004279 acquireWakeLock();
4280
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 // start recording
4282 while (!exitPending()) {
4283
4284 processConfigEvents();
4285
4286 { // scope for mLock
4287 Mutex::Autolock _l(mLock);
4288 checkForNewParameters_l();
4289 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4290 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004291 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 mStandby = true;
4293 }
4294
4295 if (exitPending()) break;
4296
Eric Laurentfeb0db62011-07-22 09:04:31 -07004297 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004298 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004299 // go to sleep
4300 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004301 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004302 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 continue;
4304 }
4305 if (mActiveTrack != 0) {
4306 if (mActiveTrack->mState == TrackBase::PAUSING) {
4307 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004308 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 mStandby = true;
4310 }
4311 mActiveTrack.clear();
4312 mStartStopCond.broadcast();
4313 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4314 if (mReqChannelCount != mActiveTrack->channelCount()) {
4315 mActiveTrack.clear();
4316 mStartStopCond.broadcast();
4317 } else if (mBytesRead != 0) {
4318 // record start succeeds only if first read from audio input
4319 // succeeds
4320 if (mBytesRead > 0) {
4321 mActiveTrack->mState = TrackBase::ACTIVE;
4322 } else {
4323 mActiveTrack.clear();
4324 }
4325 mStartStopCond.broadcast();
4326 }
4327 mStandby = false;
4328 }
4329 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004330 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 }
4332
4333 if (mActiveTrack != 0) {
4334 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4335 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004336 unlockEffectChains(effectChains);
4337 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004338 continue;
4339 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004340 for (size_t i = 0; i < effectChains.size(); i ++) {
4341 effectChains[i]->process_l();
4342 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004343
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004345 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004346 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004347 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 // no resampling
4349 while (framesOut) {
4350 size_t framesIn = mFrameCount - mRsmpInIndex;
4351 if (framesIn) {
4352 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4353 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4354 if (framesIn > framesOut)
4355 framesIn = framesOut;
4356 mRsmpInIndex += framesIn;
4357 framesOut -= framesIn;
4358 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004359 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 memcpy(dst, src, framesIn * mFrameSize);
4361 } else {
4362 int16_t *src16 = (int16_t *)src;
4363 int16_t *dst16 = (int16_t *)dst;
4364 if (mChannelCount == 1) {
4365 while (framesIn--) {
4366 *dst16++ = *src16;
4367 *dst16++ = *src16++;
4368 }
4369 } else {
4370 while (framesIn--) {
4371 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4372 src16 += 2;
4373 }
4374 }
4375 }
4376 }
4377 if (framesOut && mFrameCount == mRsmpInIndex) {
4378 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004379 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004380 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 framesOut = 0;
4382 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004383 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 mRsmpInIndex = 0;
4385 }
4386 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004387 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4389 // Force input into standby so that it tries to
4390 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004391 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004392 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004393 }
4394 mRsmpInIndex = mFrameCount;
4395 framesOut = 0;
4396 buffer.frameCount = 0;
4397 }
4398 }
4399 }
4400 } else {
4401 // resampling
4402
4403 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4404 // alter output frame count as if we were expecting stereo samples
4405 if (mChannelCount == 1 && mReqChannelCount == 1) {
4406 framesOut >>= 1;
4407 }
4408 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4409 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4410 // are 32 bit aligned which should be always true.
4411 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004412 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 // the resampler always outputs stereo samples: do post stereo to mono conversion
4414 int16_t *src = (int16_t *)mRsmpOutBuffer;
4415 int16_t *dst = buffer.i16;
4416 while (framesOut--) {
4417 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4418 src += 2;
4419 }
4420 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004421 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423
4424 }
4425 mActiveTrack->releaseBuffer(&buffer);
4426 mActiveTrack->overflow();
4427 }
4428 // client isn't retrieving buffers fast enough
4429 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004430 if (!mActiveTrack->setOverflow()) {
4431 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004432 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004433 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004434 lastWarning = now;
4435 }
4436 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 // Release the processor for a while before asking for a new buffer.
4438 // This will give the application more chance to read from the buffer and
4439 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004440 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441 }
4442 }
Eric Laurentec437d82011-07-26 20:54:46 -07004443 // enable changes in effect chain
4444 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004445 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004446 }
4447
4448 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004449 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004450 }
4451 mActiveTrack.clear();
4452
4453 mStartStopCond.broadcast();
4454
Eric Laurentfeb0db62011-07-22 09:04:31 -07004455 releaseWakeLock();
4456
Steve Block3856b092011-10-20 11:56:00 +01004457 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 return false;
4459}
4460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004461
4462sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4463 const sp<AudioFlinger::Client>& client,
4464 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004465 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004466 int channelMask,
4467 int frameCount,
4468 uint32_t flags,
4469 int sessionId,
4470 status_t *status)
4471{
4472 sp<RecordTrack> track;
4473 status_t lStatus;
4474
4475 lStatus = initCheck();
4476 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004477 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004478 goto Exit;
4479 }
4480
4481 { // scope for mLock
4482 Mutex::Autolock _l(mLock);
4483
4484 track = new RecordTrack(this, client, sampleRate,
4485 format, channelMask, frameCount, flags, sessionId);
4486
Glenn Kasten7378ca52012-01-20 13:44:40 -08004487 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004488 lStatus = NO_MEMORY;
4489 goto Exit;
4490 }
4491
4492 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004493 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4494 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004495 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004496 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4497 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004498 }
4499 lStatus = NO_ERROR;
4500
4501Exit:
4502 if (status) {
4503 *status = lStatus;
4504 }
4505 return track;
4506}
4507
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4509{
Steve Block3856b092011-10-20 11:56:00 +01004510 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511 sp <ThreadBase> strongMe = this;
4512 status_t status = NO_ERROR;
4513 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004514 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 if (mActiveTrack != 0) {
4516 if (recordTrack != mActiveTrack.get()) {
4517 status = -EBUSY;
4518 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4519 mActiveTrack->mState = TrackBase::ACTIVE;
4520 }
4521 return status;
4522 }
4523
4524 recordTrack->mState = TrackBase::IDLE;
4525 mActiveTrack = recordTrack;
4526 mLock.unlock();
4527 status_t status = AudioSystem::startInput(mId);
4528 mLock.lock();
4529 if (status != NO_ERROR) {
4530 mActiveTrack.clear();
4531 return status;
4532 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 mRsmpInIndex = mFrameCount;
4534 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004535 if (mResampler != NULL) {
4536 mResampler->reset();
4537 }
4538 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004540 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004541 mWaitWorkCV.signal();
4542 // do not wait for mStartStopCond if exiting
4543 if (mExiting) {
4544 mActiveTrack.clear();
4545 status = INVALID_OPERATION;
4546 goto startError;
4547 }
4548 mStartStopCond.wait(mLock);
4549 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 status = BAD_VALUE;
4552 goto startError;
4553 }
Steve Block3856b092011-10-20 11:56:00 +01004554 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555 return status;
4556 }
4557startError:
4558 AudioSystem::stopInput(mId);
4559 return status;
4560}
4561
4562void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004563 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 sp <ThreadBase> strongMe = this;
4565 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004566 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4568 mActiveTrack->mState = TrackBase::PAUSING;
4569 // do not wait for mStartStopCond if exiting
4570 if (mExiting) {
4571 return;
4572 }
4573 mStartStopCond.wait(mLock);
4574 // if we have been restarted, recordTrack == mActiveTrack.get() here
4575 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4576 mLock.unlock();
4577 AudioSystem::stopInput(mId);
4578 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004579 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 }
4581 }
4582 }
4583}
4584
4585status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4586{
4587 const size_t SIZE = 256;
4588 char buffer[SIZE];
4589 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004590
4591 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4592 result.append(buffer);
4593
4594 if (mActiveTrack != 0) {
4595 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004596 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 mActiveTrack->dump(buffer, SIZE);
4598 result.append(buffer);
4599
4600 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4601 result.append(buffer);
4602 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4603 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004604 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004605 result.append(buffer);
4606 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4607 result.append(buffer);
4608 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4609 result.append(buffer);
4610
4611
4612 } else {
4613 result.append("No record client\n");
4614 }
4615 write(fd, result.string(), result.size());
4616
4617 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004618 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619
4620 return NO_ERROR;
4621}
4622
4623status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4624{
4625 size_t framesReq = buffer->frameCount;
4626 size_t framesReady = mFrameCount - mRsmpInIndex;
4627 int channelCount;
4628
4629 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004630 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004632 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4634 // Force input into standby so that it tries to
4635 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004636 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004637 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004638 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004639 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640 buffer->frameCount = 0;
4641 return NOT_ENOUGH_DATA;
4642 }
4643 mRsmpInIndex = 0;
4644 framesReady = mFrameCount;
4645 }
4646
4647 if (framesReq > framesReady) {
4648 framesReq = framesReady;
4649 }
4650
4651 if (mChannelCount == 1 && mReqChannelCount == 2) {
4652 channelCount = 1;
4653 } else {
4654 channelCount = 2;
4655 }
4656 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4657 buffer->frameCount = framesReq;
4658 return NO_ERROR;
4659}
4660
4661void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4662{
4663 mRsmpInIndex += buffer->frameCount;
4664 buffer->frameCount = 0;
4665}
4666
4667bool AudioFlinger::RecordThread::checkForNewParameters_l()
4668{
4669 bool reconfig = false;
4670
4671 while (!mNewParameters.isEmpty()) {
4672 status_t status = NO_ERROR;
4673 String8 keyValuePair = mNewParameters[0];
4674 AudioParameter param = AudioParameter(keyValuePair);
4675 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004676 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 int reqSamplingRate = mReqSampleRate;
4678 int reqChannelCount = mReqChannelCount;
4679
4680 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4681 reqSamplingRate = value;
4682 reconfig = true;
4683 }
4684 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004685 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686 reconfig = true;
4687 }
4688 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004689 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004690 reconfig = true;
4691 }
4692 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4693 // do not accept frame count changes if tracks are open as the track buffer
4694 // size depends on frame count and correct behavior would not be garantied
4695 // if frame count is changed after track creation
4696 if (mActiveTrack != 0) {
4697 status = INVALID_OPERATION;
4698 } else {
4699 reconfig = true;
4700 }
4701 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004702 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4703 // forward device change to effects that have requested to be
4704 // aware of attached audio device.
4705 for (size_t i = 0; i < mEffectChains.size(); i++) {
4706 mEffectChains[i]->setDevice_l(value);
4707 }
4708 // store input device and output device but do not forward output device to audio HAL.
4709 // Note that status is ignored by the caller for output device
4710 // (see AudioFlinger::setParameters()
4711 if (value & AUDIO_DEVICE_OUT_ALL) {
4712 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4713 status = BAD_VALUE;
4714 } else {
4715 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004716 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4717 if (mTrack != NULL) {
4718 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004719 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004720 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4721 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4722 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004723 }
4724 mDevice |= (uint32_t)value;
4725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004726 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004727 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004729 mInput->stream->common.standby(&mInput->stream->common);
4730 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004731 }
4732 if (reconfig) {
4733 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004734 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004735 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004736 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4737 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004738 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739 status = NO_ERROR;
4740 }
4741 if (status == NO_ERROR) {
4742 readInputParameters();
4743 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4744 }
4745 }
4746 }
4747
4748 mNewParameters.removeAt(0);
4749
4750 mParamStatus = status;
4751 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004752 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4753 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004754 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 }
4756 return reconfig;
4757}
4758
4759String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4760{
Dima Zavinfce7a472011-04-19 22:30:36 -07004761 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004762 String8 out_s8 = String8();
4763
4764 Mutex::Autolock _l(mLock);
4765 if (initCheck() != NO_ERROR) {
4766 return out_s8;
4767 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004768
Dima Zavin799a70e2011-04-18 16:57:27 -07004769 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004770 out_s8 = String8(s);
4771 free(s);
4772 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773}
4774
4775void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4776 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004777 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004778
4779 switch (event) {
4780 case AudioSystem::INPUT_OPENED:
4781 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004782 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783 desc.samplingRate = mSampleRate;
4784 desc.format = mFormat;
4785 desc.frameCount = mFrameCount;
4786 desc.latency = 0;
4787 param2 = &desc;
4788 break;
4789
4790 case AudioSystem::INPUT_CLOSED:
4791 default:
4792 break;
4793 }
4794 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4795}
4796
4797void AudioFlinger::RecordThread::readInputParameters()
4798{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004799 delete mRsmpInBuffer;
4800 // mRsmpInBuffer is always assigned a new[] below
4801 delete mRsmpOutBuffer;
4802 mRsmpOutBuffer = NULL;
4803 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004804 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805
Dima Zavin799a70e2011-04-18 16:57:27 -07004806 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004807 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4808 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004809 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004810 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004811 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812 mFrameCount = mInputBytes / mFrameSize;
4813 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4814
4815 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4816 {
4817 int channelCount;
4818 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4819 // stereo to mono post process as the resampler always outputs stereo.
4820 if (mChannelCount == 1 && mReqChannelCount == 2) {
4821 channelCount = 1;
4822 } else {
4823 channelCount = 2;
4824 }
4825 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4826 mResampler->setSampleRate(mSampleRate);
4827 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4828 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4829
4830 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4831 if (mChannelCount == 1 && mReqChannelCount == 1) {
4832 mFrameCount >>= 1;
4833 }
4834
4835 }
4836 mRsmpInIndex = mFrameCount;
4837}
4838
4839unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4840{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004841 Mutex::Autolock _l(mLock);
4842 if (initCheck() != NO_ERROR) {
4843 return 0;
4844 }
4845
Dima Zavin799a70e2011-04-18 16:57:27 -07004846 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004847}
4848
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004849uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4850{
4851 Mutex::Autolock _l(mLock);
4852 uint32_t result = 0;
4853 if (getEffectChain_l(sessionId) != 0) {
4854 result = EFFECT_SESSION;
4855 }
4856
4857 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4858 result |= TRACK_SESSION;
4859 }
4860
4861 return result;
4862}
4863
Eric Laurent59bd0da2011-08-01 09:52:20 -07004864AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4865{
4866 Mutex::Autolock _l(mLock);
4867 return mTrack;
4868}
4869
Glenn Kastenaed850d2012-01-26 09:46:34 -08004870AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004871{
4872 Mutex::Autolock _l(mLock);
4873 return mInput;
4874}
4875
4876AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4877{
4878 Mutex::Autolock _l(mLock);
4879 AudioStreamIn *input = mInput;
4880 mInput = NULL;
4881 return input;
4882}
4883
4884// this method must always be called either with ThreadBase mLock held or inside the thread loop
4885audio_stream_t* AudioFlinger::RecordThread::stream()
4886{
4887 if (mInput == NULL) {
4888 return NULL;
4889 }
4890 return &mInput->stream->common;
4891}
4892
4893
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894// ----------------------------------------------------------------------------
4895
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004896audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004898 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899 uint32_t *pChannels,
4900 uint32_t *pLatencyMs,
4901 uint32_t flags)
4902{
4903 status_t status;
4904 PlaybackThread *thread = NULL;
4905 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4906 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004907 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 uint32_t channels = pChannels ? *pChannels : 0;
4909 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004910 audio_stream_out_t *outStream;
4911 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912
Steve Block3856b092011-10-20 11:56:00 +01004913 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914 pDevices ? *pDevices : 0,
4915 samplingRate,
4916 format,
4917 channels,
4918 flags);
4919
4920 if (pDevices == NULL || *pDevices == 0) {
4921 return 0;
4922 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004923
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924 Mutex::Autolock _l(mLock);
4925
Dima Zavin799a70e2011-04-18 16:57:27 -07004926 outHwDev = findSuitableHwDev_l(*pDevices);
4927 if (outHwDev == NULL)
4928 return 0;
4929
Glenn Kasten58f30212012-01-12 12:27:51 -08004930 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004931 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004932 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004933 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 samplingRate,
4935 format,
4936 channels,
4937 status);
4938
4939 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004940 if (outStream != NULL) {
4941 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004942 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004943
Dima Zavinfce7a472011-04-19 22:30:36 -07004944 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4945 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4946 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004947 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004948 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 } else {
4950 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004951 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952 }
4953 mPlaybackThreads.add(id, thread);
4954
Glenn Kastena0d68332012-01-27 16:47:15 -08004955 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4956 if (pFormat != NULL) *pFormat = format;
4957 if (pChannels != NULL) *pChannels = channels;
4958 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959
4960 // notify client processes of the new output creation
4961 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4962 return id;
4963 }
4964
4965 return 0;
4966}
4967
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004968audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4969 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004970{
4971 Mutex::Autolock _l(mLock);
4972 MixerThread *thread1 = checkMixerThread_l(output1);
4973 MixerThread *thread2 = checkMixerThread_l(output2);
4974
4975 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004976 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 return 0;
4978 }
4979
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004980 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4982 thread->addOutputTrack(thread2);
4983 mPlaybackThreads.add(id, thread);
4984 // notify client processes of the new output creation
4985 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4986 return id;
4987}
4988
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004989status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004990{
4991 // keep strong reference on the playback thread so that
4992 // it is not destroyed while exit() is executed
4993 sp <PlaybackThread> thread;
4994 {
4995 Mutex::Autolock _l(mLock);
4996 thread = checkPlaybackThread_l(output);
4997 if (thread == NULL) {
4998 return BAD_VALUE;
4999 }
5000
Steve Block3856b092011-10-20 11:56:00 +01005001 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005003 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005005 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005006 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5007 dupThread->removeOutputTrack((MixerThread *)thread.get());
5008 }
5009 }
5010 }
Glenn Kastena0d68332012-01-27 16:47:15 -08005011 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005012 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5013 mPlaybackThreads.removeItem(output);
5014 }
5015 thread->exit();
5016
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005017 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005018 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005019 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005020 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005021 out->hwDev->close_output_stream(out->hwDev, out->stream);
5022 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 }
5024 return NO_ERROR;
5025}
5026
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005027status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005028{
5029 Mutex::Autolock _l(mLock);
5030 PlaybackThread *thread = checkPlaybackThread_l(output);
5031
5032 if (thread == NULL) {
5033 return BAD_VALUE;
5034 }
5035
Steve Block3856b092011-10-20 11:56:00 +01005036 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037 thread->suspend();
5038
5039 return NO_ERROR;
5040}
5041
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005042status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043{
5044 Mutex::Autolock _l(mLock);
5045 PlaybackThread *thread = checkPlaybackThread_l(output);
5046
5047 if (thread == NULL) {
5048 return BAD_VALUE;
5049 }
5050
Steve Block3856b092011-10-20 11:56:00 +01005051 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052
5053 thread->restore();
5054
5055 return NO_ERROR;
5056}
5057
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005058audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005059 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005060 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005061 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005062 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005063{
5064 status_t status;
5065 RecordThread *thread = NULL;
5066 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005067 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005068 uint32_t channels = pChannels ? *pChannels : 0;
5069 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005070 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005071 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 audio_stream_in_t *inStream;
5073 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074
5075 if (pDevices == NULL || *pDevices == 0) {
5076 return 0;
5077 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005078
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 Mutex::Autolock _l(mLock);
5080
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 inHwDev = findSuitableHwDev_l(*pDevices);
5082 if (inHwDev == NULL)
5083 return 0;
5084
Glenn Kasten58f30212012-01-12 12:27:51 -08005085 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005086 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005087 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005088 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005089 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005090 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 samplingRate,
5092 format,
5093 channels,
5094 acoustics,
5095 status);
5096
5097 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5098 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5099 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005100 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005101 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005103 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005104 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005105 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005106 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005107 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005108 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 }
5110
Dima Zavin799a70e2011-04-18 16:57:27 -07005111 if (inStream != NULL) {
5112 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5113
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005114 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005115 // Start record thread
5116 // RecorThread require both input and output device indication to forward to audio
5117 // pre processing modules
5118 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5119 thread = new RecordThread(this,
5120 input,
5121 reqSamplingRate,
5122 reqChannels,
5123 id,
5124 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005126 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005127 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5128 if (pFormat != NULL) *pFormat = format;
5129 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005130
Dima Zavin799a70e2011-04-18 16:57:27 -07005131 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005132
5133 // notify client processes of the new input creation
5134 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5135 return id;
5136 }
5137
5138 return 0;
5139}
5140
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005141status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142{
5143 // keep strong reference on the record thread so that
5144 // it is not destroyed while exit() is executed
5145 sp <RecordThread> thread;
5146 {
5147 Mutex::Autolock _l(mLock);
5148 thread = checkRecordThread_l(input);
5149 if (thread == NULL) {
5150 return BAD_VALUE;
5151 }
5152
Steve Block3856b092011-10-20 11:56:00 +01005153 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005154 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5156 mRecordThreads.removeItem(input);
5157 }
5158 thread->exit();
5159
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005160 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005161 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005162 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005163 in->hwDev->close_input_stream(in->hwDev, in->stream);
5164 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165
5166 return NO_ERROR;
5167}
5168
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005169status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170{
5171 Mutex::Autolock _l(mLock);
5172 MixerThread *dstThread = checkMixerThread_l(output);
5173 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005174 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 return BAD_VALUE;
5176 }
5177
Steve Block3856b092011-10-20 11:56:00 +01005178 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005179 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5180
Eric Laurent9f6530f2011-08-30 10:18:54 -07005181 dstThread->setStreamValid(stream, true);
5182
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5184 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5185 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005186 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005187 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005188 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 }
Eric Laurentde070132010-07-13 04:45:46 -07005191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192
5193 return NO_ERROR;
5194}
5195
5196
5197int AudioFlinger::newAudioSessionId()
5198{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005199 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200}
5201
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005202void AudioFlinger::acquireAudioSessionId(int audioSession)
5203{
5204 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005205 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005206 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005207 int num = mAudioSessionRefs.size();
5208 for (int i = 0; i< num; i++) {
5209 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5210 if (ref->sessionid == audioSession && ref->pid == caller) {
5211 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005212 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005213 return;
5214 }
5215 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005216 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5217 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005218}
5219
5220void AudioFlinger::releaseAudioSessionId(int audioSession)
5221{
5222 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005223 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005224 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005225 int num = mAudioSessionRefs.size();
5226 for (int i = 0; i< num; i++) {
5227 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5228 if (ref->sessionid == audioSession && ref->pid == caller) {
5229 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005230 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005231 if (ref->cnt == 0) {
5232 mAudioSessionRefs.removeAt(i);
5233 delete ref;
5234 purgeStaleEffects_l();
5235 }
5236 return;
5237 }
5238 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005239 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005240}
5241
5242void AudioFlinger::purgeStaleEffects_l() {
5243
Steve Block3856b092011-10-20 11:56:00 +01005244 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005245
5246 Vector< sp<EffectChain> > chains;
5247
5248 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5249 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5250 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5251 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005252 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5253 chains.push(ec);
5254 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005255 }
5256 }
5257 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5258 sp<RecordThread> t = mRecordThreads.valueAt(i);
5259 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5260 sp<EffectChain> ec = t->mEffectChains[j];
5261 chains.push(ec);
5262 }
5263 }
5264
5265 for (size_t i = 0; i < chains.size(); i++) {
5266 sp<EffectChain> ec = chains[i];
5267 int sessionid = ec->sessionId();
5268 sp<ThreadBase> t = ec->mThread.promote();
5269 if (t == 0) {
5270 continue;
5271 }
5272 size_t numsessionrefs = mAudioSessionRefs.size();
5273 bool found = false;
5274 for (size_t k = 0; k < numsessionrefs; k++) {
5275 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5276 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005277 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005278 sessionid, ref->pid, ref->cnt);
5279 found = true;
5280 break;
5281 }
5282 }
5283 if (!found) {
5284 // remove all effects from the chain
5285 while (ec->mEffects.size()) {
5286 sp<EffectModule> effect = ec->mEffects[0];
5287 effect->unPin();
5288 Mutex::Autolock _l (t->mLock);
5289 t->removeEffect_l(effect);
5290 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5291 sp<EffectHandle> handle = effect->mHandles[j].promote();
5292 if (handle != 0) {
5293 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005294 if (handle->mHasControl && handle->mEnabled) {
5295 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5296 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005297 }
5298 }
5299 AudioSystem::unregisterEffect(effect->id());
5300 }
5301 }
5302 }
5303 return;
5304}
5305
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005307AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308{
5309 PlaybackThread *thread = NULL;
5310 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5311 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5312 }
5313 return thread;
5314}
5315
5316// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005317AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318{
5319 PlaybackThread *thread = checkPlaybackThread_l(output);
5320 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005321 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 thread = NULL;
5323 }
5324 }
5325 return (MixerThread *)thread;
5326}
5327
5328// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005329AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330{
5331 RecordThread *thread = NULL;
5332 if (mRecordThreads.indexOfKey(input) >= 0) {
5333 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5334 }
5335 return thread;
5336}
5337
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005338uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005340 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005341}
5342
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005343AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5344{
5345 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5346 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005347 AudioStreamOut *output = thread->getOutput();
5348 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005349 return thread;
5350 }
5351 }
5352 return NULL;
5353}
5354
5355uint32_t AudioFlinger::primaryOutputDevice_l()
5356{
5357 PlaybackThread *thread = primaryPlaybackThread_l();
5358
5359 if (thread == NULL) {
5360 return 0;
5361 }
5362
5363 return thread->device();
5364}
5365
5366
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367// ----------------------------------------------------------------------------
5368// Effect management
5369// ----------------------------------------------------------------------------
5370
5371
Glenn Kastenf587ba52012-01-26 16:25:10 -08005372status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005373{
5374 Mutex::Autolock _l(mLock);
5375 return EffectQueryNumberEffects(numEffects);
5376}
5377
Glenn Kastenf587ba52012-01-26 16:25:10 -08005378status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379{
5380 Mutex::Autolock _l(mLock);
5381 return EffectQueryEffect(index, descriptor);
5382}
5383
Glenn Kasten5e92a782012-01-30 07:40:52 -08005384status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005385 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386{
5387 Mutex::Autolock _l(mLock);
5388 return EffectGetDescriptor(pUuid, descriptor);
5389}
5390
5391
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5393 effect_descriptor_t *pDesc,
5394 const sp<IEffectClient>& effectClient,
5395 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005396 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397 int sessionId,
5398 status_t *status,
5399 int *id,
5400 int *enabled)
5401{
5402 status_t lStatus = NO_ERROR;
5403 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005405
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005406 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005407 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408
5409 if (pDesc == NULL) {
5410 lStatus = BAD_VALUE;
5411 goto Exit;
5412 }
5413
Eric Laurent84e9a102010-09-23 16:10:16 -07005414 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005415 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005416 lStatus = PERMISSION_DENIED;
5417 goto Exit;
5418 }
5419
Dima Zavinfce7a472011-04-19 22:30:36 -07005420 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005421 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005422 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005423 lStatus = PERMISSION_DENIED;
5424 goto Exit;
5425 }
5426
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005427 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005428 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005429 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005430 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005431 lStatus = BAD_VALUE;
5432 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005433 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005434 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005435 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005436 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005437 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005438 }
5439 }
5440
Mathias Agopian65ab4712010-07-14 17:59:35 -07005441 {
5442 Mutex::Autolock _l(mLock);
5443
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444
5445 if (!EffectIsNullUuid(&pDesc->uuid)) {
5446 // if uuid is specified, request effect descriptor
5447 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5448 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005449 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 goto Exit;
5451 }
5452 } else {
5453 // if uuid is not specified, look for an available implementation
5454 // of the required type in effect factory
5455 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005456 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 lStatus = BAD_VALUE;
5458 goto Exit;
5459 }
5460 uint32_t numEffects = 0;
5461 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005462 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005463 bool found = false;
5464
5465 lStatus = EffectQueryNumberEffects(&numEffects);
5466 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005467 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 goto Exit;
5469 }
5470 for (uint32_t i = 0; i < numEffects; i++) {
5471 lStatus = EffectQueryEffect(i, &desc);
5472 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005473 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474 continue;
5475 }
5476 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5477 // If matching type found save effect descriptor. If the session is
5478 // 0 and the effect is not auxiliary, continue enumeration in case
5479 // an auxiliary version of this effect type is available
5480 found = true;
5481 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005482 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5484 break;
5485 }
5486 }
5487 }
5488 if (!found) {
5489 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005490 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 goto Exit;
5492 }
5493 // For same effect type, chose auxiliary version over insert version if
5494 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005495 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5497 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5498 }
5499 }
5500
5501 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005502 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5504 lStatus = INVALID_OPERATION;
5505 goto Exit;
5506 }
5507
Eric Laurent59255e42011-07-27 19:49:51 -07005508 // check recording permission for visualizer
5509 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5510 !recordingAllowed()) {
5511 lStatus = PERMISSION_DENIED;
5512 goto Exit;
5513 }
5514
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 // return effect descriptor
5516 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5517
5518 // If output is not specified try to find a matching audio session ID in one of the
5519 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005520 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5521 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005522 // Note: io is never 0 when creating an effect on an input
5523 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005524 // look for the thread where the specified audio session is present
5525 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5526 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005527 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005528 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005529 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005530 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005531 if (io == 0) {
5532 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5533 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5534 io = mRecordThreads.keyAt(i);
5535 break;
5536 }
5537 }
5538 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005539 // If no output thread contains the requested session ID, default to
5540 // first output. The effect chain will be moved to the correct output
5541 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005542 if (io == 0 && mPlaybackThreads.size()) {
5543 io = mPlaybackThreads.keyAt(0);
5544 }
Steve Block3856b092011-10-20 11:56:00 +01005545 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005546 }
5547 ThreadBase *thread = checkRecordThread_l(io);
5548 if (thread == NULL) {
5549 thread = checkPlaybackThread_l(io);
5550 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005551 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005552 lStatus = BAD_VALUE;
5553 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005555 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005556
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005557 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005559 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005560 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5561 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562 if (handle != 0 && id != NULL) {
5563 *id = handle->id();
5564 }
5565 }
5566
5567Exit:
5568 if(status) {
5569 *status = lStatus;
5570 }
5571 return handle;
5572}
5573
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005574status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5575 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005576{
Steve Block3856b092011-10-20 11:56:00 +01005577 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005578 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005579 Mutex::Autolock _l(mLock);
5580 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005581 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005582 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583 }
Eric Laurentde070132010-07-13 04:45:46 -07005584 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5585 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005586 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005587 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588 }
Eric Laurentde070132010-07-13 04:45:46 -07005589 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5590 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005591 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005592 return BAD_VALUE;
5593 }
5594
5595 Mutex::Autolock _dl(dstThread->mLock);
5596 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005597 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005598
Mathias Agopian65ab4712010-07-14 17:59:35 -07005599 return NO_ERROR;
5600}
5601
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005602// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005603status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005604 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005605 AudioFlinger::PlaybackThread *dstThread,
5606 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005607{
Steve Block3856b092011-10-20 11:56:00 +01005608 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005609 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005610
Eric Laurent59255e42011-07-27 19:49:51 -07005611 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005612 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005613 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005614 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005615 return INVALID_OPERATION;
5616 }
5617
Eric Laurent39e94f82010-07-28 01:32:47 -07005618 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005619 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005620 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005621 // removed.
5622 srcThread->removeEffectChain_l(chain);
5623
5624 // transfer all effects one by one so that new effect chain is created on new thread with
5625 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005626 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005627 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005628 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005629 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5630 while (effect != 0) {
5631 srcThread->removeEffect_l(effect);
5632 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005633 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5634 if (effect->state() == EffectModule::ACTIVE ||
5635 effect->state() == EffectModule::STOPPING) {
5636 effect->start();
5637 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005638 // if the move request is not received from audio policy manager, the effect must be
5639 // re-registered with the new strategy and output
5640 if (dstChain == 0) {
5641 dstChain = effect->chain().promote();
5642 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005643 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005644 srcThread->addEffect_l(effect);
5645 return NO_INIT;
5646 }
5647 strategy = dstChain->strategy();
5648 }
5649 if (reRegister) {
5650 AudioSystem::unregisterEffect(effect->id());
5651 AudioSystem::registerEffect(&effect->desc(),
5652 dstOutput,
5653 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005654 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005655 effect->id());
5656 }
Eric Laurentde070132010-07-13 04:45:46 -07005657 effect = chain->getEffectFromId_l(0);
5658 }
5659
5660 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661}
5662
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005663
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005665sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 const sp<AudioFlinger::Client>& client,
5667 const sp<IEffectClient>& effectClient,
5668 int32_t priority,
5669 int sessionId,
5670 effect_descriptor_t *desc,
5671 int *enabled,
5672 status_t *status
5673 )
5674{
5675 sp<EffectModule> effect;
5676 sp<EffectHandle> handle;
5677 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005679 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 bool effectCreated = false;
5681 bool effectRegistered = false;
5682
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005683 lStatus = initCheck();
5684 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005685 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686 goto Exit;
5687 }
5688
5689 // Do not allow effects with session ID 0 on direct output or duplicating threads
5690 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005691 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005692 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005693 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 lStatus = BAD_VALUE;
5695 goto Exit;
5696 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005697 // Only Pre processor effects are allowed on input threads and only on input threads
5698 if ((mType == RECORD &&
5699 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5700 (mType != RECORD &&
5701 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005702 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005703 desc->name, desc->flags, mType);
5704 lStatus = BAD_VALUE;
5705 goto Exit;
5706 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707
Steve Block3856b092011-10-20 11:56:00 +01005708 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709
5710 { // scope for mLock
5711 Mutex::Autolock _l(mLock);
5712
5713 // check for existing effect chain with the requested audio session
5714 chain = getEffectChain_l(sessionId);
5715 if (chain == 0) {
5716 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005717 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 chain = new EffectChain(this, sessionId);
5719 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005720 chain->setStrategy(getStrategyForSession_l(sessionId));
5721 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005722 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005723 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 }
5725
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005726 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727
5728 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005729 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005730 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005731 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 if (lStatus != NO_ERROR) {
5733 goto Exit;
5734 }
5735 effectRegistered = true;
5736 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005737 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 lStatus = effect->status();
5739 if (lStatus != NO_ERROR) {
5740 goto Exit;
5741 }
Eric Laurentcab11242010-07-15 12:50:15 -07005742 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005743 if (lStatus != NO_ERROR) {
5744 goto Exit;
5745 }
5746 effectCreated = true;
5747
5748 effect->setDevice(mDevice);
5749 effect->setMode(mAudioFlinger->getMode());
5750 }
5751 // create effect handle and connect it to effect module
5752 handle = new EffectHandle(effect, client, effectClient, priority);
5753 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005754 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 *enabled = (int)effect->isEnabled();
5756 }
5757 }
5758
5759Exit:
5760 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005761 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005763 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 }
5765 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005766 AudioSystem::unregisterEffect(effect->id());
5767 }
5768 if (chainCreated) {
5769 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 }
5771 handle.clear();
5772 }
5773
5774 if(status) {
5775 *status = lStatus;
5776 }
5777 return handle;
5778}
5779
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005780sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5781{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005782 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005783 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005784}
5785
Eric Laurentde070132010-07-13 04:45:46 -07005786// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5787// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005788status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005789{
5790 // check for existing effect chain with the requested audio session
5791 int sessionId = effect->sessionId();
5792 sp<EffectChain> chain = getEffectChain_l(sessionId);
5793 bool chainCreated = false;
5794
5795 if (chain == 0) {
5796 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005797 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005798 chain = new EffectChain(this, sessionId);
5799 addEffectChain_l(chain);
5800 chain->setStrategy(getStrategyForSession_l(sessionId));
5801 chainCreated = true;
5802 }
Steve Block3856b092011-10-20 11:56:00 +01005803 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005804
5805 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005806 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005807 this, effect->desc().name, chain.get());
5808 return BAD_VALUE;
5809 }
5810
5811 status_t status = chain->addEffect_l(effect);
5812 if (status != NO_ERROR) {
5813 if (chainCreated) {
5814 removeEffectChain_l(chain);
5815 }
5816 return status;
5817 }
5818
5819 effect->setDevice(mDevice);
5820 effect->setMode(mAudioFlinger->getMode());
5821 return NO_ERROR;
5822}
5823
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005824void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005825
Steve Block3856b092011-10-20 11:56:00 +01005826 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005828 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5829 detachAuxEffect_l(effect->id());
5830 }
5831
5832 sp<EffectChain> chain = effect->chain().promote();
5833 if (chain != 0) {
5834 // remove effect chain if removing last effect
5835 if (chain->removeEffect_l(effect) == 0) {
5836 removeEffectChain_l(chain);
5837 }
5838 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005839 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005840 }
5841}
5842
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005843void AudioFlinger::ThreadBase::lockEffectChains_l(
5844 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5845{
5846 effectChains = mEffectChains;
5847 for (size_t i = 0; i < mEffectChains.size(); i++) {
5848 mEffectChains[i]->lock();
5849 }
5850}
5851
5852void AudioFlinger::ThreadBase::unlockEffectChains(
5853 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5854{
5855 for (size_t i = 0; i < effectChains.size(); i++) {
5856 effectChains[i]->unlock();
5857 }
5858}
5859
5860sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5861{
5862 Mutex::Autolock _l(mLock);
5863 return getEffectChain_l(sessionId);
5864}
5865
5866sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5867{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005868 size_t size = mEffectChains.size();
5869 for (size_t i = 0; i < size; i++) {
5870 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005871 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005872 }
5873 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005874 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005875}
5876
Glenn Kastenf78aee72012-01-04 11:00:47 -08005877void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005878{
5879 Mutex::Autolock _l(mLock);
5880 size_t size = mEffectChains.size();
5881 for (size_t i = 0; i < size; i++) {
5882 mEffectChains[i]->setMode_l(mode);
5883 }
5884}
5885
5886void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005887 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08005888 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005889
Mathias Agopian65ab4712010-07-14 17:59:35 -07005890 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005891 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 // delete the effect module if removing last handle on it
5893 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08005894 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005895 removeEffect_l(effect);
5896 AudioSystem::unregisterEffect(effect->id());
5897 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005898 }
5899}
5900
5901status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5902{
5903 int session = chain->sessionId();
5904 int16_t *buffer = mMixBuffer;
5905 bool ownsBuffer = false;
5906
Steve Block3856b092011-10-20 11:56:00 +01005907 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 if (session > 0) {
5909 // Only one effect chain can be present in direct output thread and it uses
5910 // the mix buffer as input
5911 if (mType != DIRECT) {
5912 size_t numSamples = mFrameCount * mChannelCount;
5913 buffer = new int16_t[numSamples];
5914 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005915 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 ownsBuffer = true;
5917 }
5918
5919 // Attach all tracks with same session ID to this chain.
5920 for (size_t i = 0; i < mTracks.size(); ++i) {
5921 sp<Track> track = mTracks[i];
5922 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005923 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005925 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 }
5927 }
5928
5929 // indicate all active tracks in the chain
5930 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5931 sp<Track> track = mActiveTracks[i].promote();
5932 if (track == 0) continue;
5933 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005934 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005935 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936 }
5937 }
5938 }
5939
5940 chain->setInBuffer(buffer, ownsBuffer);
5941 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005942 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005943 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005944 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5945 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005947 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5948 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005949 // Effect chain for other sessions are inserted at beginning of effect
5950 // chains list to be processed before output mix effects. Relative order between other
5951 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 size_t size = mEffectChains.size();
5953 size_t i = 0;
5954 for (i = 0; i < size; i++) {
5955 if (mEffectChains[i]->sessionId() < session) break;
5956 }
5957 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005958 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959
5960 return NO_ERROR;
5961}
5962
5963size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5964{
5965 int session = chain->sessionId();
5966
Steve Block3856b092011-10-20 11:56:00 +01005967 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968
5969 for (size_t i = 0; i < mEffectChains.size(); i++) {
5970 if (chain == mEffectChains[i]) {
5971 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005972 // detach all active tracks from the chain
5973 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5974 sp<Track> track = mActiveTracks[i].promote();
5975 if (track == 0) continue;
5976 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005977 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005978 chain.get(), session);
5979 chain->decActiveTrackCnt();
5980 }
5981 }
5982
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 // detach all tracks with same session ID from this chain
5984 for (size_t i = 0; i < mTracks.size(); ++i) {
5985 sp<Track> track = mTracks[i];
5986 if (session == track->sessionId()) {
5987 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005988 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 }
5990 }
Eric Laurentde070132010-07-13 04:45:46 -07005991 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 }
5993 }
5994 return mEffectChains.size();
5995}
5996
Eric Laurentde070132010-07-13 04:45:46 -07005997status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5998 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999{
6000 Mutex::Autolock _l(mLock);
6001 return attachAuxEffect_l(track, EffectId);
6002}
6003
Eric Laurentde070132010-07-13 04:45:46 -07006004status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6005 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006006{
6007 status_t status = NO_ERROR;
6008
6009 if (EffectId == 0) {
6010 track->setAuxBuffer(0, NULL);
6011 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006012 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6013 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006014 if (effect != 0) {
6015 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6016 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6017 } else {
6018 status = INVALID_OPERATION;
6019 }
6020 } else {
6021 status = BAD_VALUE;
6022 }
6023 }
6024 return status;
6025}
6026
6027void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6028{
6029 for (size_t i = 0; i < mTracks.size(); ++i) {
6030 sp<Track> track = mTracks[i];
6031 if (track->auxEffectId() == effectId) {
6032 attachAuxEffect_l(track, 0);
6033 }
6034 }
6035}
6036
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006037status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6038{
6039 // only one chain per input thread
6040 if (mEffectChains.size() != 0) {
6041 return INVALID_OPERATION;
6042 }
Steve Block3856b092011-10-20 11:56:00 +01006043 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006044
6045 chain->setInBuffer(NULL);
6046 chain->setOutBuffer(NULL);
6047
Eric Laurent59255e42011-07-27 19:49:51 -07006048 checkSuspendOnAddEffectChain_l(chain);
6049
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006050 mEffectChains.add(chain);
6051
6052 return NO_ERROR;
6053}
6054
6055size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6056{
Steve Block3856b092011-10-20 11:56:00 +01006057 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006058 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006059 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6060 chain.get(), mEffectChains.size(), this);
6061 if (mEffectChains.size() == 1) {
6062 mEffectChains.removeAt(0);
6063 }
6064 return 0;
6065}
6066
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067// ----------------------------------------------------------------------------
6068// EffectModule implementation
6069// ----------------------------------------------------------------------------
6070
6071#undef LOG_TAG
6072#define LOG_TAG "AudioFlinger::EffectModule"
6073
6074AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6075 const wp<AudioFlinger::EffectChain>& chain,
6076 effect_descriptor_t *desc,
6077 int id,
6078 int sessionId)
6079 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006080 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006081{
Steve Block3856b092011-10-20 11:56:00 +01006082 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 int lStatus;
6084 sp<ThreadBase> thread = mThread.promote();
6085 if (thread == 0) {
6086 return;
6087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088
6089 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6090
6091 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006092 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093
6094 if (mStatus != NO_ERROR) {
6095 return;
6096 }
6097 lStatus = init();
6098 if (lStatus < 0) {
6099 mStatus = lStatus;
6100 goto Error;
6101 }
6102
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006103 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6104 mPinned = true;
6105 }
Steve Block3856b092011-10-20 11:56:00 +01006106 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107 return;
6108Error:
6109 EffectRelease(mEffectInterface);
6110 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006111 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006112}
6113
6114AudioFlinger::EffectModule::~EffectModule()
6115{
Steve Block3856b092011-10-20 11:56:00 +01006116 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006117 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006118 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6119 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6120 sp<ThreadBase> thread = mThread.promote();
6121 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006122 audio_stream_t *stream = thread->stream();
6123 if (stream != NULL) {
6124 stream->remove_audio_effect(stream, mEffectInterface);
6125 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006126 }
6127 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 // release effect engine
6129 EffectRelease(mEffectInterface);
6130 }
6131}
6132
Glenn Kasten435dbe62012-01-30 10:15:48 -08006133status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134{
6135 status_t status;
6136
6137 Mutex::Autolock _l(mLock);
6138 // First handle in mHandles has highest priority and controls the effect module
6139 int priority = handle->priority();
6140 size_t size = mHandles.size();
6141 sp<EffectHandle> h;
6142 size_t i;
6143 for (i = 0; i < size; i++) {
6144 h = mHandles[i].promote();
6145 if (h == 0) continue;
6146 if (h->priority() <= priority) break;
6147 }
6148 // if inserted in first place, move effect control from previous owner to this handle
6149 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006150 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006152 enabled = h->enabled();
6153 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 }
Eric Laurent59255e42011-07-27 19:49:51 -07006155 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 status = NO_ERROR;
6157 } else {
6158 status = ALREADY_EXISTS;
6159 }
Steve Block3856b092011-10-20 11:56:00 +01006160 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 mHandles.insertAt(handle, i);
6162 return status;
6163}
6164
6165size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6166{
6167 Mutex::Autolock _l(mLock);
6168 size_t size = mHandles.size();
6169 size_t i;
6170 for (i = 0; i < size; i++) {
6171 if (mHandles[i] == handle) break;
6172 }
6173 if (i == size) {
6174 return size;
6175 }
Steve Block3856b092011-10-20 11:56:00 +01006176 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006177
6178 bool enabled = false;
6179 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006180 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006181 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006182 enabled = hdl->enabled();
6183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006184 mHandles.removeAt(i);
6185 size = mHandles.size();
6186 // if removed from first place, move effect control from this handle to next in line
6187 if (i == 0 && size != 0) {
6188 sp<EffectHandle> h = mHandles[0].promote();
6189 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006190 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191 }
6192 }
6193
Eric Laurentec437d82011-07-26 20:54:46 -07006194 // Prevent calls to process() and other functions on effect interface from now on.
6195 // The effect engine will be released by the destructor when the last strong reference on
6196 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006197 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006198 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006199 }
6200
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 return size;
6202}
6203
Eric Laurent59255e42011-07-27 19:49:51 -07006204sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6205{
6206 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006207 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006208}
6209
Glenn Kasten58123c32012-02-03 10:32:24 -08006210void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211{
Steve Block3856b092011-10-20 11:56:00 +01006212 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 // keep a strong reference on this EffectModule to avoid calling the
6214 // destructor before we exit
6215 sp<EffectModule> keep(this);
6216 {
6217 sp<ThreadBase> thread = mThread.promote();
6218 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006219 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 }
6221 }
6222}
6223
6224void AudioFlinger::EffectModule::updateState() {
6225 Mutex::Autolock _l(mLock);
6226
6227 switch (mState) {
6228 case RESTART:
6229 reset_l();
6230 // FALL THROUGH
6231
6232 case STARTING:
6233 // clear auxiliary effect input buffer for next accumulation
6234 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6235 memset(mConfig.inputCfg.buffer.raw,
6236 0,
6237 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6238 }
6239 start_l();
6240 mState = ACTIVE;
6241 break;
6242 case STOPPING:
6243 stop_l();
6244 mDisableWaitCnt = mMaxDisableWaitCnt;
6245 mState = STOPPED;
6246 break;
6247 case STOPPED:
6248 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6249 // turn off sequence.
6250 if (--mDisableWaitCnt == 0) {
6251 reset_l();
6252 mState = IDLE;
6253 }
6254 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006255 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 break;
6257 }
6258}
6259
6260void AudioFlinger::EffectModule::process()
6261{
6262 Mutex::Autolock _l(mLock);
6263
Eric Laurentec437d82011-07-26 20:54:46 -07006264 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006265 mConfig.inputCfg.buffer.raw == NULL ||
6266 mConfig.outputCfg.buffer.raw == NULL) {
6267 return;
6268 }
6269
Eric Laurent8f45bd72010-08-31 13:50:07 -07006270 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6272 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006273 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006275 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 }
6277
6278 // do the actual processing in the effect engine
6279 int ret = (*mEffectInterface)->process(mEffectInterface,
6280 &mConfig.inputCfg.buffer,
6281 &mConfig.outputCfg.buffer);
6282
6283 // force transition to IDLE state when engine is ready
6284 if (mState == STOPPED && ret == -ENODATA) {
6285 mDisableWaitCnt = 1;
6286 }
6287
6288 // clear auxiliary effect input buffer for next accumulation
6289 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006290 memset(mConfig.inputCfg.buffer.raw, 0,
6291 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 }
6293 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006294 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6295 // If an insert effect is idle and input buffer is different from output buffer,
6296 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006298 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006299 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6300 int16_t *in = mConfig.inputCfg.buffer.s16;
6301 int16_t *out = mConfig.outputCfg.buffer.s16;
6302 for (size_t i = 0; i < frameCnt; i++) {
6303 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 }
6306 }
6307}
6308
6309void AudioFlinger::EffectModule::reset_l()
6310{
6311 if (mEffectInterface == NULL) {
6312 return;
6313 }
6314 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6315}
6316
6317status_t AudioFlinger::EffectModule::configure()
6318{
6319 uint32_t channels;
6320 if (mEffectInterface == NULL) {
6321 return NO_INIT;
6322 }
6323
6324 sp<ThreadBase> thread = mThread.promote();
6325 if (thread == 0) {
6326 return DEAD_OBJECT;
6327 }
6328
6329 // TODO: handle configuration of effects replacing track process
6330 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006331 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006333 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334 }
6335
6336 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006337 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 } else {
6339 mConfig.inputCfg.channels = channels;
6340 }
6341 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006342 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6343 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 mConfig.inputCfg.samplingRate = thread->sampleRate();
6345 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6346 mConfig.inputCfg.bufferProvider.cookie = NULL;
6347 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6348 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6349 mConfig.outputCfg.bufferProvider.cookie = NULL;
6350 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6351 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6352 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6353 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006354 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006355 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 // - in other sessions:
6357 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6358 // other effect: overwrites output buffer: input buffer == output buffer
6359 // Auxiliary effect:
6360 // accumulates in output buffer: input buffer != output buffer
6361 // Therefore: accumulate <=> input buffer != output buffer
6362 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6363 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6364 } else {
6365 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6366 }
6367 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6368 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6369 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6370 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6371
Steve Block3856b092011-10-20 11:56:00 +01006372 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006373 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6374
Mathias Agopian65ab4712010-07-14 17:59:35 -07006375 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006376 uint32_t size = sizeof(int);
6377 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006378 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006379 sizeof(effect_config_t),
6380 &mConfig,
6381 &size,
6382 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 if (status == 0) {
6384 status = cmdStatus;
6385 }
6386
6387 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6388 (1000 * mConfig.outputCfg.buffer.frameCount);
6389
6390 return status;
6391}
6392
6393status_t AudioFlinger::EffectModule::init()
6394{
6395 Mutex::Autolock _l(mLock);
6396 if (mEffectInterface == NULL) {
6397 return NO_INIT;
6398 }
6399 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006400 uint32_t size = sizeof(status_t);
6401 status_t status = (*mEffectInterface)->command(mEffectInterface,
6402 EFFECT_CMD_INIT,
6403 0,
6404 NULL,
6405 &size,
6406 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006407 if (status == 0) {
6408 status = cmdStatus;
6409 }
6410 return status;
6411}
6412
Eric Laurentec35a142011-10-05 17:42:25 -07006413status_t AudioFlinger::EffectModule::start()
6414{
6415 Mutex::Autolock _l(mLock);
6416 return start_l();
6417}
6418
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419status_t AudioFlinger::EffectModule::start_l()
6420{
6421 if (mEffectInterface == NULL) {
6422 return NO_INIT;
6423 }
6424 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006425 uint32_t size = sizeof(status_t);
6426 status_t status = (*mEffectInterface)->command(mEffectInterface,
6427 EFFECT_CMD_ENABLE,
6428 0,
6429 NULL,
6430 &size,
6431 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 if (status == 0) {
6433 status = cmdStatus;
6434 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006435 if (status == 0 &&
6436 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6437 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6438 sp<ThreadBase> thread = mThread.promote();
6439 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006440 audio_stream_t *stream = thread->stream();
6441 if (stream != NULL) {
6442 stream->add_audio_effect(stream, mEffectInterface);
6443 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006444 }
6445 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 return status;
6447}
6448
Eric Laurentec437d82011-07-26 20:54:46 -07006449status_t AudioFlinger::EffectModule::stop()
6450{
6451 Mutex::Autolock _l(mLock);
6452 return stop_l();
6453}
6454
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455status_t AudioFlinger::EffectModule::stop_l()
6456{
6457 if (mEffectInterface == NULL) {
6458 return NO_INIT;
6459 }
6460 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006461 uint32_t size = sizeof(status_t);
6462 status_t status = (*mEffectInterface)->command(mEffectInterface,
6463 EFFECT_CMD_DISABLE,
6464 0,
6465 NULL,
6466 &size,
6467 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 if (status == 0) {
6469 status = cmdStatus;
6470 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006471 if (status == 0 &&
6472 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6473 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6474 sp<ThreadBase> thread = mThread.promote();
6475 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006476 audio_stream_t *stream = thread->stream();
6477 if (stream != NULL) {
6478 stream->remove_audio_effect(stream, mEffectInterface);
6479 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006480 }
6481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006482 return status;
6483}
6484
Eric Laurent25f43952010-07-28 05:40:18 -07006485status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6486 uint32_t cmdSize,
6487 void *pCmdData,
6488 uint32_t *replySize,
6489 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490{
6491 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006492// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006493
Eric Laurentec437d82011-07-26 20:54:46 -07006494 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006495 return NO_INIT;
6496 }
Eric Laurent25f43952010-07-28 05:40:18 -07006497 status_t status = (*mEffectInterface)->command(mEffectInterface,
6498 cmdCode,
6499 cmdSize,
6500 pCmdData,
6501 replySize,
6502 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006504 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 for (size_t i = 1; i < mHandles.size(); i++) {
6506 sp<EffectHandle> h = mHandles[i].promote();
6507 if (h != 0) {
6508 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6509 }
6510 }
6511 }
6512 return status;
6513}
6514
6515status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6516{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006517
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006519 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520
6521 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006522 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6523 if (enabled && status != NO_ERROR) {
6524 return status;
6525 }
6526
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527 switch (mState) {
6528 // going from disabled to enabled
6529 case IDLE:
6530 mState = STARTING;
6531 break;
6532 case STOPPED:
6533 mState = RESTART;
6534 break;
6535 case STOPPING:
6536 mState = ACTIVE;
6537 break;
6538
6539 // going from enabled to disabled
6540 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006541 mState = STOPPED;
6542 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543 case STARTING:
6544 mState = IDLE;
6545 break;
6546 case ACTIVE:
6547 mState = STOPPING;
6548 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006549 case DESTROYED:
6550 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 }
6552 for (size_t i = 1; i < mHandles.size(); i++) {
6553 sp<EffectHandle> h = mHandles[i].promote();
6554 if (h != 0) {
6555 h->setEnabled(enabled);
6556 }
6557 }
6558 }
6559 return NO_ERROR;
6560}
6561
Glenn Kastenc59c0042012-02-02 14:06:11 -08006562bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563{
6564 switch (mState) {
6565 case RESTART:
6566 case STARTING:
6567 case ACTIVE:
6568 return true;
6569 case IDLE:
6570 case STOPPING:
6571 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006572 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 default:
6574 return false;
6575 }
6576}
6577
Glenn Kastenc59c0042012-02-02 14:06:11 -08006578bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006579{
6580 switch (mState) {
6581 case RESTART:
6582 case ACTIVE:
6583 case STOPPING:
6584 case STOPPED:
6585 return true;
6586 case IDLE:
6587 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006588 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006589 default:
6590 return false;
6591 }
6592}
6593
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6595{
6596 Mutex::Autolock _l(mLock);
6597 status_t status = NO_ERROR;
6598
6599 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6600 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006601 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006602 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6603 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604 status_t cmdStatus;
6605 uint32_t volume[2];
6606 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006607 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006608 volume[0] = *left;
6609 volume[1] = *right;
6610 if (controller) {
6611 pVolume = volume;
6612 }
Eric Laurent25f43952010-07-28 05:40:18 -07006613 status = (*mEffectInterface)->command(mEffectInterface,
6614 EFFECT_CMD_SET_VOLUME,
6615 size,
6616 volume,
6617 &size,
6618 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006619 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6620 *left = volume[0];
6621 *right = volume[1];
6622 }
6623 }
6624 return status;
6625}
6626
6627status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6628{
6629 Mutex::Autolock _l(mLock);
6630 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006631 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6632 // audio pre processing modules on RecordThread can receive both output and
6633 // input device indication in the same call
6634 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6635 if (dev) {
6636 status_t cmdStatus;
6637 uint32_t size = sizeof(status_t);
6638
6639 status = (*mEffectInterface)->command(mEffectInterface,
6640 EFFECT_CMD_SET_DEVICE,
6641 sizeof(uint32_t),
6642 &dev,
6643 &size,
6644 &cmdStatus);
6645 if (status == NO_ERROR) {
6646 status = cmdStatus;
6647 }
6648 }
6649 dev = device & AUDIO_DEVICE_IN_ALL;
6650 if (dev) {
6651 status_t cmdStatus;
6652 uint32_t size = sizeof(status_t);
6653
6654 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6655 EFFECT_CMD_SET_INPUT_DEVICE,
6656 sizeof(uint32_t),
6657 &dev,
6658 &size,
6659 &cmdStatus);
6660 if (status2 == NO_ERROR) {
6661 status2 = cmdStatus;
6662 }
6663 if (status == NO_ERROR) {
6664 status = status2;
6665 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006666 }
6667 }
6668 return status;
6669}
6670
Glenn Kastenf78aee72012-01-04 11:00:47 -08006671status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672{
6673 Mutex::Autolock _l(mLock);
6674 status_t status = NO_ERROR;
6675 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006676 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006677 uint32_t size = sizeof(status_t);
6678 status = (*mEffectInterface)->command(mEffectInterface,
6679 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006680 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006681 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006682 &size,
6683 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 if (status == NO_ERROR) {
6685 status = cmdStatus;
6686 }
6687 }
6688 return status;
6689}
6690
Eric Laurent59255e42011-07-27 19:49:51 -07006691void AudioFlinger::EffectModule::setSuspended(bool suspended)
6692{
6693 Mutex::Autolock _l(mLock);
6694 mSuspended = suspended;
6695}
Glenn Kastena3a85482012-01-04 11:01:11 -08006696
6697bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006698{
6699 Mutex::Autolock _l(mLock);
6700 return mSuspended;
6701}
6702
Mathias Agopian65ab4712010-07-14 17:59:35 -07006703status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6704{
6705 const size_t SIZE = 256;
6706 char buffer[SIZE];
6707 String8 result;
6708
6709 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6710 result.append(buffer);
6711
6712 bool locked = tryLock(mLock);
6713 // failed to lock - AudioFlinger is probably deadlocked
6714 if (!locked) {
6715 result.append("\t\tCould not lock Fx mutex:\n");
6716 }
6717
6718 result.append("\t\tSession Status State Engine:\n");
6719 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6720 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6721 result.append(buffer);
6722
6723 result.append("\t\tDescriptor:\n");
6724 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6725 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6726 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6727 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6728 result.append(buffer);
6729 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6730 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6731 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6732 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6733 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006734 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006735 mDescriptor.apiVersion,
6736 mDescriptor.flags);
6737 result.append(buffer);
6738 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6739 mDescriptor.name);
6740 result.append(buffer);
6741 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6742 mDescriptor.implementor);
6743 result.append(buffer);
6744
6745 result.append("\t\t- Input configuration:\n");
6746 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6747 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6748 (uint32_t)mConfig.inputCfg.buffer.raw,
6749 mConfig.inputCfg.buffer.frameCount,
6750 mConfig.inputCfg.samplingRate,
6751 mConfig.inputCfg.channels,
6752 mConfig.inputCfg.format);
6753 result.append(buffer);
6754
6755 result.append("\t\t- Output configuration:\n");
6756 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6757 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6758 (uint32_t)mConfig.outputCfg.buffer.raw,
6759 mConfig.outputCfg.buffer.frameCount,
6760 mConfig.outputCfg.samplingRate,
6761 mConfig.outputCfg.channels,
6762 mConfig.outputCfg.format);
6763 result.append(buffer);
6764
6765 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6766 result.append(buffer);
6767 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6768 for (size_t i = 0; i < mHandles.size(); ++i) {
6769 sp<EffectHandle> handle = mHandles[i].promote();
6770 if (handle != 0) {
6771 handle->dump(buffer, SIZE);
6772 result.append(buffer);
6773 }
6774 }
6775
6776 result.append("\n");
6777
6778 write(fd, result.string(), result.length());
6779
6780 if (locked) {
6781 mLock.unlock();
6782 }
6783
6784 return NO_ERROR;
6785}
6786
6787// ----------------------------------------------------------------------------
6788// EffectHandle implementation
6789// ----------------------------------------------------------------------------
6790
6791#undef LOG_TAG
6792#define LOG_TAG "AudioFlinger::EffectHandle"
6793
6794AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6795 const sp<AudioFlinger::Client>& client,
6796 const sp<IEffectClient>& effectClient,
6797 int32_t priority)
6798 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006799 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006800 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801{
Steve Block3856b092011-10-20 11:56:00 +01006802 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006804 if (client == 0) {
6805 return;
6806 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006807 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6808 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6809 if (mCblkMemory != 0) {
6810 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6811
Glenn Kastena0d68332012-01-27 16:47:15 -08006812 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813 new(mCblk) effect_param_cblk_t();
6814 mBuffer = (uint8_t *)mCblk + bufOffset;
6815 }
6816 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006817 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 return;
6819 }
6820}
6821
6822AudioFlinger::EffectHandle::~EffectHandle()
6823{
Steve Block3856b092011-10-20 11:56:00 +01006824 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006825 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006826 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827}
6828
6829status_t AudioFlinger::EffectHandle::enable()
6830{
Steve Block3856b092011-10-20 11:56:00 +01006831 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832 if (!mHasControl) return INVALID_OPERATION;
6833 if (mEffect == 0) return DEAD_OBJECT;
6834
Eric Laurentdb7c0792011-08-10 10:37:50 -07006835 if (mEnabled) {
6836 return NO_ERROR;
6837 }
6838
Eric Laurent59255e42011-07-27 19:49:51 -07006839 mEnabled = true;
6840
6841 sp<ThreadBase> thread = mEffect->thread().promote();
6842 if (thread != 0) {
6843 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6844 }
6845
6846 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6847 if (mEffect->suspended()) {
6848 return NO_ERROR;
6849 }
6850
Eric Laurentdb7c0792011-08-10 10:37:50 -07006851 status_t status = mEffect->setEnabled(true);
6852 if (status != NO_ERROR) {
6853 if (thread != 0) {
6854 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6855 }
6856 mEnabled = false;
6857 }
6858 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859}
6860
6861status_t AudioFlinger::EffectHandle::disable()
6862{
Steve Block3856b092011-10-20 11:56:00 +01006863 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006865 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866
Eric Laurentdb7c0792011-08-10 10:37:50 -07006867 if (!mEnabled) {
6868 return NO_ERROR;
6869 }
Eric Laurent59255e42011-07-27 19:49:51 -07006870 mEnabled = false;
6871
6872 if (mEffect->suspended()) {
6873 return NO_ERROR;
6874 }
6875
6876 status_t status = mEffect->setEnabled(false);
6877
6878 sp<ThreadBase> thread = mEffect->thread().promote();
6879 if (thread != 0) {
6880 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6881 }
6882
6883 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006884}
6885
6886void AudioFlinger::EffectHandle::disconnect()
6887{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006888 disconnect(true);
6889}
6890
Glenn Kasten58123c32012-02-03 10:32:24 -08006891void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006892{
Glenn Kasten58123c32012-02-03 10:32:24 -08006893 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 if (mEffect == 0) {
6895 return;
6896 }
Glenn Kasten58123c32012-02-03 10:32:24 -08006897 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07006898
Eric Laurenta85a74a2011-10-19 11:44:54 -07006899 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006900 sp<ThreadBase> thread = mEffect->thread().promote();
6901 if (thread != 0) {
6902 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6903 }
Eric Laurent59255e42011-07-27 19:49:51 -07006904 }
6905
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 // release sp on module => module destructor can be called now
6907 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006909 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006910 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006911 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6912 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006913 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006914 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6916 mClient.clear();
6917 }
6918}
6919
Eric Laurent25f43952010-07-28 05:40:18 -07006920status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6921 uint32_t cmdSize,
6922 void *pCmdData,
6923 uint32_t *replySize,
6924 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925{
Steve Block3856b092011-10-20 11:56:00 +01006926// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006927// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928
6929 // only get parameter command is permitted for applications not controlling the effect
6930 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6931 return INVALID_OPERATION;
6932 }
6933 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006934 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935
6936 // handle commands that are not forwarded transparently to effect engine
6937 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6938 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6939 // no risk to block the whole media server process or mixer threads is we are stuck here
6940 Mutex::Autolock _l(mCblk->lock);
6941 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6942 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6943 mCblk->serverIndex = 0;
6944 mCblk->clientIndex = 0;
6945 return BAD_VALUE;
6946 }
6947 status_t status = NO_ERROR;
6948 while (mCblk->serverIndex < mCblk->clientIndex) {
6949 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006950 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 int *p = (int *)(mBuffer + mCblk->serverIndex);
6952 int size = *p++;
6953 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006954 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006955 break;
6956 }
6957 effect_param_t *param = (effect_param_t *)p;
6958 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006959 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006960 mCblk->serverIndex += size;
6961 continue;
6962 }
Eric Laurent25f43952010-07-28 05:40:18 -07006963 uint32_t psize = sizeof(effect_param_t) +
6964 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6965 param->vsize;
6966 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6967 psize,
6968 p,
6969 &rsize,
6970 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006971 // stop at first error encountered
6972 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006974 *(int *)pReplyData = reply;
6975 break;
6976 } else if (reply != NO_ERROR) {
6977 *(int *)pReplyData = reply;
6978 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 }
6980 mCblk->serverIndex += size;
6981 }
6982 mCblk->serverIndex = 0;
6983 mCblk->clientIndex = 0;
6984 return status;
6985 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006986 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 return enable();
6988 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006989 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990 return disable();
6991 }
6992
6993 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6994}
6995
Eric Laurent59255e42011-07-27 19:49:51 -07006996void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006997{
Steve Block3856b092011-10-20 11:56:00 +01006998 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999
7000 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007001 mEnabled = enabled;
7002
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 if (signal && mEffectClient != 0) {
7004 mEffectClient->controlStatusChanged(hasControl);
7005 }
7006}
7007
Eric Laurent25f43952010-07-28 05:40:18 -07007008void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7009 uint32_t cmdSize,
7010 void *pCmdData,
7011 uint32_t replySize,
7012 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013{
7014 if (mEffectClient != 0) {
7015 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7016 }
7017}
7018
7019
7020
7021void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7022{
7023 if (mEffectClient != 0) {
7024 mEffectClient->enableStatusChanged(enabled);
7025 }
7026}
7027
7028status_t AudioFlinger::EffectHandle::onTransact(
7029 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7030{
7031 return BnEffect::onTransact(code, data, reply, flags);
7032}
7033
7034
7035void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7036{
Glenn Kastena0d68332012-01-27 16:47:15 -08007037 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007038
7039 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007040 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041 mPriority,
7042 mHasControl,
7043 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007044 mCblk ? mCblk->clientIndex : 0,
7045 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007046 );
7047
7048 if (locked) {
7049 mCblk->lock.unlock();
7050 }
7051}
7052
7053#undef LOG_TAG
7054#define LOG_TAG "AudioFlinger::EffectChain"
7055
7056AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7057 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007058 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007059 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7060 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061{
Dima Zavinfce7a472011-04-19 22:30:36 -07007062 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007063 sp<ThreadBase> thread = mThread.promote();
7064 if (thread == 0) {
7065 return;
7066 }
7067 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7068 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069}
7070
7071AudioFlinger::EffectChain::~EffectChain()
7072{
7073 if (mOwnInBuffer) {
7074 delete mInBuffer;
7075 }
7076
7077}
7078
Eric Laurent59255e42011-07-27 19:49:51 -07007079// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007080sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007082 size_t size = mEffects.size();
7083
7084 for (size_t i = 0; i < size; i++) {
7085 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007086 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007087 }
7088 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007089 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090}
7091
Eric Laurent59255e42011-07-27 19:49:51 -07007092// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007093sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007094{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 size_t size = mEffects.size();
7096
7097 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007098 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7099 if (id == 0 || mEffects[i]->id() == id) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007100 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101 }
7102 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007103 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007104}
7105
Eric Laurent59255e42011-07-27 19:49:51 -07007106// getEffectFromType_l() must be called with ThreadBase::mLock held
7107sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7108 const effect_uuid_t *type)
7109{
Eric Laurent59255e42011-07-27 19:49:51 -07007110 size_t size = mEffects.size();
7111
7112 for (size_t i = 0; i < size; i++) {
7113 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007114 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007115 }
7116 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007117 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007118}
7119
Mathias Agopian65ab4712010-07-14 17:59:35 -07007120// Must be called with EffectChain::mLock locked
7121void AudioFlinger::EffectChain::process_l()
7122{
Eric Laurentdac69112010-09-28 14:09:57 -07007123 sp<ThreadBase> thread = mThread.promote();
7124 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007125 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007126 return;
7127 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007128 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7129 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007130 // always process effects unless no more tracks are on the session and the effect tail
7131 // has been rendered
7132 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007133 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007134 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007135
Eric Laurent544fe9b2011-11-11 15:42:52 -08007136 if (!tracksOnSession && mTailBufferCount == 0) {
7137 doProcess = false;
7138 }
7139
7140 if (activeTrackCnt() == 0) {
7141 // if no track is active and the effect tail has not been rendered,
7142 // the input buffer must be cleared here as the mixer process will not do it
7143 if (tracksOnSession || mTailBufferCount > 0) {
7144 size_t numSamples = thread->frameCount() * thread->channelCount();
7145 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7146 if (mTailBufferCount > 0) {
7147 mTailBufferCount--;
7148 }
7149 }
7150 }
Eric Laurentdac69112010-09-28 14:09:57 -07007151 }
7152
Mathias Agopian65ab4712010-07-14 17:59:35 -07007153 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007154 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007155 for (size_t i = 0; i < size; i++) {
7156 mEffects[i]->process();
7157 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158 }
7159 for (size_t i = 0; i < size; i++) {
7160 mEffects[i]->updateState();
7161 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007162}
7163
Eric Laurentcab11242010-07-15 12:50:15 -07007164// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007165status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166{
7167 effect_descriptor_t desc = effect->desc();
7168 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7169
7170 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007171 effect->setChain(this);
7172 sp<ThreadBase> thread = mThread.promote();
7173 if (thread == 0) {
7174 return NO_INIT;
7175 }
7176 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177
7178 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7179 // Auxiliary effects are inserted at the beginning of mEffects vector as
7180 // they are processed first and accumulated in chain input buffer
7181 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007182
Mathias Agopian65ab4712010-07-14 17:59:35 -07007183 // the input buffer for auxiliary effect contains mono samples in
7184 // 32 bit format. This is to avoid saturation in AudoMixer
7185 // accumulation stage. Saturation is done in EffectModule::process() before
7186 // calling the process in effect engine
7187 size_t numSamples = thread->frameCount();
7188 int32_t *buffer = new int32_t[numSamples];
7189 memset(buffer, 0, numSamples * sizeof(int32_t));
7190 effect->setInBuffer((int16_t *)buffer);
7191 // auxiliary effects output samples to chain input buffer for further processing
7192 // by insert effects
7193 effect->setOutBuffer(mInBuffer);
7194 } else {
7195 // Insert effects are inserted at the end of mEffects vector as they are processed
7196 // after track and auxiliary effects.
7197 // Insert effect order as a function of indicated preference:
7198 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7199 // another effect is present
7200 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7201 // last effect claiming first position
7202 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7203 // first effect claiming last position
7204 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7205 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7206 // already present
7207
7208 int size = (int)mEffects.size();
7209 int idx_insert = size;
7210 int idx_insert_first = -1;
7211 int idx_insert_last = -1;
7212
7213 for (int i = 0; i < size; i++) {
7214 effect_descriptor_t d = mEffects[i]->desc();
7215 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7216 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7217 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7218 // check invalid effect chaining combinations
7219 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7220 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007221 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007222 return INVALID_OPERATION;
7223 }
7224 // remember position of first insert effect and by default
7225 // select this as insert position for new effect
7226 if (idx_insert == size) {
7227 idx_insert = i;
7228 }
7229 // remember position of last insert effect claiming
7230 // first position
7231 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7232 idx_insert_first = i;
7233 }
7234 // remember position of first insert effect claiming
7235 // last position
7236 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7237 idx_insert_last == -1) {
7238 idx_insert_last = i;
7239 }
7240 }
7241 }
7242
7243 // modify idx_insert from first position if needed
7244 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7245 if (idx_insert_last != -1) {
7246 idx_insert = idx_insert_last;
7247 } else {
7248 idx_insert = size;
7249 }
7250 } else {
7251 if (idx_insert_first != -1) {
7252 idx_insert = idx_insert_first + 1;
7253 }
7254 }
7255
7256 // always read samples from chain input buffer
7257 effect->setInBuffer(mInBuffer);
7258
7259 // if last effect in the chain, output samples to chain
7260 // output buffer, otherwise to chain input buffer
7261 if (idx_insert == size) {
7262 if (idx_insert != 0) {
7263 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7264 mEffects[idx_insert-1]->configure();
7265 }
7266 effect->setOutBuffer(mOutBuffer);
7267 } else {
7268 effect->setOutBuffer(mInBuffer);
7269 }
7270 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007271
Steve Block3856b092011-10-20 11:56:00 +01007272 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273 }
7274 effect->configure();
7275 return NO_ERROR;
7276}
7277
Eric Laurentcab11242010-07-15 12:50:15 -07007278// removeEffect_l() must be called with PlaybackThread::mLock held
7279size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007280{
7281 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282 int size = (int)mEffects.size();
7283 int i;
7284 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7285
7286 for (i = 0; i < size; i++) {
7287 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007288 // calling stop here will remove pre-processing effect from the audio HAL.
7289 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7290 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007291 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7292 mEffects[i]->state() == EffectModule::STOPPING) {
7293 mEffects[i]->stop();
7294 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7296 delete[] effect->inBuffer();
7297 } else {
7298 if (i == size - 1 && i != 0) {
7299 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7300 mEffects[i - 1]->configure();
7301 }
7302 }
7303 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007304 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305 break;
7306 }
7307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308
7309 return mEffects.size();
7310}
7311
Eric Laurentcab11242010-07-15 12:50:15 -07007312// setDevice_l() must be called with PlaybackThread::mLock held
7313void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
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]->setDevice(device);
7318 }
7319}
7320
Eric Laurentcab11242010-07-15 12:50:15 -07007321// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007322void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323{
7324 size_t size = mEffects.size();
7325 for (size_t i = 0; i < size; i++) {
7326 mEffects[i]->setMode(mode);
7327 }
7328}
7329
Eric Laurentcab11242010-07-15 12:50:15 -07007330// setVolume_l() must be called with PlaybackThread::mLock held
7331bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007332{
7333 uint32_t newLeft = *left;
7334 uint32_t newRight = *right;
7335 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007336 int ctrlIdx = -1;
7337 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338
Eric Laurentcab11242010-07-15 12:50:15 -07007339 // first update volume controller
7340 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007341 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007342 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7343 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007344 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007345 break;
7346 }
7347 }
7348
7349 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007350 if (hasControl) {
7351 *left = mNewLeftVolume;
7352 *right = mNewRightVolume;
7353 }
7354 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007355 }
7356
7357 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007358 mLeftVolume = newLeft;
7359 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007360
7361 // second get volume update from volume controller
7362 if (ctrlIdx >= 0) {
7363 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007364 mNewLeftVolume = newLeft;
7365 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007366 }
7367 // then indicate volume to all other effects in chain.
7368 // Pass altered volume to effects before volume controller
7369 // and requested volume to effects after controller
7370 uint32_t lVol = newLeft;
7371 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007372
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007374 if ((int)i == ctrlIdx) continue;
7375 // this also works for ctrlIdx == -1 when there is no volume controller
7376 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007377 lVol = *left;
7378 rVol = *right;
7379 }
7380 mEffects[i]->setVolume(&lVol, &rVol, false);
7381 }
7382 *left = newLeft;
7383 *right = newRight;
7384
7385 return hasControl;
7386}
7387
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7389{
7390 const size_t SIZE = 256;
7391 char buffer[SIZE];
7392 String8 result;
7393
7394 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7395 result.append(buffer);
7396
7397 bool locked = tryLock(mLock);
7398 // failed to lock - AudioFlinger is probably deadlocked
7399 if (!locked) {
7400 result.append("\tCould not lock mutex:\n");
7401 }
7402
Eric Laurentcab11242010-07-15 12:50:15 -07007403 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7404 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007405 mEffects.size(),
7406 (uint32_t)mInBuffer,
7407 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408 mActiveTrackCnt);
7409 result.append(buffer);
7410 write(fd, result.string(), result.size());
7411
7412 for (size_t i = 0; i < mEffects.size(); ++i) {
7413 sp<EffectModule> effect = mEffects[i];
7414 if (effect != 0) {
7415 effect->dump(fd, args);
7416 }
7417 }
7418
7419 if (locked) {
7420 mLock.unlock();
7421 }
7422
7423 return NO_ERROR;
7424}
7425
Eric Laurent59255e42011-07-27 19:49:51 -07007426// must be called with ThreadBase::mLock held
7427void AudioFlinger::EffectChain::setEffectSuspended_l(
7428 const effect_uuid_t *type, bool suspend)
7429{
7430 sp<SuspendedEffectDesc> desc;
7431 // use effect type UUID timelow as key as there is no real risk of identical
7432 // timeLow fields among effect type UUIDs.
7433 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7434 if (suspend) {
7435 if (index >= 0) {
7436 desc = mSuspendedEffects.valueAt(index);
7437 } else {
7438 desc = new SuspendedEffectDesc();
7439 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7440 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007441 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007442 }
7443 if (desc->mRefCount++ == 0) {
7444 sp<EffectModule> effect = getEffectIfEnabled(type);
7445 if (effect != 0) {
7446 desc->mEffect = effect;
7447 effect->setSuspended(true);
7448 effect->setEnabled(false);
7449 }
7450 }
7451 } else {
7452 if (index < 0) {
7453 return;
7454 }
7455 desc = mSuspendedEffects.valueAt(index);
7456 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007457 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007458 desc->mRefCount = 1;
7459 }
7460 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007461 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007462 if (desc->mEffect != 0) {
7463 sp<EffectModule> effect = desc->mEffect.promote();
7464 if (effect != 0) {
7465 effect->setSuspended(false);
7466 sp<EffectHandle> handle = effect->controlHandle();
7467 if (handle != 0) {
7468 effect->setEnabled(handle->enabled());
7469 }
7470 }
7471 desc->mEffect.clear();
7472 }
7473 mSuspendedEffects.removeItemsAt(index);
7474 }
7475 }
7476}
7477
7478// must be called with ThreadBase::mLock held
7479void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7480{
7481 sp<SuspendedEffectDesc> desc;
7482
7483 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7484 if (suspend) {
7485 if (index >= 0) {
7486 desc = mSuspendedEffects.valueAt(index);
7487 } else {
7488 desc = new SuspendedEffectDesc();
7489 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007490 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007491 }
7492 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007493 Vector< sp<EffectModule> > effects;
7494 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007495 for (size_t i = 0; i < effects.size(); i++) {
7496 setEffectSuspended_l(&effects[i]->desc().type, true);
7497 }
7498 }
7499 } else {
7500 if (index < 0) {
7501 return;
7502 }
7503 desc = mSuspendedEffects.valueAt(index);
7504 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007505 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007506 desc->mRefCount = 1;
7507 }
7508 if (--desc->mRefCount == 0) {
7509 Vector<const effect_uuid_t *> types;
7510 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7511 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7512 continue;
7513 }
7514 types.add(&mSuspendedEffects.valueAt(i)->mType);
7515 }
7516 for (size_t i = 0; i < types.size(); i++) {
7517 setEffectSuspended_l(types[i], false);
7518 }
Steve Block3856b092011-10-20 11:56:00 +01007519 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007520 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7521 }
7522 }
7523}
7524
Eric Laurent6bffdb82011-09-23 08:40:41 -07007525
7526// The volume effect is used for automated tests only
7527#ifndef OPENSL_ES_H_
7528static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7529 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7530const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7531#endif //OPENSL_ES_H_
7532
Eric Laurentdb7c0792011-08-10 10:37:50 -07007533bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7534{
7535 // auxiliary effects and visualizer are never suspended on output mix
7536 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7537 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007538 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7539 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007540 return false;
7541 }
7542 return true;
7543}
7544
Glenn Kastend0539712012-01-30 12:56:03 -08007545void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007546{
Glenn Kastend0539712012-01-30 12:56:03 -08007547 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007548 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007549 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7550 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007551 }
Eric Laurent59255e42011-07-27 19:49:51 -07007552 }
Eric Laurent59255e42011-07-27 19:49:51 -07007553}
7554
7555sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7556 const effect_uuid_t *type)
7557{
Glenn Kasten090f0192012-01-30 13:00:02 -08007558 sp<EffectModule> effect = getEffectFromType_l(type);
7559 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007560}
7561
7562void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7563 bool enabled)
7564{
7565 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7566 if (enabled) {
7567 if (index < 0) {
7568 // if the effect is not suspend check if all effects are suspended
7569 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7570 if (index < 0) {
7571 return;
7572 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007573 if (!isEffectEligibleForSuspend(effect->desc())) {
7574 return;
7575 }
Eric Laurent59255e42011-07-27 19:49:51 -07007576 setEffectSuspended_l(&effect->desc().type, enabled);
7577 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007578 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007579 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007580 return;
7581 }
Eric Laurent59255e42011-07-27 19:49:51 -07007582 }
Steve Block3856b092011-10-20 11:56:00 +01007583 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007584 effect->desc().type.timeLow);
7585 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7586 // if effect is requested to suspended but was not yet enabled, supend it now.
7587 if (desc->mEffect == 0) {
7588 desc->mEffect = effect;
7589 effect->setEnabled(false);
7590 effect->setSuspended(true);
7591 }
7592 } else {
7593 if (index < 0) {
7594 return;
7595 }
Steve Block3856b092011-10-20 11:56:00 +01007596 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007597 effect->desc().type.timeLow);
7598 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7599 desc->mEffect.clear();
7600 effect->setSuspended(false);
7601 }
7602}
7603
Mathias Agopian65ab4712010-07-14 17:59:35 -07007604#undef LOG_TAG
7605#define LOG_TAG "AudioFlinger"
7606
7607// ----------------------------------------------------------------------------
7608
7609status_t AudioFlinger::onTransact(
7610 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7611{
7612 return BnAudioFlinger::onTransact(code, data, reply, flags);
7613}
7614
Mathias Agopian65ab4712010-07-14 17:59:35 -07007615}; // namespace android