blob: aaf73ea6a6e89cc91a7f33c5f43745e7c328dfa2 [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
Glenn Kasten23d82a92012-02-03 11:10:00 -0800751 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling pid %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{
Glenn Kasten23d82a92012-02-03 11:10:00 -0800824// ALOGV("getParameters() io %d, keys %s, tid %d, calling pid %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),
Glenn Kastenb28686f2012-01-06 08:39:38 -08001001 mStandby(false), mId(id),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001002 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{
Steve Block3856b092011-10-20 11:56:00 +01001020 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021 {
Glenn Kastenb28686f2012-01-06 08:39:38 -08001022 // This lock prevents the following race in thread (uniprocessor for illustration):
1023 // if (!exitPending()) {
1024 // // context switch from here to exit()
1025 // // exit() calls requestExit(), what exitPending() observes
1026 // // exit() calls signal(), which is dropped since no waiters
1027 // // context switch back from exit() to here
1028 // mWaitWorkCV.wait(...);
1029 // // now thread is hung
1030 // }
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001031 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001032 requestExit();
1033 mWaitWorkCV.signal();
1034 }
Glenn Kastenb28686f2012-01-06 08:39:38 -08001035 // When Thread::requestExitAndWait is made virtual and this method is renamed to
1036 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037 requestExitAndWait();
1038}
1039
Mathias Agopian65ab4712010-07-14 17:59:35 -07001040status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1041{
1042 status_t status;
1043
Steve Block3856b092011-10-20 11:56:00 +01001044 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001045 Mutex::Autolock _l(mLock);
1046
1047 mNewParameters.add(keyValuePairs);
1048 mWaitWorkCV.signal();
1049 // wait condition with timeout in case the thread loop has exited
1050 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001051 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001052 status = mParamStatus;
1053 mWaitWorkCV.signal();
1054 } else {
1055 status = TIMED_OUT;
1056 }
1057 return status;
1058}
1059
1060void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1061{
1062 Mutex::Autolock _l(mLock);
1063 sendConfigEvent_l(event, param);
1064}
1065
1066// sendConfigEvent_l() must be called with ThreadBase::mLock held
1067void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1068{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001069 ConfigEvent configEvent;
1070 configEvent.mEvent = event;
1071 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001073 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mWaitWorkCV.signal();
1075}
1076
1077void AudioFlinger::ThreadBase::processConfigEvents()
1078{
1079 mLock.lock();
1080 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001081 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001082 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001083 mConfigEvents.removeAt(0);
1084 // release mLock before locking AudioFlinger mLock: lock order is always
1085 // AudioFlinger then ThreadBase to avoid cross deadlock
1086 mLock.unlock();
1087 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001088 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001090 mLock.lock();
1091 }
1092 mLock.unlock();
1093}
1094
1095status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1096{
1097 const size_t SIZE = 256;
1098 char buffer[SIZE];
1099 String8 result;
1100
1101 bool locked = tryLock(mLock);
1102 if (!locked) {
1103 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1104 write(fd, buffer, strlen(buffer));
1105 }
1106
1107 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1108 result.append(buffer);
1109 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1114 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001115 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1116 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1118 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001119 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 result.append(buffer);
1121
1122 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1123 result.append(buffer);
1124 result.append(" Index Command");
1125 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1126 snprintf(buffer, SIZE, "\n %02d ", i);
1127 result.append(buffer);
1128 result.append(mNewParameters[i]);
1129 }
1130
1131 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1132 result.append(buffer);
1133 snprintf(buffer, SIZE, " Index event param\n");
1134 result.append(buffer);
1135 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001136 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001137 result.append(buffer);
1138 }
1139 result.append("\n");
1140
1141 write(fd, result.string(), result.size());
1142
1143 if (locked) {
1144 mLock.unlock();
1145 }
1146 return NO_ERROR;
1147}
1148
Eric Laurent1d2bff02011-07-24 17:49:51 -07001149status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1150{
1151 const size_t SIZE = 256;
1152 char buffer[SIZE];
1153 String8 result;
1154
1155 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1156 write(fd, buffer, strlen(buffer));
1157
1158 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1159 sp<EffectChain> chain = mEffectChains[i];
1160 if (chain != 0) {
1161 chain->dump(fd, args);
1162 }
1163 }
1164 return NO_ERROR;
1165}
1166
Eric Laurentfeb0db62011-07-22 09:04:31 -07001167void AudioFlinger::ThreadBase::acquireWakeLock()
1168{
1169 Mutex::Autolock _l(mLock);
1170 acquireWakeLock_l();
1171}
1172
1173void AudioFlinger::ThreadBase::acquireWakeLock_l()
1174{
1175 if (mPowerManager == 0) {
1176 // use checkService() to avoid blocking if power service is not up yet
1177 sp<IBinder> binder =
1178 defaultServiceManager()->checkService(String16("power"));
1179 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001180 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001181 } else {
1182 mPowerManager = interface_cast<IPowerManager>(binder);
1183 binder->linkToDeath(mDeathRecipient);
1184 }
1185 }
1186 if (mPowerManager != 0) {
1187 sp<IBinder> binder = new BBinder();
1188 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1189 binder,
1190 String16(mName));
1191 if (status == NO_ERROR) {
1192 mWakeLockToken = binder;
1193 }
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001195 }
1196}
1197
1198void AudioFlinger::ThreadBase::releaseWakeLock()
1199{
1200 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001201 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001202}
1203
1204void AudioFlinger::ThreadBase::releaseWakeLock_l()
1205{
1206 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001208 if (mPowerManager != 0) {
1209 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1210 }
1211 mWakeLockToken.clear();
1212 }
1213}
1214
1215void AudioFlinger::ThreadBase::clearPowerManager()
1216{
1217 Mutex::Autolock _l(mLock);
1218 releaseWakeLock_l();
1219 mPowerManager.clear();
1220}
1221
1222void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1223{
1224 sp<ThreadBase> thread = mThread.promote();
1225 if (thread != 0) {
1226 thread->clearPowerManager();
1227 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001228 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001229}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001230
Eric Laurent59255e42011-07-27 19:49:51 -07001231void AudioFlinger::ThreadBase::setEffectSuspended(
1232 const effect_uuid_t *type, bool suspend, int sessionId)
1233{
1234 Mutex::Autolock _l(mLock);
1235 setEffectSuspended_l(type, suspend, sessionId);
1236}
1237
1238void AudioFlinger::ThreadBase::setEffectSuspended_l(
1239 const effect_uuid_t *type, bool suspend, int sessionId)
1240{
Glenn Kasten090f0192012-01-30 13:00:02 -08001241 sp<EffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent59255e42011-07-27 19:49:51 -07001242 if (chain != 0) {
1243 if (type != NULL) {
1244 chain->setEffectSuspended_l(type, suspend);
1245 } else {
1246 chain->setEffectSuspendedAll_l(suspend);
1247 }
1248 }
1249
1250 updateSuspendedSessions_l(type, suspend, sessionId);
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1254{
1255 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1256 if (index < 0) {
1257 return;
1258 }
1259
1260 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1261 mSuspendedSessions.editValueAt(index);
1262
1263 for (size_t i = 0; i < sessionEffects.size(); i++) {
1264 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1265 for (int j = 0; j < desc->mRefCount; j++) {
1266 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1267 chain->setEffectSuspendedAll_l(true);
1268 } else {
Steve Block3856b092011-10-20 11:56:00 +01001269 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001270 desc->mType.timeLow);
1271 chain->setEffectSuspended_l(&desc->mType, true);
1272 }
1273 }
1274 }
1275}
1276
Eric Laurent59255e42011-07-27 19:49:51 -07001277void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1278 bool suspend,
1279 int sessionId)
1280{
1281 int index = mSuspendedSessions.indexOfKey(sessionId);
1282
1283 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1284
1285 if (suspend) {
1286 if (index >= 0) {
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 } else {
1289 mSuspendedSessions.add(sessionId, sessionEffects);
1290 }
1291 } else {
1292 if (index < 0) {
1293 return;
1294 }
1295 sessionEffects = mSuspendedSessions.editValueAt(index);
1296 }
1297
1298
1299 int key = EffectChain::kKeyForSuspendAll;
1300 if (type != NULL) {
1301 key = type->timeLow;
1302 }
1303 index = sessionEffects.indexOfKey(key);
1304
1305 sp <SuspendedSessionDesc> desc;
1306 if (suspend) {
1307 if (index >= 0) {
1308 desc = sessionEffects.valueAt(index);
1309 } else {
1310 desc = new SuspendedSessionDesc();
1311 if (type != NULL) {
1312 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1313 }
1314 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001316 }
1317 desc->mRefCount++;
1318 } else {
1319 if (index < 0) {
1320 return;
1321 }
1322 desc = sessionEffects.valueAt(index);
1323 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001324 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001325 sessionEffects.removeItemsAt(index);
1326 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001328 sessionId);
1329 mSuspendedSessions.removeItem(sessionId);
1330 }
1331 }
1332 }
1333 if (!sessionEffects.isEmpty()) {
1334 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1335 }
1336}
1337
1338void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1339 bool enabled,
1340 int sessionId)
1341{
1342 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001343 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1344}
Eric Laurent59255e42011-07-27 19:49:51 -07001345
Eric Laurenta85a74a2011-10-19 11:44:54 -07001346void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1347 bool enabled,
1348 int sessionId)
1349{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001350 if (mType != RECORD) {
1351 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1352 // another session. This gives the priority to well behaved effect control panels
1353 // and applications not using global effects.
1354 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1355 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1356 }
1357 }
Eric Laurent59255e42011-07-27 19:49:51 -07001358
1359 sp<EffectChain> chain = getEffectChain_l(sessionId);
1360 if (chain != 0) {
1361 chain->checkSuspendOnEffectEnabled(effect, enabled);
1362 }
1363}
1364
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365// ----------------------------------------------------------------------------
1366
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001367AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1368 AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001369 audio_io_handle_t id,
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001370 uint32_t device,
1371 type_t type)
1372 : ThreadBase(audioFlinger, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001373 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0),
1374 // Assumes constructor is called by AudioFlinger with it's mLock held,
1375 // but it would be safer to explicitly pass initial masterMute as parameter
1376 mMasterMute(audioFlinger->masterMute_l()),
1377 // mStreamTypes[] initialized in constructor body
1378 mOutput(output),
1379 // Assumes constructor is called by AudioFlinger with it's mLock held,
1380 // but it would be safer to explicitly pass initial masterVolume as parameter
1381 mMasterVolume(audioFlinger->masterVolume_l()),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001382 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001384 snprintf(mName, kNameLength, "AudioOut_%d", id);
1385
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 readOutputParameters();
1387
Glenn Kasten263709e2012-01-06 08:40:01 -08001388 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001389 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1390 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1391 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001392 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1393 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001394 // initialized by stream_type_t default constructor
1395 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001396 }
1397}
1398
1399AudioFlinger::PlaybackThread::~PlaybackThread()
1400{
1401 delete [] mMixBuffer;
1402}
1403
1404status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1405{
1406 dumpInternals(fd, args);
1407 dumpTracks(fd, args);
1408 dumpEffectChains(fd, args);
1409 return NO_ERROR;
1410}
1411
1412status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1413{
1414 const size_t SIZE = 256;
1415 char buffer[SIZE];
1416 String8 result;
1417
1418 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1419 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001420 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 -07001421 for (size_t i = 0; i < mTracks.size(); ++i) {
1422 sp<Track> track = mTracks[i];
1423 if (track != 0) {
1424 track->dump(buffer, SIZE);
1425 result.append(buffer);
1426 }
1427 }
1428
1429 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1430 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001431 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 -07001432 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Glenn Kasten77c11192012-01-25 14:27:41 -08001433 sp<Track> track = mActiveTracks[i].promote();
1434 if (track != 0) {
1435 track->dump(buffer, SIZE);
1436 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 }
1438 }
1439 write(fd, result.string(), result.size());
1440 return NO_ERROR;
1441}
1442
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1444{
1445 const size_t SIZE = 256;
1446 char buffer[SIZE];
1447 String8 result;
1448
1449 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1456 result.append(buffer);
1457 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1458 result.append(buffer);
1459 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1460 result.append(buffer);
1461 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1462 result.append(buffer);
1463 write(fd, result.string(), result.size());
1464
1465 dumpBase(fd, args);
1466
1467 return NO_ERROR;
1468}
1469
1470// Thread virtuals
1471status_t AudioFlinger::PlaybackThread::readyToRun()
1472{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001473 status_t status = initCheck();
1474 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001475 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001476 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001477 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001479 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480}
1481
1482void AudioFlinger::PlaybackThread::onFirstRef()
1483{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001484 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485}
1486
1487// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1488sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1489 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001490 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08001492 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001493 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001494 int frameCount,
1495 const sp<IMemory>& sharedBuffer,
1496 int sessionId,
1497 status_t *status)
1498{
1499 sp<Track> track;
1500 status_t lStatus;
1501
1502 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001503 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1504 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001505 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001506 "for output %p with format %d",
1507 sampleRate, format, channelMask, mOutput, mFormat);
1508 lStatus = BAD_VALUE;
1509 goto Exit;
1510 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001511 }
1512 } else {
1513 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1514 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001515 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 lStatus = BAD_VALUE;
1517 goto Exit;
1518 }
1519 }
1520
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001521 lStatus = initCheck();
1522 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001523 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524 goto Exit;
1525 }
1526
1527 { // scope for mLock
1528 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001529
1530 // all tracks in same audio session must share the same routing strategy otherwise
1531 // conflicts will happen when tracks are moved from one output to another by audio policy
1532 // manager
Glenn Kasten02bbd202012-02-08 12:35:35 -08001533 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001534 for (size_t i = 0; i < mTracks.size(); ++i) {
1535 sp<Track> t = mTracks[i];
1536 if (t != 0) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001537 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
Glenn Kastend8796012011-10-28 10:31:42 -07001538 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001539 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001540 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001541 lStatus = BAD_VALUE;
1542 goto Exit;
1543 }
1544 }
1545 }
1546
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001548 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549 if (track->getCblk() == NULL || track->name() < 0) {
1550 lStatus = NO_MEMORY;
1551 goto Exit;
1552 }
1553 mTracks.add(track);
1554
1555 sp<EffectChain> chain = getEffectChain_l(sessionId);
1556 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001557 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 track->setMainBuffer(chain->inBuffer());
Glenn Kasten02bbd202012-02-08 12:35:35 -08001559 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
Eric Laurentb469b942011-05-09 12:09:06 -07001560 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001562
1563 // invalidate track immediately if the stream type was moved to another thread since
1564 // createTrack() was called by the client process.
1565 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001566 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001567 this, streamType);
1568 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 }
1571 lStatus = NO_ERROR;
1572
1573Exit:
1574 if(status) {
1575 *status = lStatus;
1576 }
1577 return track;
1578}
1579
1580uint32_t AudioFlinger::PlaybackThread::latency() const
1581{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001582 Mutex::Autolock _l(mLock);
1583 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001584 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001585 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001586 return 0;
1587 }
1588}
1589
1590status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1591{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 mMasterVolume = value;
1593 return NO_ERROR;
1594}
1595
1596status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1597{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 mMasterMute = muted;
1599 return NO_ERROR;
1600}
1601
Glenn Kastenfff6d712012-01-12 16:38:12 -08001602status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001603{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 mStreamTypes[stream].volume = value;
1605 return NO_ERROR;
1606}
1607
Glenn Kastenfff6d712012-01-12 16:38:12 -08001608status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 mStreamTypes[stream].mute = muted;
1611 return NO_ERROR;
1612}
1613
Glenn Kastenfff6d712012-01-12 16:38:12 -08001614float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615{
1616 return mStreamTypes[stream].volume;
1617}
1618
Glenn Kastenfff6d712012-01-12 16:38:12 -08001619bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620{
1621 return mStreamTypes[stream].mute;
1622}
1623
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624// addTrack_l() must be called with ThreadBase::mLock held
1625status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1626{
1627 status_t status = ALREADY_EXISTS;
1628
1629 // set retry count for buffer fill
1630 track->mRetryCount = kMaxTrackStartupRetries;
1631 if (mActiveTracks.indexOf(track) < 0) {
1632 // the track is newly added, make sure it fills up all its
1633 // buffers before playing. This is to ensure the client will
1634 // effectively get the latency it requested.
1635 track->mFillingUpStatus = Track::FS_FILLING;
1636 track->mResetDone = false;
1637 mActiveTracks.add(track);
1638 if (track->mainBuffer() != mMixBuffer) {
1639 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1640 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001641 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001642 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 }
1644 }
1645
1646 status = NO_ERROR;
1647 }
1648
Steve Block3856b092011-10-20 11:56:00 +01001649 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 mWaitWorkCV.broadcast();
1651
1652 return status;
1653}
1654
1655// destroyTrack_l() must be called with ThreadBase::mLock held
1656void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1657{
1658 track->mState = TrackBase::TERMINATED;
1659 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001660 removeTrack_l(track);
1661 }
1662}
1663
1664void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1665{
1666 mTracks.remove(track);
1667 deleteTrackName_l(track->name());
1668 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1669 if (chain != 0) {
1670 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 }
1672}
1673
1674String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1675{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001676 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001677 char *s;
1678
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001679 Mutex::Autolock _l(mLock);
1680 if (initCheck() != NO_ERROR) {
1681 return out_s8;
1682 }
1683
Dima Zavin799a70e2011-04-18 16:57:27 -07001684 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001685 out_s8 = String8(s);
1686 free(s);
1687 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688}
1689
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001690// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1692 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08001693 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001694
Steve Block3856b092011-10-20 11:56:00 +01001695 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696
1697 switch (event) {
1698 case AudioSystem::OUTPUT_OPENED:
1699 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001700 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 desc.samplingRate = mSampleRate;
1702 desc.format = mFormat;
1703 desc.frameCount = mFrameCount;
1704 desc.latency = latency();
1705 param2 = &desc;
1706 break;
1707
1708 case AudioSystem::STREAM_CONFIG_CHANGED:
1709 param2 = &param;
1710 case AudioSystem::OUTPUT_CLOSED:
1711 default:
1712 break;
1713 }
1714 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1715}
1716
1717void AudioFlinger::PlaybackThread::readOutputParameters()
1718{
Dima Zavin799a70e2011-04-18 16:57:27 -07001719 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001720 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1721 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001722 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001723 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001724 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725
1726 // FIXME - Current mixer implementation only supports stereo output: Always
1727 // Allocate a stereo buffer even if HW output is mono.
Glenn Kastene9dd0172012-01-27 18:08:45 -08001728 delete[] mMixBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001729 mMixBuffer = new int16_t[mFrameCount * 2];
1730 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1731
Eric Laurentde070132010-07-13 04:45:46 -07001732 // force reconfiguration of effect chains and engines to take new buffer size and audio
1733 // parameters into account
1734 // Note that mLock is not held when readOutputParameters() is called from the constructor
1735 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1736 // matter.
1737 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1738 Vector< sp<EffectChain> > effectChains = mEffectChains;
1739 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001740 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742}
1743
1744status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1745{
Glenn Kastena0d68332012-01-27 16:47:15 -08001746 if (halFrames == NULL || dspFrames == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747 return BAD_VALUE;
1748 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001749 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001750 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 return INVALID_OPERATION;
1752 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001753 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754
Dima Zavin799a70e2011-04-18 16:57:27 -07001755 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756}
1757
Eric Laurent39e94f82010-07-28 01:32:47 -07001758uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759{
1760 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001761 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001763 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 }
1765
1766 for (size_t i = 0; i < mTracks.size(); ++i) {
1767 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001768 if (sessionId == track->sessionId() &&
1769 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001770 result |= TRACK_SESSION;
1771 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 }
1773 }
1774
Eric Laurent39e94f82010-07-28 01:32:47 -07001775 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776}
1777
Eric Laurentde070132010-07-13 04:45:46 -07001778uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1779{
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001781 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001782 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1783 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001784 }
1785 for (size_t i = 0; i < mTracks.size(); i++) {
1786 sp<Track> track = mTracks[i];
1787 if (sessionId == track->sessionId() &&
1788 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08001789 return AudioSystem::getStrategyForStream(track->streamType());
Eric Laurentde070132010-07-13 04:45:46 -07001790 }
1791 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001792 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001793}
1794
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795
Glenn Kastenaed850d2012-01-26 09:46:34 -08001796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001797{
1798 Mutex::Autolock _l(mLock);
1799 return mOutput;
1800}
1801
1802AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1803{
1804 Mutex::Autolock _l(mLock);
1805 AudioStreamOut *output = mOutput;
1806 mOutput = NULL;
1807 return output;
1808}
1809
1810// this method must always be called either with ThreadBase mLock held or inside the thread loop
1811audio_stream_t* AudioFlinger::PlaybackThread::stream()
1812{
1813 if (mOutput == NULL) {
1814 return NULL;
1815 }
1816 return &mOutput->stream->common;
1817}
1818
Eric Laurent162b40b2011-12-05 09:47:19 -08001819uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1820{
1821 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1822 // decoding and transfer time. So sleeping for half of the latency would likely cause
1823 // underruns
1824 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1825 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1826 } else {
1827 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1828 }
1829}
1830
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831// ----------------------------------------------------------------------------
1832
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001833AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08001834 audio_io_handle_t id, uint32_t device, type_t type)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08001835 : PlaybackThread(audioFlinger, output, id, device, type),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08001836 mAudioMixer(new AudioMixer(mFrameCount, mSampleRate)),
1837 mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 // FIXME - Current mixer implementation only supports stereo output
1840 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001841 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 }
1843}
1844
1845AudioFlinger::MixerThread::~MixerThread()
1846{
1847 delete mAudioMixer;
1848}
1849
1850bool AudioFlinger::MixerThread::threadLoop()
1851{
1852 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08001853 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854 nsecs_t standbyTime = systemTime();
1855 size_t mixBufferSize = mFrameCount * mFrameSize;
1856 // FIXME: Relaxed timing because of a certain device that can't meet latency
1857 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001858 // increase threshold again due to low power audio mode. The way this warning threshold is
1859 // calculated and its usefulness should be reconsidered anyway.
1860 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001861 nsecs_t lastWarning = 0;
1862 bool longStandbyExit = false;
1863 uint32_t activeSleepTime = activeSleepTimeUs();
1864 uint32_t idleSleepTime = idleSleepTimeUs();
1865 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001866 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001868#ifdef DEBUG_CPU_USAGE
1869 ThreadCpuUsage cpu;
1870 const CentralTendencyStatistics& stats = cpu.statistics();
1871#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872
Eric Laurentfeb0db62011-07-22 09:04:31 -07001873 acquireWakeLock();
1874
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 while (!exitPending())
1876 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001877#ifdef DEBUG_CPU_USAGE
1878 cpu.sampleAndEnable();
1879 unsigned n = stats.n();
1880 // cpu.elapsed() is expensive, so don't call it every loop
1881 if ((n & 127) == 1) {
1882 long long elapsed = cpu.elapsed();
1883 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1884 double perLoop = elapsed / (double) n;
1885 double perLoop100 = perLoop * 0.01;
1886 double mean = stats.mean();
1887 double stddev = stats.stddev();
1888 double minimum = stats.minimum();
1889 double maximum = stats.maximum();
1890 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001891 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 -07001892 elapsed * .000000001, n, perLoop * .000001,
1893 mean * .001,
1894 stddev * .001,
1895 minimum * .001,
1896 maximum * .001,
1897 mean / perLoop100,
1898 stddev / perLoop100,
1899 minimum / perLoop100,
1900 maximum / perLoop100);
1901 }
1902 }
1903#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 processConfigEvents();
1905
1906 mixerStatus = MIXER_IDLE;
1907 { // scope for mLock
1908
1909 Mutex::Autolock _l(mLock);
1910
1911 if (checkForNewParameters_l()) {
1912 mixBufferSize = mFrameCount * mFrameSize;
1913 // FIXME: Relaxed timing because of a certain device that can't meet latency
1914 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001915 // increase threshold again due to low power audio mode. The way this warning
1916 // threshold is calculated and its usefulness should be reconsidered anyway.
1917 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918 activeSleepTime = activeSleepTimeUs();
1919 idleSleepTime = idleSleepTimeUs();
1920 }
1921
1922 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1923
1924 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001925 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1926 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08001928 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001929 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 mStandby = true;
1931 mBytesWritten = 0;
1932 }
1933
1934 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1935 // we're about to wait, flush the binder command buffer
1936 IPCThreadState::self()->flushCommands();
1937
1938 if (exitPending()) break;
1939
Eric Laurentfeb0db62011-07-22 09:04:31 -07001940 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001941 // wait until we have something to do...
Glenn Kasten90bebef2012-01-27 15:24:38 -08001942 ALOGV("MixerThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001943 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08001944 ALOGV("MixerThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001945 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946
Eric Laurent27741442012-01-17 19:20:12 -08001947 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08001948 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 char value[PROPERTY_VALUE_MAX];
1950 property_get("ro.audio.silent", value, "0");
1951 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001952 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001953 setMasterMute(true);
1954 }
1955 }
1956
1957 standbyTime = systemTime() + kStandbyTimeInNsecs;
1958 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001959 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001960 continue;
1961 }
1962 }
1963
1964 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1965
1966 // prevent any changes in effect chain list and in each effect chain
1967 // during mixing and effect process as the audio buffers could be deleted
1968 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001969 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971
Glenn Kastenf6b16782011-12-15 09:51:17 -08001972 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001973 // mix buffers...
1974 mAudioMixer->process();
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001975 // increase sleep time progressively when application underrun condition clears.
1976 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
1977 // that a steady state of alternating ready/not ready conditions keeps the sleep time
1978 // such that we would underrun the audio HAL.
1979 if ((sleepTime == 0) && (sleepTimeShift > 0)) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001980 sleepTimeShift--;
1981 }
Eric Laurent21e4b6e2012-01-23 18:56:59 -08001982 sleepTime = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 standbyTime = systemTime() + kStandbyTimeInNsecs;
1984 //TODO: delay standby when effects have a tail
1985 } else {
1986 // If no tracks are ready, sleep once for the duration of an output
1987 // buffer size, then write 0s to the output
1988 if (sleepTime == 0) {
1989 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001990 sleepTime = activeSleepTime >> sleepTimeShift;
1991 if (sleepTime < kMinThreadSleepTimeUs) {
1992 sleepTime = kMinThreadSleepTimeUs;
1993 }
1994 // reduce sleep time in case of consecutive application underruns to avoid
1995 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1996 // duration we would end up writing less data than needed by the audio HAL if
1997 // the condition persists.
1998 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1999 sleepTimeShift++;
2000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 } else {
2002 sleepTime = idleSleepTime;
2003 }
2004 } else if (mBytesWritten != 0 ||
2005 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2006 memset (mMixBuffer, 0, mixBufferSize);
2007 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002008 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009 }
2010 // TODO add standby time extension fct of effect tail
2011 }
2012
2013 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002014 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 }
2016 // sleepTime == 0 means we must write to audio hardware
2017 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002018 for (size_t i = 0; i < effectChains.size(); i ++) {
2019 effectChains[i]->process_l();
2020 }
2021 // enable changes in effect chain
2022 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 mLastWriteTime = systemTime();
2024 mInWrite = true;
2025 mBytesWritten += mixBufferSize;
2026
Dima Zavin799a70e2011-04-18 16:57:27 -07002027 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2029 mNumWrites++;
2030 mInWrite = false;
2031 nsecs_t now = systemTime();
2032 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002033 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002034 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002035 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002036 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 ns2ms(delta), mNumDelayedWrites, this);
2038 lastWarning = now;
2039 }
2040 if (mStandby) {
2041 longStandbyExit = true;
2042 }
2043 }
2044 mStandby = false;
2045 } else {
2046 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002047 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048 usleep(sleepTime);
2049 }
2050
2051 // finally let go of all our tracks, without the lock held
2052 // since we can't guarantee the destructors won't acquire that
2053 // same lock.
2054 tracksToRemove.clear();
2055
2056 // Effect chains will be actually deleted here if they were removed from
2057 // mEffectChains list during mixing or effects processing
2058 effectChains.clear();
2059 }
2060
2061 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002062 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002063 }
2064
Eric Laurentfeb0db62011-07-22 09:04:31 -07002065 releaseWakeLock();
2066
Steve Block3856b092011-10-20 11:56:00 +01002067 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 return false;
2069}
2070
2071// prepareTracks_l() must be called with ThreadBase::mLock held
Glenn Kasten29c23c32012-01-26 13:37:52 -08002072AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
2073 const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002074{
2075
Glenn Kasten29c23c32012-01-26 13:37:52 -08002076 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 // find out which tracks need to be processed
2078 size_t count = activeTracks.size();
2079 size_t mixedTracks = 0;
2080 size_t tracksWithEffect = 0;
2081
2082 float masterVolume = mMasterVolume;
2083 bool masterMute = mMasterMute;
2084
Eric Laurent571d49c2010-08-11 05:20:11 -07002085 if (masterMute) {
2086 masterVolume = 0;
2087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002089 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002091 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002092 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 masterVolume = (float)((v + (1 << 23)) >> 24);
2094 chain.clear();
2095 }
2096
2097 for (size_t i=0 ; i<count ; i++) {
2098 sp<Track> t = activeTracks[i].promote();
2099 if (t == 0) continue;
2100
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002101 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 Track* const track = t.get();
2103 audio_track_cblk_t* cblk = track->cblk();
2104
2105 // The first time a track is added we wait
2106 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002107 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002108 // make sure that we have enough frames to mix one full buffer.
2109 // enforce this condition only once to enable draining the buffer in case the client
2110 // app does not call stop() and relies on underrun to stop:
Eric Laurent27741442012-01-17 19:20:12 -08002111 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002112 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002113 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002114 if (!track->isStopped() && !track->isPausing() &&
Eric Laurent27741442012-01-17 19:20:12 -08002115 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002116 if (t->sampleRate() == (int)mSampleRate) {
2117 minFrames = mFrameCount;
2118 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002119 // +1 for rounding and +1 for additional sample needed for interpolation
2120 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2121 // add frames already consumed but not yet released by the resampler
2122 // because cblk->framesReady() will include these frames
2123 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2124 // the minimum track buffer size is normally twice the number of frames necessary
2125 // to fill one buffer and the resampler should not leave more than one buffer worth
2126 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002127 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002128 }
2129 }
2130 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002131 !track->isPaused() && !track->isTerminated())
2132 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002133 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134
2135 mixedTracks++;
2136
2137 // track->mainBuffer() != mMixBuffer means there is an effect chain
2138 // connected to the track
2139 chain.clear();
2140 if (track->mainBuffer() != mMixBuffer) {
2141 chain = getEffectChain_l(track->sessionId());
2142 // Delegate volume control to effect in track effect chain if needed
2143 if (chain != 0) {
2144 tracksWithEffect++;
2145 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002146 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002147 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002148 }
2149 }
2150
2151
2152 int param = AudioMixer::VOLUME;
2153 if (track->mFillingUpStatus == Track::FS_FILLED) {
2154 // no ramp for the first volume setting
2155 track->mFillingUpStatus = Track::FS_ACTIVE;
2156 if (track->mState == TrackBase::RESUMING) {
2157 track->mState = TrackBase::ACTIVE;
2158 param = AudioMixer::RAMP_VOLUME;
2159 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002160 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 } else if (cblk->server != 0) {
2162 // If the track is stopped before the first frame was mixed,
2163 // do not apply ramp
2164 param = AudioMixer::RAMP_VOLUME;
2165 }
2166
2167 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002168 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002169 if (track->isMuted() || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002170 mStreamTypes[track->streamType()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002171 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 if (track->isPausing()) {
2173 track->setPaused();
2174 }
2175 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002176
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177 // read original volumes with volume control
Glenn Kasten02bbd202012-02-08 12:35:35 -08002178 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 float v = masterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002180 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002181 vl = vlr & 0xFFFF;
2182 vr = vlr >> 16;
2183 // track volumes come from shared memory, so can't be trusted and must be clamped
2184 if (vl > MAX_GAIN_INT) {
2185 ALOGV("Track left volume out of range: %04X", vl);
2186 vl = MAX_GAIN_INT;
2187 }
2188 if (vr > MAX_GAIN_INT) {
2189 ALOGV("Track right volume out of range: %04X", vr);
2190 vr = MAX_GAIN_INT;
2191 }
2192 // now apply the master volume and stream type volume
2193 vl = (uint32_t)(v * vl) << 12;
2194 vr = (uint32_t)(v * vr) << 12;
2195 // assuming master volume and stream type volume each go up to 1.0,
2196 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002197
Glenn Kasten05632a52012-01-03 14:22:33 -08002198 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2199 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002200 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002201 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002202 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002203 }
2204 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002206 // Delegate volume control to effect in track effect chain if needed
2207 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2208 // Do not ramp volume if volume is controlled by effect
2209 param = AudioMixer::VOLUME;
2210 track->mHasVolumeController = true;
2211 } else {
2212 // force no volume ramp when volume controller was just disabled or removed
2213 // from effect chain to avoid volume spike
2214 if (track->mHasVolumeController) {
2215 param = AudioMixer::VOLUME;
2216 }
2217 track->mHasVolumeController = false;
2218 }
2219
2220 // Convert volumes from 8.24 to 4.12 format
2221 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002222 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002223 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2224 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2225 left = int16_t(v_clamped);
2226 v_clamped = (vr + (1 << 11)) >> 12;
2227 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2228 right = int16_t(v_clamped);
2229
2230 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2231 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002234 mAudioMixer->setBufferProvider(name, track);
2235 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002237 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2238 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2239 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002241 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002242 AudioMixer::TRACK,
2243 AudioMixer::FORMAT, (void *)track->format());
2244 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002245 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002247 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002248 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002249 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 AudioMixer::RESAMPLE,
2251 AudioMixer::SAMPLE_RATE,
2252 (void *)(cblk->sampleRate));
2253 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002254 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 AudioMixer::TRACK,
2256 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2257 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002258 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 AudioMixer::TRACK,
2260 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2261
2262 // reset retry count
2263 track->mRetryCount = kMaxTrackRetries;
Eric Laurent27741442012-01-17 19:20:12 -08002264 // If one track is ready, set the mixer ready if:
2265 // - the mixer was not ready during previous round OR
2266 // - no other track is not ready
2267 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2268 mixerStatus != MIXER_TRACKS_ENABLED) {
2269 mixerStatus = MIXER_TRACKS_READY;
2270 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002272 //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 -07002273 if (track->isStopped()) {
2274 track->reset();
2275 }
2276 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2277 // We have consumed all the buffers of this track.
2278 // Remove it from the list of active tracks.
2279 tracksToRemove->add(track);
2280 } else {
2281 // No buffers for this track. Give it a few chances to
2282 // fill a buffer, then remove it from active list.
2283 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002284 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002286 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002287 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurent27741442012-01-17 19:20:12 -08002288 // If one track is not ready, mark the mixer also not ready if:
2289 // - the mixer was ready during previous round OR
2290 // - no other track is ready
2291 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2292 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 mixerStatus = MIXER_TRACKS_ENABLED;
2294 }
2295 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002296 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 }
2298 }
2299
2300 // remove all the tracks that need to be...
2301 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002302 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 for (size_t i=0 ; i<count ; i++) {
2304 const sp<Track>& track = tracksToRemove->itemAt(i);
2305 mActiveTracks.remove(track);
2306 if (track->mainBuffer() != mMixBuffer) {
2307 chain = getEffectChain_l(track->sessionId());
2308 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002309 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002310 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 }
2312 }
2313 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002314 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 }
2316 }
2317 }
2318
2319 // mix buffer must be cleared if all tracks are connected to an
2320 // effect chain as in this case the mixer will not write to
2321 // mix buffer and track effects will accumulate into it
2322 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2323 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2324 }
2325
Eric Laurent27741442012-01-17 19:20:12 -08002326 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 return mixerStatus;
2328}
2329
Glenn Kastenfff6d712012-01-12 16:38:12 -08002330void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331{
Steve Block3856b092011-10-20 11:56:00 +01002332 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002333 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002335
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 size_t size = mTracks.size();
2337 for (size_t i = 0; i < size; i++) {
2338 sp<Track> t = mTracks[i];
Glenn Kasten02bbd202012-02-08 12:35:35 -08002339 if (t->streamType() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002340 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002341 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 }
2343 }
2344}
2345
Glenn Kastenfff6d712012-01-12 16:38:12 -08002346void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002347{
Steve Block3856b092011-10-20 11:56:00 +01002348 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002349 this, streamType, valid);
2350 Mutex::Autolock _l(mLock);
2351
2352 mStreamTypes[streamType].valid = valid;
2353}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002354
2355// getTrackName_l() must be called with ThreadBase::mLock held
2356int AudioFlinger::MixerThread::getTrackName_l()
2357{
2358 return mAudioMixer->getTrackName();
2359}
2360
2361// deleteTrackName_l() must be called with ThreadBase::mLock held
2362void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2363{
Steve Block3856b092011-10-20 11:56:00 +01002364 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 mAudioMixer->deleteTrackName(name);
2366}
2367
2368// checkForNewParameters_l() must be called with ThreadBase::mLock held
2369bool AudioFlinger::MixerThread::checkForNewParameters_l()
2370{
2371 bool reconfig = false;
2372
2373 while (!mNewParameters.isEmpty()) {
2374 status_t status = NO_ERROR;
2375 String8 keyValuePair = mNewParameters[0];
2376 AudioParameter param = AudioParameter(keyValuePair);
2377 int value;
2378
2379 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2380 reconfig = true;
2381 }
2382 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08002383 if ((audio_format_t) value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 status = BAD_VALUE;
2385 } else {
2386 reconfig = true;
2387 }
2388 }
2389 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002390 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391 status = BAD_VALUE;
2392 } else {
2393 reconfig = true;
2394 }
2395 }
2396 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2397 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002398 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399 // if frame count is changed after track creation
2400 if (!mTracks.isEmpty()) {
2401 status = INVALID_OPERATION;
2402 } else {
2403 reconfig = true;
2404 }
2405 }
2406 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002407 // when changing the audio output device, call addBatteryData to notify
2408 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002409 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002410 uint32_t params = 0;
2411 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002412 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002413 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2414 }
2415
2416 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002417 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002418 // check if any other device (except speaker) is on
2419 if (value & deviceWithoutSpeaker ) {
2420 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2421 }
2422
2423 if (params != 0) {
2424 addBatteryData(params);
2425 }
2426 }
2427
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 // forward device change to effects that have requested to be
2429 // aware of attached audio device.
2430 mDevice = (uint32_t)value;
2431 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002432 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 }
2434 }
2435
2436 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002437 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002438 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002440 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 mStandby = true;
2442 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002443 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002444 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445 }
2446 if (status == NO_ERROR && reconfig) {
2447 delete mAudioMixer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08002448 // for safety in case readOutputParameters() accesses mAudioMixer (it doesn't)
2449 mAudioMixer = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450 readOutputParameters();
2451 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2452 for (size_t i = 0; i < mTracks.size() ; i++) {
2453 int name = getTrackName_l();
2454 if (name < 0) break;
2455 mTracks[i]->mName = name;
2456 // limit track sample rate to 2 x new output sample rate
2457 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2458 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2459 }
2460 }
2461 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2462 }
2463 }
2464
2465 mNewParameters.removeAt(0);
2466
2467 mParamStatus = status;
2468 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002469 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2470 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002471 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 }
2473 return reconfig;
2474}
2475
2476status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2477{
2478 const size_t SIZE = 256;
2479 char buffer[SIZE];
2480 String8 result;
2481
2482 PlaybackThread::dumpInternals(fd, args);
2483
2484 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2485 result.append(buffer);
2486 write(fd, result.string(), result.size());
2487 return NO_ERROR;
2488}
2489
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2491{
Eric Laurent60e18242010-07-29 06:50:24 -07002492 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493}
2494
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002495uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2496{
2497 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2498}
2499
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500// ----------------------------------------------------------------------------
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002501AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
2502 AudioStreamOut* output, audio_io_handle_t id, uint32_t device)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002503 : PlaybackThread(audioFlinger, output, id, device, DIRECT)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08002504 // mLeftVolFloat, mRightVolFloat
2505 // mLeftVolShort, mRightVolShort
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002507}
2508
2509AudioFlinger::DirectOutputThread::~DirectOutputThread()
2510{
2511}
2512
Mathias Agopian65ab4712010-07-14 17:59:35 -07002513void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2514{
2515 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002516 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002517 return;
2518 }
2519
2520 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002521 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522 size_t count = mFrameCount * mChannelCount;
2523 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2524 int16_t *dst = mMixBuffer + count-1;
2525 while(count--) {
2526 *dst-- = (int16_t)(*src--^0x80) << 8;
2527 }
2528 }
2529
2530 size_t frameCount = mFrameCount;
2531 int16_t *out = mMixBuffer;
2532 if (ramp) {
2533 if (mChannelCount == 1) {
2534 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2535 int32_t vlInc = d / (int32_t)frameCount;
2536 int32_t vl = ((int32_t)mLeftVolShort << 16);
2537 do {
2538 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2539 out++;
2540 vl += vlInc;
2541 } while (--frameCount);
2542
2543 } else {
2544 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2545 int32_t vlInc = d / (int32_t)frameCount;
2546 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2547 int32_t vrInc = d / (int32_t)frameCount;
2548 int32_t vl = ((int32_t)mLeftVolShort << 16);
2549 int32_t vr = ((int32_t)mRightVolShort << 16);
2550 do {
2551 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2552 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2553 out += 2;
2554 vl += vlInc;
2555 vr += vrInc;
2556 } while (--frameCount);
2557 }
2558 } else {
2559 if (mChannelCount == 1) {
2560 do {
2561 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2562 out++;
2563 } while (--frameCount);
2564 } else {
2565 do {
2566 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2567 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2568 out += 2;
2569 } while (--frameCount);
2570 }
2571 }
2572
2573 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002574 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002575 size_t count = mFrameCount * mChannelCount;
2576 int16_t *src = mMixBuffer;
2577 uint8_t *dst = (uint8_t *)mMixBuffer;
2578 while(count--) {
2579 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2580 }
2581 }
2582
2583 mLeftVolShort = leftVol;
2584 mRightVolShort = rightVol;
2585}
2586
2587bool AudioFlinger::DirectOutputThread::threadLoop()
2588{
Glenn Kasten29c23c32012-01-26 13:37:52 -08002589 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002590 sp<Track> trackToRemove;
2591 sp<Track> activeTrack;
2592 nsecs_t standbyTime = systemTime();
2593 int8_t *curBuf;
2594 size_t mixBufferSize = mFrameCount*mFrameSize;
2595 uint32_t activeSleepTime = activeSleepTimeUs();
2596 uint32_t idleSleepTime = idleSleepTimeUs();
2597 uint32_t sleepTime = idleSleepTime;
2598 // use shorter standby delay as on normal output to release
2599 // hardware resources as soon as possible
2600 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2601
Eric Laurentfeb0db62011-07-22 09:04:31 -07002602 acquireWakeLock();
2603
Mathias Agopian65ab4712010-07-14 17:59:35 -07002604 while (!exitPending())
2605 {
2606 bool rampVolume;
2607 uint16_t leftVol;
2608 uint16_t rightVol;
2609 Vector< sp<EffectChain> > effectChains;
2610
2611 processConfigEvents();
2612
2613 mixerStatus = MIXER_IDLE;
2614
2615 { // scope for the mLock
2616
2617 Mutex::Autolock _l(mLock);
2618
2619 if (checkForNewParameters_l()) {
2620 mixBufferSize = mFrameCount*mFrameSize;
2621 activeSleepTime = activeSleepTimeUs();
2622 idleSleepTime = idleSleepTimeUs();
2623 standbyDelay = microseconds(activeSleepTime*2);
2624 }
2625
2626 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002627 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2628 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002629 // wait until we have something to do...
2630 if (!mStandby) {
Glenn Kasten90bebef2012-01-27 15:24:38 -08002631 ALOGV("Audio hardware entering standby, mixer %p", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002632 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002633 mStandby = true;
2634 mBytesWritten = 0;
2635 }
2636
2637 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2638 // we're about to wait, flush the binder command buffer
2639 IPCThreadState::self()->flushCommands();
2640
2641 if (exitPending()) break;
2642
Eric Laurentfeb0db62011-07-22 09:04:31 -07002643 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08002644 ALOGV("DirectOutputThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08002646 ALOGV("DirectOutputThread %p TID %d waking up in active mode", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002647 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002648
Glenn Kastenf1d45922012-01-13 15:54:24 -08002649 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 char value[PROPERTY_VALUE_MAX];
2651 property_get("ro.audio.silent", value, "0");
2652 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002653 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654 setMasterMute(true);
2655 }
2656 }
2657
2658 standbyTime = systemTime() + standbyDelay;
2659 sleepTime = idleSleepTime;
2660 continue;
2661 }
2662 }
2663
2664 effectChains = mEffectChains;
2665
2666 // find out which tracks need to be processed
2667 if (mActiveTracks.size() != 0) {
2668 sp<Track> t = mActiveTracks[0].promote();
2669 if (t == 0) continue;
2670
2671 Track* const track = t.get();
2672 audio_track_cblk_t* cblk = track->cblk();
2673
2674 // The first time a track is added we wait
2675 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002676 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677 !track->isPaused() && !track->isTerminated())
2678 {
Steve Block3856b092011-10-20 11:56:00 +01002679 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002680
2681 if (track->mFillingUpStatus == Track::FS_FILLED) {
2682 track->mFillingUpStatus = Track::FS_ACTIVE;
2683 mLeftVolFloat = mRightVolFloat = 0;
2684 mLeftVolShort = mRightVolShort = 0;
2685 if (track->mState == TrackBase::RESUMING) {
2686 track->mState = TrackBase::ACTIVE;
2687 rampVolume = true;
2688 }
2689 } else if (cblk->server != 0) {
2690 // If the track is stopped before the first frame was mixed,
2691 // do not apply ramp
2692 rampVolume = true;
2693 }
2694 // compute volume for this track
2695 float left, right;
2696 if (track->isMuted() || mMasterMute || track->isPausing() ||
Glenn Kasten02bbd202012-02-08 12:35:35 -08002697 mStreamTypes[track->streamType()].mute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 left = right = 0;
2699 if (track->isPausing()) {
2700 track->setPaused();
2701 }
2702 } else {
Glenn Kasten02bbd202012-02-08 12:35:35 -08002703 float typeVolume = mStreamTypes[track->streamType()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 float v = mMasterVolume * typeVolume;
Glenn Kasten83d86532012-01-17 14:39:34 -08002705 uint32_t vlr = cblk->getVolumeLR();
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002706 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2708 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002709 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2711 right = v_clamped/MAX_GAIN;
2712 }
2713
2714 if (left != mLeftVolFloat || right != mRightVolFloat) {
2715 mLeftVolFloat = left;
2716 mRightVolFloat = right;
2717
2718 // If audio HAL implements volume control,
2719 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002720 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002721 left = 1.0f;
2722 right = 1.0f;
2723 }
2724
2725 // Convert volumes from float to 8.24
2726 uint32_t vl = (uint32_t)(left * (1 << 24));
2727 uint32_t vr = (uint32_t)(right * (1 << 24));
2728
2729 // Delegate volume control to effect in track effect chain if needed
2730 // only one effect chain can be present on DirectOutputThread, so if
2731 // there is one, the track is connected to it
2732 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002733 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002734 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735 rampVolume = false;
2736 }
2737 }
2738
2739 // Convert volumes from 8.24 to 4.12 format
2740 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2741 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2742 leftVol = (uint16_t)v_clamped;
2743 v_clamped = (vr + (1 << 11)) >> 12;
2744 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2745 rightVol = (uint16_t)v_clamped;
2746 } else {
2747 leftVol = mLeftVolShort;
2748 rightVol = mRightVolShort;
2749 rampVolume = false;
2750 }
2751
2752 // reset retry count
2753 track->mRetryCount = kMaxTrackRetriesDirect;
2754 activeTrack = t;
2755 mixerStatus = MIXER_TRACKS_READY;
2756 } else {
Steve Block3856b092011-10-20 11:56:00 +01002757 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002758 if (track->isStopped()) {
2759 track->reset();
2760 }
2761 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2762 // We have consumed all the buffers of this track.
2763 // Remove it from the list of active tracks.
2764 trackToRemove = track;
2765 } else {
2766 // No buffers for this track. Give it a few chances to
2767 // fill a buffer, then remove it from active list.
2768 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002769 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 trackToRemove = track;
2771 } else {
2772 mixerStatus = MIXER_TRACKS_ENABLED;
2773 }
2774 }
2775 }
2776 }
2777
2778 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002779 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002780 mActiveTracks.remove(trackToRemove);
2781 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002782 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002783 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002784 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002785 }
2786 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002787 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 }
2789 }
2790
Eric Laurentde070132010-07-13 04:45:46 -07002791 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792 }
2793
Glenn Kastenf6b16782011-12-15 09:51:17 -08002794 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002795 AudioBufferProvider::Buffer buffer;
2796 size_t frameCount = mFrameCount;
2797 curBuf = (int8_t *)mMixBuffer;
2798 // output audio to hardware
2799 while (frameCount) {
2800 buffer.frameCount = frameCount;
2801 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002802 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 memset(curBuf, 0, frameCount * mFrameSize);
2804 break;
2805 }
2806 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2807 frameCount -= buffer.frameCount;
2808 curBuf += buffer.frameCount * mFrameSize;
2809 activeTrack->releaseBuffer(&buffer);
2810 }
2811 sleepTime = 0;
2812 standbyTime = systemTime() + standbyDelay;
2813 } else {
2814 if (sleepTime == 0) {
2815 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2816 sleepTime = activeSleepTime;
2817 } else {
2818 sleepTime = idleSleepTime;
2819 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002820 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2822 sleepTime = 0;
2823 }
2824 }
2825
2826 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002827 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 }
2829 // sleepTime == 0 means we must write to audio hardware
2830 if (sleepTime == 0) {
2831 if (mixerStatus == MIXER_TRACKS_READY) {
2832 applyVolume(leftVol, rightVol, rampVolume);
2833 }
2834 for (size_t i = 0; i < effectChains.size(); i ++) {
2835 effectChains[i]->process_l();
2836 }
Eric Laurentde070132010-07-13 04:45:46 -07002837 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838
2839 mLastWriteTime = systemTime();
2840 mInWrite = true;
2841 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002842 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2844 mNumWrites++;
2845 mInWrite = false;
2846 mStandby = false;
2847 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002848 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 usleep(sleepTime);
2850 }
2851
2852 // finally let go of removed track, without the lock held
2853 // since we can't guarantee the destructors won't acquire that
2854 // same lock.
2855 trackToRemove.clear();
2856 activeTrack.clear();
2857
2858 // Effect chains will be actually deleted here if they were removed from
2859 // mEffectChains list during mixing or effects processing
2860 effectChains.clear();
2861 }
2862
2863 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002864 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002865 }
2866
Eric Laurentfeb0db62011-07-22 09:04:31 -07002867 releaseWakeLock();
2868
Steve Block3856b092011-10-20 11:56:00 +01002869 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 return false;
2871}
2872
2873// getTrackName_l() must be called with ThreadBase::mLock held
2874int AudioFlinger::DirectOutputThread::getTrackName_l()
2875{
2876 return 0;
2877}
2878
2879// deleteTrackName_l() must be called with ThreadBase::mLock held
2880void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2881{
2882}
2883
2884// checkForNewParameters_l() must be called with ThreadBase::mLock held
2885bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2886{
2887 bool reconfig = false;
2888
2889 while (!mNewParameters.isEmpty()) {
2890 status_t status = NO_ERROR;
2891 String8 keyValuePair = mNewParameters[0];
2892 AudioParameter param = AudioParameter(keyValuePair);
2893 int value;
2894
2895 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2896 // do not accept frame count changes if tracks are open as the track buffer
2897 // size depends on frame count and correct behavior would not be garantied
2898 // if frame count is changed after track creation
2899 if (!mTracks.isEmpty()) {
2900 status = INVALID_OPERATION;
2901 } else {
2902 reconfig = true;
2903 }
2904 }
2905 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002906 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002907 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002909 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 mStandby = true;
2911 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002912 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002913 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002914 }
2915 if (status == NO_ERROR && reconfig) {
2916 readOutputParameters();
2917 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2918 }
2919 }
2920
2921 mNewParameters.removeAt(0);
2922
2923 mParamStatus = status;
2924 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002925 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2926 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002927 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002928 }
2929 return reconfig;
2930}
2931
2932uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2933{
2934 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002935 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002936 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 } else {
2938 time = 10000;
2939 }
2940 return time;
2941}
2942
2943uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2944{
2945 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002946 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002947 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948 } else {
2949 time = 10000;
2950 }
2951 return time;
2952}
2953
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002954uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2955{
2956 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002957 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002958 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2959 } else {
2960 time = 10000;
2961 }
2962 return time;
2963}
2964
2965
Mathias Agopian65ab4712010-07-14 17:59:35 -07002966// ----------------------------------------------------------------------------
2967
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002968AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08002969 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id)
Glenn Kasten23bb8be2012-01-26 10:38:26 -08002970 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device(), DUPLICATING),
2971 mWaitTimeMs(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972{
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 addOutputTrack(mainThread);
2974}
2975
2976AudioFlinger::DuplicatingThread::~DuplicatingThread()
2977{
2978 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2979 mOutputTracks[i]->destroy();
2980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002981}
2982
2983bool AudioFlinger::DuplicatingThread::threadLoop()
2984{
2985 Vector< sp<Track> > tracksToRemove;
Glenn Kasten29c23c32012-01-26 13:37:52 -08002986 mixer_state mixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002987 nsecs_t standbyTime = systemTime();
2988 size_t mixBufferSize = mFrameCount*mFrameSize;
2989 SortedVector< sp<OutputTrack> > outputTracks;
2990 uint32_t writeFrames = 0;
2991 uint32_t activeSleepTime = activeSleepTimeUs();
2992 uint32_t idleSleepTime = idleSleepTimeUs();
2993 uint32_t sleepTime = idleSleepTime;
2994 Vector< sp<EffectChain> > effectChains;
2995
Eric Laurentfeb0db62011-07-22 09:04:31 -07002996 acquireWakeLock();
2997
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 while (!exitPending())
2999 {
3000 processConfigEvents();
3001
3002 mixerStatus = MIXER_IDLE;
3003 { // scope for the mLock
3004
3005 Mutex::Autolock _l(mLock);
3006
3007 if (checkForNewParameters_l()) {
3008 mixBufferSize = mFrameCount*mFrameSize;
3009 updateWaitTime();
3010 activeSleepTime = activeSleepTimeUs();
3011 idleSleepTime = idleSleepTimeUs();
3012 }
3013
3014 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3015
3016 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3017 outputTracks.add(mOutputTracks[i]);
3018 }
3019
3020 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003021 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3022 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003023 if (!mStandby) {
3024 for (size_t i = 0; i < outputTracks.size(); i++) {
3025 outputTracks[i]->stop();
3026 }
3027 mStandby = true;
3028 mBytesWritten = 0;
3029 }
3030
3031 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3032 // we're about to wait, flush the binder command buffer
3033 IPCThreadState::self()->flushCommands();
3034 outputTracks.clear();
3035
3036 if (exitPending()) break;
3037
Eric Laurentfeb0db62011-07-22 09:04:31 -07003038 releaseWakeLock_l();
Glenn Kasten90bebef2012-01-27 15:24:38 -08003039 ALOGV("DuplicatingThread %p TID %d going to sleep", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 mWaitWorkCV.wait(mLock);
Glenn Kasten90bebef2012-01-27 15:24:38 -08003041 ALOGV("DuplicatingThread %p TID %d waking up", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003042 acquireWakeLock_l();
3043
Eric Laurent27741442012-01-17 19:20:12 -08003044 mPrevMixerStatus = MIXER_IDLE;
Glenn Kastenf1d45922012-01-13 15:54:24 -08003045 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 char value[PROPERTY_VALUE_MAX];
3047 property_get("ro.audio.silent", value, "0");
3048 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003049 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 setMasterMute(true);
3051 }
3052 }
3053
3054 standbyTime = systemTime() + kStandbyTimeInNsecs;
3055 sleepTime = idleSleepTime;
3056 continue;
3057 }
3058 }
3059
3060 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3061
3062 // prevent any changes in effect chain list and in each effect chain
3063 // during mixing and effect process as the audio buffers could be deleted
3064 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003065 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003066 }
3067
Glenn Kastenf6b16782011-12-15 09:51:17 -08003068 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069 // mix buffers...
3070 if (outputsReady(outputTracks)) {
3071 mAudioMixer->process();
3072 } else {
3073 memset(mMixBuffer, 0, mixBufferSize);
3074 }
3075 sleepTime = 0;
3076 writeFrames = mFrameCount;
3077 } else {
3078 if (sleepTime == 0) {
3079 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3080 sleepTime = activeSleepTime;
3081 } else {
3082 sleepTime = idleSleepTime;
3083 }
3084 } else if (mBytesWritten != 0) {
3085 // flush remaining overflow buffers in output tracks
3086 for (size_t i = 0; i < outputTracks.size(); i++) {
3087 if (outputTracks[i]->isActive()) {
3088 sleepTime = 0;
3089 writeFrames = 0;
3090 memset(mMixBuffer, 0, mixBufferSize);
3091 break;
3092 }
3093 }
3094 }
3095 }
3096
3097 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003098 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003099 }
3100 // sleepTime == 0 means we must write to audio hardware
3101 if (sleepTime == 0) {
3102 for (size_t i = 0; i < effectChains.size(); i ++) {
3103 effectChains[i]->process_l();
3104 }
3105 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003106 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107
3108 standbyTime = systemTime() + kStandbyTimeInNsecs;
3109 for (size_t i = 0; i < outputTracks.size(); i++) {
3110 outputTracks[i]->write(mMixBuffer, writeFrames);
3111 }
3112 mStandby = false;
3113 mBytesWritten += mixBufferSize;
3114 } else {
3115 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003116 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 usleep(sleepTime);
3118 }
3119
3120 // finally let go of all our tracks, without the lock held
3121 // since we can't guarantee the destructors won't acquire that
3122 // same lock.
3123 tracksToRemove.clear();
3124 outputTracks.clear();
3125
3126 // Effect chains will be actually deleted here if they were removed from
3127 // mEffectChains list during mixing or effects processing
3128 effectChains.clear();
3129 }
3130
Eric Laurentfeb0db62011-07-22 09:04:31 -07003131 releaseWakeLock();
3132
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133 return false;
3134}
3135
3136void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3137{
3138 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3139 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3140 this,
3141 mSampleRate,
3142 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003143 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 frameCount);
3145 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003146 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003148 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003149 updateWaitTime();
3150 }
3151}
3152
3153void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3154{
3155 Mutex::Autolock _l(mLock);
3156 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3157 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3158 mOutputTracks[i]->destroy();
3159 mOutputTracks.removeAt(i);
3160 updateWaitTime();
3161 return;
3162 }
3163 }
Steve Block3856b092011-10-20 11:56:00 +01003164 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165}
3166
3167void AudioFlinger::DuplicatingThread::updateWaitTime()
3168{
3169 mWaitTimeMs = UINT_MAX;
3170 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3171 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
Glenn Kasten7378ca52012-01-20 13:44:40 -08003172 if (strong != 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3174 if (waitTimeMs < mWaitTimeMs) {
3175 mWaitTimeMs = waitTimeMs;
3176 }
3177 }
3178 }
3179}
3180
3181
3182bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3183{
3184 for (size_t i = 0; i < outputTracks.size(); i++) {
3185 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3186 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003187 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 return false;
3189 }
3190 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3191 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003192 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 return false;
3194 }
3195 }
3196 return true;
3197}
3198
3199uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3200{
3201 return (mWaitTimeMs * 1000) / 2;
3202}
3203
3204// ----------------------------------------------------------------------------
3205
3206// TrackBase constructor must be called with AudioFlinger::mLock held
3207AudioFlinger::ThreadBase::TrackBase::TrackBase(
3208 const wp<ThreadBase>& thread,
3209 const sp<Client>& client,
3210 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003211 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003212 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003213 int frameCount,
3214 uint32_t flags,
3215 const sp<IMemory>& sharedBuffer,
3216 int sessionId)
3217 : RefBase(),
3218 mThread(thread),
3219 mClient(client),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003220 mCblk(NULL),
3221 // mBuffer
3222 // mBufferEnd
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 mFrameCount(0),
3224 mState(IDLE),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 mFormat(format),
3226 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3227 mSessionId(sessionId)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003228 // mChannelCount
3229 // mChannelMask
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230{
Steve Block3856b092011-10-20 11:56:00 +01003231 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003232
Steve Blockb8a80522011-12-20 16:23:08 +00003233 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003235 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3237 if (sharedBuffer == 0) {
3238 size += bufferSize;
3239 }
3240
3241 if (client != NULL) {
3242 mCblkMemory = client->heap()->allocate(size);
3243 if (mCblkMemory != 0) {
3244 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
Glenn Kastena0d68332012-01-27 16:47:15 -08003245 if (mCblk != NULL) { // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 new(mCblk) audio_track_cblk_t();
3247 // clear all buffers
3248 mCblk->frameCount = frameCount;
3249 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003250 mChannelCount = channelCount;
3251 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 if (sharedBuffer == 0) {
3253 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3254 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3255 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003256 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 mCblk->flags = CBLK_UNDERRUN_ON;
3258 } else {
3259 mBuffer = sharedBuffer->pointer();
3260 }
3261 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3262 }
3263 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003264 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 client->heap()->dump("AudioTrack");
3266 return;
3267 }
3268 } else {
3269 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003270 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003271 new(mCblk) audio_track_cblk_t();
3272 // clear all buffers
3273 mCblk->frameCount = frameCount;
3274 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003275 mChannelCount = channelCount;
3276 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3278 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3279 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003280 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003281 mCblk->flags = CBLK_UNDERRUN_ON;
3282 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003283 }
3284}
3285
3286AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3287{
Glenn Kastena0d68332012-01-27 16:47:15 -08003288 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003289 if (mClient == 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 delete mCblk;
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08003291 } else {
3292 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003293 }
3294 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08003295 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten7378ca52012-01-20 13:44:40 -08003296 if (mClient != 0) {
Glenn Kasten84afa3b2012-01-25 15:28:08 -08003297 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
Glenn Kasten7378ca52012-01-20 13:44:40 -08003299 // If the client's reference count drops to zero, the associated destructor
3300 // must run with AudioFlinger lock held. Thus the explicit clear() rather than
3301 // relying on the automatic clear() at end of scope.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 mClient.clear();
3303 }
3304}
3305
3306void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3307{
Glenn Kastene0feee32011-12-13 11:53:26 -08003308 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003309 mFrameCount = buffer->frameCount;
3310 step();
3311 buffer->frameCount = 0;
3312}
3313
3314bool AudioFlinger::ThreadBase::TrackBase::step() {
3315 bool result;
3316 audio_track_cblk_t* cblk = this->cblk();
3317
3318 result = cblk->stepServer(mFrameCount);
3319 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003320 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 mFlags |= STEPSERVER_FAILED;
3322 }
3323 return result;
3324}
3325
3326void AudioFlinger::ThreadBase::TrackBase::reset() {
3327 audio_track_cblk_t* cblk = this->cblk();
3328
3329 cblk->user = 0;
3330 cblk->server = 0;
3331 cblk->userBase = 0;
3332 cblk->serverBase = 0;
3333 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003334 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335}
3336
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3338 return (int)mCblk->sampleRate;
3339}
3340
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3342 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003343 size_t frameSize = cblk->frameSize;
3344 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3345 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346
3347 // Check validity of returned pointer in case the track control block would have been corrupted.
3348 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003349 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003350 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 -07003351 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003353 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Glenn Kastena0d68332012-01-27 16:47:15 -08003354 return NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003355 }
3356
3357 return bufferStart;
3358}
3359
3360// ----------------------------------------------------------------------------
3361
3362// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3363AudioFlinger::PlaybackThread::Track::Track(
3364 const wp<ThreadBase>& thread,
3365 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003366 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003368 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003369 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 int frameCount,
3371 const sp<IMemory>& sharedBuffer,
3372 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003373 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003374 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3375 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376{
3377 if (mCblk != NULL) {
3378 sp<ThreadBase> baseThread = thread.promote();
3379 if (baseThread != 0) {
3380 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3381 mName = playbackThread->getTrackName_l();
3382 mMainBuffer = playbackThread->mixBuffer();
3383 }
Glenn Kasten23d82a92012-02-03 11:10:00 -08003384 ALOGV("Track constructor name %d, calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003386 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003388 mStreamType = streamType;
3389 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3390 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003391 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003392 }
3393}
3394
3395AudioFlinger::PlaybackThread::Track::~Track()
3396{
Steve Block3856b092011-10-20 11:56:00 +01003397 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003398 sp<ThreadBase> thread = mThread.promote();
3399 if (thread != 0) {
3400 Mutex::Autolock _l(thread->mLock);
3401 mState = TERMINATED;
3402 }
3403}
3404
3405void AudioFlinger::PlaybackThread::Track::destroy()
3406{
3407 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3408 // by removing it from mTracks vector, so there is a risk that this Tracks's
3409 // desctructor is called. As the destructor needs to lock mLock,
3410 // we must acquire a strong reference on this Track before locking mLock
3411 // here so that the destructor is called only when exiting this function.
3412 // On the other hand, as long as Track::destroy() is only called by
3413 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3414 // this Track with its member mTrack.
3415 sp<Track> keep(this);
3416 { // scope for mLock
3417 sp<ThreadBase> thread = mThread.promote();
3418 if (thread != 0) {
3419 if (!isOutputTrack()) {
3420 if (mState == ACTIVE || mState == RESUMING) {
Glenn Kasten02bbd202012-02-08 12:35:35 -08003421 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003422
3423 // to track the speaker usage
3424 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 }
3426 AudioSystem::releaseOutput(thread->id());
3427 }
3428 Mutex::Autolock _l(thread->mLock);
3429 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3430 playbackThread->destroyTrack_l(this);
3431 }
3432 }
3433}
3434
3435void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3436{
Glenn Kasten83d86532012-01-17 14:39:34 -08003437 uint32_t vlr = mCblk->getVolumeLR();
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003438 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 -07003439 mName - AudioMixer::TRACK0,
Glenn Kasten7378ca52012-01-20 13:44:40 -08003440 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 mStreamType,
3442 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003443 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 mSessionId,
3445 mFrameCount,
3446 mState,
3447 mMute,
3448 mFillingUpStatus,
3449 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003450 vlr & 0xFFFF,
3451 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 mCblk->server,
3453 mCblk->user,
3454 (int)mMainBuffer,
3455 (int)mAuxBuffer);
3456}
3457
3458status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3459{
3460 audio_track_cblk_t* cblk = this->cblk();
3461 uint32_t framesReady;
3462 uint32_t framesReq = buffer->frameCount;
3463
3464 // Check if last stepServer failed, try to step now
3465 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3466 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003467 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3469 }
3470
3471 framesReady = cblk->framesReady();
3472
Glenn Kastenf6b16782011-12-15 09:51:17 -08003473 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 uint32_t s = cblk->server;
3475 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3476
3477 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3478 if (framesReq > framesReady) {
3479 framesReq = framesReady;
3480 }
3481 if (s + framesReq > bufferEnd) {
3482 framesReq = bufferEnd - s;
3483 }
3484
3485 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003486 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487
3488 buffer->frameCount = framesReq;
3489 return NO_ERROR;
3490 }
3491
3492getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003493 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003495 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 return NOT_ENOUGH_DATA;
3497}
3498
3499bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003500 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501
3502 if (mCblk->framesReady() >= mCblk->frameCount ||
3503 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3504 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003505 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 return true;
3507 }
3508 return false;
3509}
3510
3511status_t AudioFlinger::PlaybackThread::Track::start()
3512{
3513 status_t status = NO_ERROR;
Glenn Kasten23d82a92012-02-03 11:10:00 -08003514 ALOGV("start(%d), calling pid %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003515 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 sp<ThreadBase> thread = mThread.promote();
3517 if (thread != 0) {
3518 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003519 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 // here the track could be either new, or restarted
3521 // in both cases "unstop" the track
3522 if (mState == PAUSED) {
3523 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003524 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 } else {
3526 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003527 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003528 }
3529
3530 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3531 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003532 status = AudioSystem::startOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003534
3535 // to track the speaker usage
3536 if (status == NO_ERROR) {
3537 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3538 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 }
3540 if (status == NO_ERROR) {
3541 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3542 playbackThread->addTrack_l(this);
3543 } else {
3544 mState = state;
3545 }
3546 } else {
3547 status = BAD_VALUE;
3548 }
3549 return status;
3550}
3551
3552void AudioFlinger::PlaybackThread::Track::stop()
3553{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003554 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555 sp<ThreadBase> thread = mThread.promote();
3556 if (thread != 0) {
3557 Mutex::Autolock _l(thread->mLock);
Glenn Kastenb853e982012-01-26 13:39:18 -08003558 track_state state = mState;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559 if (mState > STOPPED) {
3560 mState = STOPPED;
3561 // If the track is not active (PAUSED and buffers full), flush buffers
3562 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3563 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3564 reset();
3565 }
Steve Block3856b092011-10-20 11:56:00 +01003566 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 }
3568 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3569 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003570 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003572
3573 // to track the speaker usage
3574 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003575 }
3576 }
3577}
3578
3579void AudioFlinger::PlaybackThread::Track::pause()
3580{
Glenn Kasten23d82a92012-02-03 11:10:00 -08003581 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 sp<ThreadBase> thread = mThread.promote();
3583 if (thread != 0) {
3584 Mutex::Autolock _l(thread->mLock);
3585 if (mState == ACTIVE || mState == RESUMING) {
3586 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003587 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 if (!isOutputTrack()) {
3589 thread->mLock.unlock();
Glenn Kasten02bbd202012-02-08 12:35:35 -08003590 AudioSystem::stopOutput(thread->id(), mStreamType, mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003592
3593 // to track the speaker usage
3594 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 }
3596 }
3597 }
3598}
3599
3600void AudioFlinger::PlaybackThread::Track::flush()
3601{
Steve Block3856b092011-10-20 11:56:00 +01003602 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003603 sp<ThreadBase> thread = mThread.promote();
3604 if (thread != 0) {
3605 Mutex::Autolock _l(thread->mLock);
3606 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3607 return;
3608 }
3609 // No point remaining in PAUSED state after a flush => go to
3610 // STOPPED state
3611 mState = STOPPED;
3612
Eric Laurent38ccae22011-03-28 18:37:07 -07003613 // do not reset the track if it is still in the process of being stopped or paused.
3614 // this will be done by prepareTracks_l() when the track is stopped.
3615 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3616 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3617 reset();
3618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 }
3620}
3621
3622void AudioFlinger::PlaybackThread::Track::reset()
3623{
3624 // Do not reset twice to avoid discarding data written just after a flush and before
3625 // the audioflinger thread detects the track is stopped.
3626 if (!mResetDone) {
3627 TrackBase::reset();
3628 // Force underrun condition to avoid false underrun callback until first data is
3629 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003630 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3631 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 mFillingUpStatus = FS_FILLING;
3633 mResetDone = true;
3634 }
3635}
3636
3637void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3638{
3639 mMute = muted;
3640}
3641
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3643{
3644 status_t status = DEAD_OBJECT;
3645 sp<ThreadBase> thread = mThread.promote();
3646 if (thread != 0) {
3647 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3648 status = playbackThread->attachAuxEffect(this, EffectId);
3649 }
3650 return status;
3651}
3652
3653void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3654{
3655 mAuxEffectId = EffectId;
3656 mAuxBuffer = buffer;
3657}
3658
3659// ----------------------------------------------------------------------------
3660
3661// RecordTrack constructor must be called with AudioFlinger::mLock held
3662AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3663 const wp<ThreadBase>& thread,
3664 const sp<Client>& client,
3665 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003666 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003667 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003668 int frameCount,
3669 uint32_t flags,
3670 int sessionId)
3671 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003672 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673 mOverflow(false)
3674{
3675 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003676 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003677 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003678 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003679 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003680 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003681 } else {
3682 mCblk->frameSize = sizeof(int8_t);
3683 }
3684 }
3685}
3686
3687AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3688{
3689 sp<ThreadBase> thread = mThread.promote();
3690 if (thread != 0) {
3691 AudioSystem::releaseInput(thread->id());
3692 }
3693}
3694
3695status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3696{
3697 audio_track_cblk_t* cblk = this->cblk();
3698 uint32_t framesAvail;
3699 uint32_t framesReq = buffer->frameCount;
3700
3701 // Check if last stepServer failed, try to step now
3702 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3703 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003704 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003705 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3706 }
3707
3708 framesAvail = cblk->framesAvailable_l();
3709
Glenn Kastenf6b16782011-12-15 09:51:17 -08003710 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711 uint32_t s = cblk->server;
3712 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3713
3714 if (framesReq > framesAvail) {
3715 framesReq = framesAvail;
3716 }
3717 if (s + framesReq > bufferEnd) {
3718 framesReq = bufferEnd - s;
3719 }
3720
3721 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003722 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723
3724 buffer->frameCount = framesReq;
3725 return NO_ERROR;
3726 }
3727
3728getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003729 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730 buffer->frameCount = 0;
3731 return NOT_ENOUGH_DATA;
3732}
3733
3734status_t AudioFlinger::RecordThread::RecordTrack::start()
3735{
3736 sp<ThreadBase> thread = mThread.promote();
3737 if (thread != 0) {
3738 RecordThread *recordThread = (RecordThread *)thread.get();
3739 return recordThread->start(this);
3740 } else {
3741 return BAD_VALUE;
3742 }
3743}
3744
3745void AudioFlinger::RecordThread::RecordTrack::stop()
3746{
3747 sp<ThreadBase> thread = mThread.promote();
3748 if (thread != 0) {
3749 RecordThread *recordThread = (RecordThread *)thread.get();
3750 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003751 TrackBase::reset();
3752 // Force overerrun condition to avoid false overrun callback until first data is
3753 // read from buffer
3754 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 }
3756}
3757
3758void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3759{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003760 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08003761 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003763 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003764 mSessionId,
3765 mFrameCount,
3766 mState,
3767 mCblk->sampleRate,
3768 mCblk->server,
3769 mCblk->user);
3770}
3771
3772
3773// ----------------------------------------------------------------------------
3774
3775AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3776 const wp<ThreadBase>& thread,
3777 DuplicatingThread *sourceThread,
3778 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08003779 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003780 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003781 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003782 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783 mActive(false), mSourceThread(sourceThread)
3784{
3785
3786 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3787 if (mCblk != NULL) {
3788 mCblk->flags |= CBLK_DIRECTION_OUT;
3789 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 mOutBuffer.frameCount = 0;
3791 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003792 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003793 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3794 mCblk, mBuffer, mCblk->buffers,
3795 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003796 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003797 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003798 }
3799}
3800
3801AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3802{
3803 clearBufferQueue();
3804}
3805
3806status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3807{
3808 status_t status = Track::start();
3809 if (status != NO_ERROR) {
3810 return status;
3811 }
3812
3813 mActive = true;
3814 mRetryCount = 127;
3815 return status;
3816}
3817
3818void AudioFlinger::PlaybackThread::OutputTrack::stop()
3819{
3820 Track::stop();
3821 clearBufferQueue();
3822 mOutBuffer.frameCount = 0;
3823 mActive = false;
3824}
3825
3826bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3827{
3828 Buffer *pInBuffer;
3829 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003830 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831 bool outputBufferFull = false;
3832 inBuffer.frameCount = frames;
3833 inBuffer.i16 = data;
3834
3835 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3836
3837 if (!mActive && frames != 0) {
3838 start();
3839 sp<ThreadBase> thread = mThread.promote();
3840 if (thread != 0) {
3841 MixerThread *mixerThread = (MixerThread *)thread.get();
3842 if (mCblk->frameCount > frames){
3843 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3844 uint32_t startFrames = (mCblk->frameCount - frames);
3845 pInBuffer = new Buffer;
3846 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3847 pInBuffer->frameCount = startFrames;
3848 pInBuffer->i16 = pInBuffer->mBuffer;
3849 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3850 mBufferQueue.add(pInBuffer);
3851 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003852 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003853 }
3854 }
3855 }
3856 }
3857
3858 while (waitTimeLeftMs) {
3859 // First write pending buffers, then new data
3860 if (mBufferQueue.size()) {
3861 pInBuffer = mBufferQueue.itemAt(0);
3862 } else {
3863 pInBuffer = &inBuffer;
3864 }
3865
3866 if (pInBuffer->frameCount == 0) {
3867 break;
3868 }
3869
3870 if (mOutBuffer.frameCount == 0) {
3871 mOutBuffer.frameCount = pInBuffer->frameCount;
3872 nsecs_t startTime = systemTime();
Glenn Kasten335787f2012-01-20 17:00:00 -08003873 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003874 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003875 outputBufferFull = true;
3876 break;
3877 }
3878 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3879 if (waitTimeLeftMs >= waitTimeMs) {
3880 waitTimeLeftMs -= waitTimeMs;
3881 } else {
3882 waitTimeLeftMs = 0;
3883 }
3884 }
3885
3886 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3887 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3888 mCblk->stepUser(outFrames);
3889 pInBuffer->frameCount -= outFrames;
3890 pInBuffer->i16 += outFrames * channelCount;
3891 mOutBuffer.frameCount -= outFrames;
3892 mOutBuffer.i16 += outFrames * channelCount;
3893
3894 if (pInBuffer->frameCount == 0) {
3895 if (mBufferQueue.size()) {
3896 mBufferQueue.removeAt(0);
3897 delete [] pInBuffer->mBuffer;
3898 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003899 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900 } else {
3901 break;
3902 }
3903 }
3904 }
3905
3906 // If we could not write all frames, allocate a buffer and queue it for next time.
3907 if (inBuffer.frameCount) {
3908 sp<ThreadBase> thread = mThread.promote();
3909 if (thread != 0 && !thread->standby()) {
3910 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3911 pInBuffer = new Buffer;
3912 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3913 pInBuffer->frameCount = inBuffer.frameCount;
3914 pInBuffer->i16 = pInBuffer->mBuffer;
3915 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3916 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003917 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003919 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 }
3921 }
3922 }
3923
3924 // Calling write() with a 0 length buffer, means that no more data will be written:
3925 // If no more buffers are pending, fill output track buffer to make sure it is started
3926 // by output mixer.
3927 if (frames == 0 && mBufferQueue.size() == 0) {
3928 if (mCblk->user < mCblk->frameCount) {
3929 frames = mCblk->frameCount - mCblk->user;
3930 pInBuffer = new Buffer;
3931 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3932 pInBuffer->frameCount = frames;
3933 pInBuffer->i16 = pInBuffer->mBuffer;
3934 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3935 mBufferQueue.add(pInBuffer);
3936 } else if (mActive) {
3937 stop();
3938 }
3939 }
3940
3941 return outputBufferFull;
3942}
3943
3944status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3945{
3946 int active;
3947 status_t result;
3948 audio_track_cblk_t* cblk = mCblk;
3949 uint32_t framesReq = buffer->frameCount;
3950
Steve Block3856b092011-10-20 11:56:00 +01003951// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003952 buffer->frameCount = 0;
3953
3954 uint32_t framesAvail = cblk->framesAvailable();
3955
3956
3957 if (framesAvail == 0) {
3958 Mutex::Autolock _l(cblk->lock);
3959 goto start_loop_here;
3960 while (framesAvail == 0) {
3961 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003962 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003963 ALOGV("Not active and NO_MORE_BUFFERS");
Glenn Kasten335787f2012-01-20 17:00:00 -08003964 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003965 }
3966 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3967 if (result != NO_ERROR) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003968 return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969 }
3970 // read the server count again
3971 start_loop_here:
3972 framesAvail = cblk->framesAvailable_l();
3973 }
3974 }
3975
3976// if (framesAvail < framesReq) {
Glenn Kasten335787f2012-01-20 17:00:00 -08003977// return NO_MORE_BUFFERS;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978// }
3979
3980 if (framesReq > framesAvail) {
3981 framesReq = framesAvail;
3982 }
3983
3984 uint32_t u = cblk->user;
3985 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3986
3987 if (u + framesReq > bufferEnd) {
3988 framesReq = bufferEnd - u;
3989 }
3990
3991 buffer->frameCount = framesReq;
3992 buffer->raw = (void *)cblk->buffer(u);
3993 return NO_ERROR;
3994}
3995
3996
3997void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3998{
3999 size_t size = mBufferQueue.size();
4000 Buffer *pBuffer;
4001
4002 for (size_t i = 0; i < size; i++) {
4003 pBuffer = mBufferQueue.itemAt(i);
4004 delete [] pBuffer->mBuffer;
4005 delete pBuffer;
4006 }
4007 mBufferQueue.clear();
4008}
4009
4010// ----------------------------------------------------------------------------
4011
4012AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4013 : RefBase(),
4014 mAudioFlinger(audioFlinger),
4015 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4016 mPid(pid)
4017{
4018 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4019}
4020
4021// Client destructor must be called with AudioFlinger::mLock held
4022AudioFlinger::Client::~Client()
4023{
4024 mAudioFlinger->removeClient_l(mPid);
4025}
4026
Glenn Kasten435dbe62012-01-30 10:15:48 -08004027sp<MemoryDealer> AudioFlinger::Client::heap() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028{
4029 return mMemoryDealer;
4030}
4031
4032// ----------------------------------------------------------------------------
4033
4034AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4035 const sp<IAudioFlingerClient>& client,
4036 pid_t pid)
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004037 : mAudioFlinger(audioFlinger), mPid(pid), mAudioFlingerClient(client)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038{
4039}
4040
4041AudioFlinger::NotificationClient::~NotificationClient()
4042{
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043}
4044
4045void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4046{
4047 sp<NotificationClient> keep(this);
4048 {
4049 mAudioFlinger->removeNotificationClient(mPid);
4050 }
4051}
4052
4053// ----------------------------------------------------------------------------
4054
4055AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4056 : BnAudioTrack(),
4057 mTrack(track)
4058{
4059}
4060
4061AudioFlinger::TrackHandle::~TrackHandle() {
4062 // just stop the track on deletion, associated resources
4063 // will be freed from the main thread once all pending buffers have
4064 // been played. Unless it's not in the active track list, in which
4065 // case we free everything now...
4066 mTrack->destroy();
4067}
4068
Glenn Kasten90716c52012-01-26 13:40:12 -08004069sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4070 return mTrack->getCblk();
4071}
4072
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073status_t AudioFlinger::TrackHandle::start() {
4074 return mTrack->start();
4075}
4076
4077void AudioFlinger::TrackHandle::stop() {
4078 mTrack->stop();
4079}
4080
4081void AudioFlinger::TrackHandle::flush() {
4082 mTrack->flush();
4083}
4084
4085void AudioFlinger::TrackHandle::mute(bool e) {
4086 mTrack->mute(e);
4087}
4088
4089void AudioFlinger::TrackHandle::pause() {
4090 mTrack->pause();
4091}
4092
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4094{
4095 return mTrack->attachAuxEffect(EffectId);
4096}
4097
4098status_t AudioFlinger::TrackHandle::onTransact(
4099 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4100{
4101 return BnAudioTrack::onTransact(code, data, reply, flags);
4102}
4103
4104// ----------------------------------------------------------------------------
4105
4106sp<IAudioRecord> AudioFlinger::openRecord(
4107 pid_t pid,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004108 audio_io_handle_t input,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004110 audio_format_t format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004111 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 int frameCount,
4113 uint32_t flags,
4114 int *sessionId,
4115 status_t *status)
4116{
4117 sp<RecordThread::RecordTrack> recordTrack;
4118 sp<RecordHandle> recordHandle;
4119 sp<Client> client;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120 status_t lStatus;
4121 RecordThread *thread;
4122 size_t inFrameCount;
4123 int lSessionId;
4124
4125 // check calling permissions
4126 if (!recordingAllowed()) {
4127 lStatus = PERMISSION_DENIED;
4128 goto Exit;
4129 }
4130
4131 // add client to list
4132 { // scope for mLock
4133 Mutex::Autolock _l(mLock);
4134 thread = checkRecordThread_l(input);
4135 if (thread == NULL) {
4136 lStatus = BAD_VALUE;
4137 goto Exit;
4138 }
4139
Glenn Kasten98ec94c2012-01-25 14:28:29 -08004140 client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141
4142 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004143 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004144 lSessionId = *sessionId;
4145 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004146 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 if (sessionId != NULL) {
4148 *sessionId = lSessionId;
4149 }
4150 }
4151 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004152 recordTrack = thread->createRecordTrack_l(client,
4153 sampleRate,
4154 format,
4155 channelMask,
4156 frameCount,
4157 flags,
4158 lSessionId,
4159 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004161 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4163 // destructor is called by the TrackBase destructor with mLock held
4164 client.clear();
4165 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 goto Exit;
4167 }
4168
4169 // return to handle to client
4170 recordHandle = new RecordHandle(recordTrack);
4171 lStatus = NO_ERROR;
4172
4173Exit:
4174 if (status) {
4175 *status = lStatus;
4176 }
4177 return recordHandle;
4178}
4179
4180// ----------------------------------------------------------------------------
4181
4182AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4183 : BnAudioRecord(),
4184 mRecordTrack(recordTrack)
4185{
4186}
4187
4188AudioFlinger::RecordHandle::~RecordHandle() {
4189 stop();
4190}
4191
Glenn Kasten90716c52012-01-26 13:40:12 -08004192sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4193 return mRecordTrack->getCblk();
4194}
4195
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004197 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 return mRecordTrack->start();
4199}
4200
4201void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004202 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 mRecordTrack->stop();
4204}
4205
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206status_t AudioFlinger::RecordHandle::onTransact(
4207 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4208{
4209 return BnAudioRecord::onTransact(code, data, reply, flags);
4210}
4211
4212// ----------------------------------------------------------------------------
4213
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004214AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4215 AudioStreamIn *input,
4216 uint32_t sampleRate,
4217 uint32_t channels,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004218 audio_io_handle_t id,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004219 uint32_t device) :
Glenn Kasten23bb8be2012-01-26 10:38:26 -08004220 ThreadBase(audioFlinger, id, device, RECORD),
Glenn Kasten84afa3b2012-01-25 15:28:08 -08004221 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL),
4222 // mRsmpInIndex and mInputBytes set by readInputParameters()
4223 mReqChannelCount(popcount(channels)),
4224 mReqSampleRate(sampleRate)
4225 // mBytesRead is only meaningful while active, and so is cleared in start()
4226 // (but might be better to also clear here for dump?)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004228 snprintf(mName, kNameLength, "AudioIn_%d", id);
4229
Mathias Agopian65ab4712010-07-14 17:59:35 -07004230 readInputParameters();
4231}
4232
4233
4234AudioFlinger::RecordThread::~RecordThread()
4235{
4236 delete[] mRsmpInBuffer;
Glenn Kastene9dd0172012-01-27 18:08:45 -08004237 delete mResampler;
4238 delete[] mRsmpOutBuffer;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239}
4240
4241void AudioFlinger::RecordThread::onFirstRef()
4242{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004243 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244}
4245
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004246status_t AudioFlinger::RecordThread::readyToRun()
4247{
4248 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004249 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004250 return status;
4251}
4252
Mathias Agopian65ab4712010-07-14 17:59:35 -07004253bool AudioFlinger::RecordThread::threadLoop()
4254{
4255 AudioBufferProvider::Buffer buffer;
4256 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004257 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258
Eric Laurent44d98482010-09-30 16:12:31 -07004259 nsecs_t lastWarning = 0;
4260
Eric Laurentfeb0db62011-07-22 09:04:31 -07004261 acquireWakeLock();
4262
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 // start recording
4264 while (!exitPending()) {
4265
4266 processConfigEvents();
4267
4268 { // scope for mLock
4269 Mutex::Autolock _l(mLock);
4270 checkForNewParameters_l();
4271 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4272 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004273 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274 mStandby = true;
4275 }
4276
4277 if (exitPending()) break;
4278
Eric Laurentfeb0db62011-07-22 09:04:31 -07004279 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004280 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 // go to sleep
4282 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004283 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004284 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 continue;
4286 }
4287 if (mActiveTrack != 0) {
4288 if (mActiveTrack->mState == TrackBase::PAUSING) {
4289 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004290 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291 mStandby = true;
4292 }
4293 mActiveTrack.clear();
4294 mStartStopCond.broadcast();
4295 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4296 if (mReqChannelCount != mActiveTrack->channelCount()) {
4297 mActiveTrack.clear();
4298 mStartStopCond.broadcast();
4299 } else if (mBytesRead != 0) {
4300 // record start succeeds only if first read from audio input
4301 // succeeds
4302 if (mBytesRead > 0) {
4303 mActiveTrack->mState = TrackBase::ACTIVE;
4304 } else {
4305 mActiveTrack.clear();
4306 }
4307 mStartStopCond.broadcast();
4308 }
4309 mStandby = false;
4310 }
4311 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004312 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 }
4314
4315 if (mActiveTrack != 0) {
4316 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4317 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004318 unlockEffectChains(effectChains);
4319 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 continue;
4321 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004322 for (size_t i = 0; i < effectChains.size(); i ++) {
4323 effectChains[i]->process_l();
4324 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004325
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004327 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004329 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004330 // no resampling
4331 while (framesOut) {
4332 size_t framesIn = mFrameCount - mRsmpInIndex;
4333 if (framesIn) {
4334 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4335 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4336 if (framesIn > framesOut)
4337 framesIn = framesOut;
4338 mRsmpInIndex += framesIn;
4339 framesOut -= framesIn;
4340 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004341 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 memcpy(dst, src, framesIn * mFrameSize);
4343 } else {
4344 int16_t *src16 = (int16_t *)src;
4345 int16_t *dst16 = (int16_t *)dst;
4346 if (mChannelCount == 1) {
4347 while (framesIn--) {
4348 *dst16++ = *src16;
4349 *dst16++ = *src16++;
4350 }
4351 } else {
4352 while (framesIn--) {
4353 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4354 src16 += 2;
4355 }
4356 }
4357 }
4358 }
4359 if (framesOut && mFrameCount == mRsmpInIndex) {
4360 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004361 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004362 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 framesOut = 0;
4364 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004365 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 mRsmpInIndex = 0;
4367 }
4368 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004369 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4371 // Force input into standby so that it tries to
4372 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004373 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004374 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 }
4376 mRsmpInIndex = mFrameCount;
4377 framesOut = 0;
4378 buffer.frameCount = 0;
4379 }
4380 }
4381 }
4382 } else {
4383 // resampling
4384
4385 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4386 // alter output frame count as if we were expecting stereo samples
4387 if (mChannelCount == 1 && mReqChannelCount == 1) {
4388 framesOut >>= 1;
4389 }
4390 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4391 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4392 // are 32 bit aligned which should be always true.
4393 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004394 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 // the resampler always outputs stereo samples: do post stereo to mono conversion
4396 int16_t *src = (int16_t *)mRsmpOutBuffer;
4397 int16_t *dst = buffer.i16;
4398 while (framesOut--) {
4399 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4400 src += 2;
4401 }
4402 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004403 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 }
4405
4406 }
4407 mActiveTrack->releaseBuffer(&buffer);
4408 mActiveTrack->overflow();
4409 }
4410 // client isn't retrieving buffers fast enough
4411 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004412 if (!mActiveTrack->setOverflow()) {
4413 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004414 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004415 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004416 lastWarning = now;
4417 }
4418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004419 // Release the processor for a while before asking for a new buffer.
4420 // This will give the application more chance to read from the buffer and
4421 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004422 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423 }
4424 }
Eric Laurentec437d82011-07-26 20:54:46 -07004425 // enable changes in effect chain
4426 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004427 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 }
4429
4430 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004431 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004432 }
4433 mActiveTrack.clear();
4434
4435 mStartStopCond.broadcast();
4436
Eric Laurentfeb0db62011-07-22 09:04:31 -07004437 releaseWakeLock();
4438
Steve Block3856b092011-10-20 11:56:00 +01004439 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 return false;
4441}
4442
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004443
4444sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4445 const sp<AudioFlinger::Client>& client,
4446 uint32_t sampleRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004447 audio_format_t format,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004448 int channelMask,
4449 int frameCount,
4450 uint32_t flags,
4451 int sessionId,
4452 status_t *status)
4453{
4454 sp<RecordTrack> track;
4455 status_t lStatus;
4456
4457 lStatus = initCheck();
4458 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004459 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004460 goto Exit;
4461 }
4462
4463 { // scope for mLock
4464 Mutex::Autolock _l(mLock);
4465
4466 track = new RecordTrack(this, client, sampleRate,
4467 format, channelMask, frameCount, flags, sessionId);
4468
Glenn Kasten7378ca52012-01-20 13:44:40 -08004469 if (track->getCblk() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004470 lStatus = NO_MEMORY;
4471 goto Exit;
4472 }
4473
4474 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004475 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4476 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004477 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004478 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4479 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004480 }
4481 lStatus = NO_ERROR;
4482
4483Exit:
4484 if (status) {
4485 *status = lStatus;
4486 }
4487 return track;
4488}
4489
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4491{
Steve Block3856b092011-10-20 11:56:00 +01004492 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493 sp <ThreadBase> strongMe = this;
4494 status_t status = NO_ERROR;
4495 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004496 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497 if (mActiveTrack != 0) {
4498 if (recordTrack != mActiveTrack.get()) {
4499 status = -EBUSY;
4500 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4501 mActiveTrack->mState = TrackBase::ACTIVE;
4502 }
4503 return status;
4504 }
4505
4506 recordTrack->mState = TrackBase::IDLE;
4507 mActiveTrack = recordTrack;
4508 mLock.unlock();
4509 status_t status = AudioSystem::startInput(mId);
4510 mLock.lock();
4511 if (status != NO_ERROR) {
4512 mActiveTrack.clear();
4513 return status;
4514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 mRsmpInIndex = mFrameCount;
4516 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004517 if (mResampler != NULL) {
4518 mResampler->reset();
4519 }
4520 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004521 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004522 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 mWaitWorkCV.signal();
4524 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004525 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 mActiveTrack.clear();
4527 status = INVALID_OPERATION;
4528 goto startError;
4529 }
4530 mStartStopCond.wait(mLock);
4531 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004532 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 status = BAD_VALUE;
4534 goto startError;
4535 }
Steve Block3856b092011-10-20 11:56:00 +01004536 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004537 return status;
4538 }
4539startError:
4540 AudioSystem::stopInput(mId);
4541 return status;
4542}
4543
4544void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004545 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004546 sp <ThreadBase> strongMe = this;
4547 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004548 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4550 mActiveTrack->mState = TrackBase::PAUSING;
4551 // do not wait for mStartStopCond if exiting
Glenn Kastenb28686f2012-01-06 08:39:38 -08004552 if (exitPending()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 return;
4554 }
4555 mStartStopCond.wait(mLock);
4556 // if we have been restarted, recordTrack == mActiveTrack.get() here
4557 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4558 mLock.unlock();
4559 AudioSystem::stopInput(mId);
4560 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004561 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 }
4563 }
4564 }
4565}
4566
4567status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4568{
4569 const size_t SIZE = 256;
4570 char buffer[SIZE];
4571 String8 result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572
4573 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4574 result.append(buffer);
4575
4576 if (mActiveTrack != 0) {
4577 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004578 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004579 mActiveTrack->dump(buffer, SIZE);
4580 result.append(buffer);
4581
4582 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4583 result.append(buffer);
4584 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4585 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004586 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 result.append(buffer);
4588 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4589 result.append(buffer);
4590 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4591 result.append(buffer);
4592
4593
4594 } else {
4595 result.append("No record client\n");
4596 }
4597 write(fd, result.string(), result.size());
4598
4599 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004600 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601
4602 return NO_ERROR;
4603}
4604
4605status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4606{
4607 size_t framesReq = buffer->frameCount;
4608 size_t framesReady = mFrameCount - mRsmpInIndex;
4609 int channelCount;
4610
4611 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004612 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004614 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4616 // Force input into standby so that it tries to
4617 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004618 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004619 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004621 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004622 buffer->frameCount = 0;
4623 return NOT_ENOUGH_DATA;
4624 }
4625 mRsmpInIndex = 0;
4626 framesReady = mFrameCount;
4627 }
4628
4629 if (framesReq > framesReady) {
4630 framesReq = framesReady;
4631 }
4632
4633 if (mChannelCount == 1 && mReqChannelCount == 2) {
4634 channelCount = 1;
4635 } else {
4636 channelCount = 2;
4637 }
4638 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4639 buffer->frameCount = framesReq;
4640 return NO_ERROR;
4641}
4642
4643void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4644{
4645 mRsmpInIndex += buffer->frameCount;
4646 buffer->frameCount = 0;
4647}
4648
4649bool AudioFlinger::RecordThread::checkForNewParameters_l()
4650{
4651 bool reconfig = false;
4652
4653 while (!mNewParameters.isEmpty()) {
4654 status_t status = NO_ERROR;
4655 String8 keyValuePair = mNewParameters[0];
4656 AudioParameter param = AudioParameter(keyValuePair);
4657 int value;
Glenn Kasten58f30212012-01-12 12:27:51 -08004658 audio_format_t reqFormat = mFormat;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004659 int reqSamplingRate = mReqSampleRate;
4660 int reqChannelCount = mReqChannelCount;
4661
4662 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4663 reqSamplingRate = value;
4664 reconfig = true;
4665 }
4666 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Glenn Kasten58f30212012-01-12 12:27:51 -08004667 reqFormat = (audio_format_t) value;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004668 reconfig = true;
4669 }
4670 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004671 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672 reconfig = true;
4673 }
4674 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4675 // do not accept frame count changes if tracks are open as the track buffer
4676 // size depends on frame count and correct behavior would not be garantied
4677 // if frame count is changed after track creation
4678 if (mActiveTrack != 0) {
4679 status = INVALID_OPERATION;
4680 } else {
4681 reconfig = true;
4682 }
4683 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004684 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4685 // forward device change to effects that have requested to be
4686 // aware of attached audio device.
4687 for (size_t i = 0; i < mEffectChains.size(); i++) {
4688 mEffectChains[i]->setDevice_l(value);
4689 }
4690 // store input device and output device but do not forward output device to audio HAL.
4691 // Note that status is ignored by the caller for output device
4692 // (see AudioFlinger::setParameters()
4693 if (value & AUDIO_DEVICE_OUT_ALL) {
4694 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4695 status = BAD_VALUE;
4696 } else {
4697 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004698 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4699 if (mTrack != NULL) {
4700 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004701 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004702 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4703 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4704 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004705 }
4706 mDevice |= (uint32_t)value;
4707 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004708 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004709 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004710 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004711 mInput->stream->common.standby(&mInput->stream->common);
4712 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 }
4714 if (reconfig) {
4715 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004716 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004717 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004718 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4719 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004720 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 status = NO_ERROR;
4722 }
4723 if (status == NO_ERROR) {
4724 readInputParameters();
4725 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4726 }
4727 }
4728 }
4729
4730 mNewParameters.removeAt(0);
4731
4732 mParamStatus = status;
4733 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004734 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4735 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004736 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004737 }
4738 return reconfig;
4739}
4740
4741String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4742{
Dima Zavinfce7a472011-04-19 22:30:36 -07004743 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004744 String8 out_s8 = String8();
4745
4746 Mutex::Autolock _l(mLock);
4747 if (initCheck() != NO_ERROR) {
4748 return out_s8;
4749 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004750
Dima Zavin799a70e2011-04-18 16:57:27 -07004751 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004752 out_s8 = String8(s);
4753 free(s);
4754 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755}
4756
4757void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4758 AudioSystem::OutputDescriptor desc;
Glenn Kastena0d68332012-01-27 16:47:15 -08004759 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004760
4761 switch (event) {
4762 case AudioSystem::INPUT_OPENED:
4763 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004764 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004765 desc.samplingRate = mSampleRate;
4766 desc.format = mFormat;
4767 desc.frameCount = mFrameCount;
4768 desc.latency = 0;
4769 param2 = &desc;
4770 break;
4771
4772 case AudioSystem::INPUT_CLOSED:
4773 default:
4774 break;
4775 }
4776 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4777}
4778
4779void AudioFlinger::RecordThread::readInputParameters()
4780{
Glenn Kastene9dd0172012-01-27 18:08:45 -08004781 delete mRsmpInBuffer;
4782 // mRsmpInBuffer is always assigned a new[] below
4783 delete mRsmpOutBuffer;
4784 mRsmpOutBuffer = NULL;
4785 delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004786 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787
Dima Zavin799a70e2011-04-18 16:57:27 -07004788 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004789 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4790 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004791 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004792 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004793 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 mFrameCount = mInputBytes / mFrameSize;
4795 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4796
4797 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4798 {
4799 int channelCount;
4800 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4801 // stereo to mono post process as the resampler always outputs stereo.
4802 if (mChannelCount == 1 && mReqChannelCount == 2) {
4803 channelCount = 1;
4804 } else {
4805 channelCount = 2;
4806 }
4807 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4808 mResampler->setSampleRate(mSampleRate);
4809 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4810 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4811
4812 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4813 if (mChannelCount == 1 && mReqChannelCount == 1) {
4814 mFrameCount >>= 1;
4815 }
4816
4817 }
4818 mRsmpInIndex = mFrameCount;
4819}
4820
4821unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4822{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004823 Mutex::Autolock _l(mLock);
4824 if (initCheck() != NO_ERROR) {
4825 return 0;
4826 }
4827
Dima Zavin799a70e2011-04-18 16:57:27 -07004828 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004829}
4830
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004831uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4832{
4833 Mutex::Autolock _l(mLock);
4834 uint32_t result = 0;
4835 if (getEffectChain_l(sessionId) != 0) {
4836 result = EFFECT_SESSION;
4837 }
4838
4839 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4840 result |= TRACK_SESSION;
4841 }
4842
4843 return result;
4844}
4845
Eric Laurent59bd0da2011-08-01 09:52:20 -07004846AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4847{
4848 Mutex::Autolock _l(mLock);
4849 return mTrack;
4850}
4851
Glenn Kastenaed850d2012-01-26 09:46:34 -08004852AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput() const
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004853{
4854 Mutex::Autolock _l(mLock);
4855 return mInput;
4856}
4857
4858AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4859{
4860 Mutex::Autolock _l(mLock);
4861 AudioStreamIn *input = mInput;
4862 mInput = NULL;
4863 return input;
4864}
4865
4866// this method must always be called either with ThreadBase mLock held or inside the thread loop
4867audio_stream_t* AudioFlinger::RecordThread::stream()
4868{
4869 if (mInput == NULL) {
4870 return NULL;
4871 }
4872 return &mInput->stream->common;
4873}
4874
4875
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876// ----------------------------------------------------------------------------
4877
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004878audio_io_handle_t AudioFlinger::openOutput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08004880 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004881 uint32_t *pChannels,
4882 uint32_t *pLatencyMs,
4883 uint32_t flags)
4884{
4885 status_t status;
4886 PlaybackThread *thread = NULL;
4887 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4888 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08004889 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004890 uint32_t channels = pChannels ? *pChannels : 0;
4891 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004892 audio_stream_out_t *outStream;
4893 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894
Steve Block3856b092011-10-20 11:56:00 +01004895 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004896 pDevices ? *pDevices : 0,
4897 samplingRate,
4898 format,
4899 channels,
4900 flags);
4901
4902 if (pDevices == NULL || *pDevices == 0) {
4903 return 0;
4904 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004905
Mathias Agopian65ab4712010-07-14 17:59:35 -07004906 Mutex::Autolock _l(mLock);
4907
Dima Zavin799a70e2011-04-18 16:57:27 -07004908 outHwDev = findSuitableHwDev_l(*pDevices);
4909 if (outHwDev == NULL)
4910 return 0;
4911
Glenn Kasten58f30212012-01-12 12:27:51 -08004912 status = outHwDev->open_output_stream(outHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07004913 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004914 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004915 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004916 samplingRate,
4917 format,
4918 channels,
4919 status);
4920
4921 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004922 if (outStream != NULL) {
4923 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004924 audio_io_handle_t id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004925
Dima Zavinfce7a472011-04-19 22:30:36 -07004926 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4927 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4928 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004930 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 } else {
4932 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004933 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 }
4935 mPlaybackThreads.add(id, thread);
4936
Glenn Kastena0d68332012-01-27 16:47:15 -08004937 if (pSamplingRate != NULL) *pSamplingRate = samplingRate;
4938 if (pFormat != NULL) *pFormat = format;
4939 if (pChannels != NULL) *pChannels = channels;
4940 if (pLatencyMs != NULL) *pLatencyMs = thread->latency();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004941
4942 // notify client processes of the new output creation
4943 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4944 return id;
4945 }
4946
4947 return 0;
4948}
4949
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004950audio_io_handle_t AudioFlinger::openDuplicateOutput(audio_io_handle_t output1,
4951 audio_io_handle_t output2)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952{
4953 Mutex::Autolock _l(mLock);
4954 MixerThread *thread1 = checkMixerThread_l(output1);
4955 MixerThread *thread2 = checkMixerThread_l(output2);
4956
4957 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004958 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 return 0;
4960 }
4961
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004962 audio_io_handle_t id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4964 thread->addOutputTrack(thread2);
4965 mPlaybackThreads.add(id, thread);
4966 // notify client processes of the new output creation
4967 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4968 return id;
4969}
4970
Glenn Kasten72ef00d2012-01-17 11:09:42 -08004971status_t AudioFlinger::closeOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972{
4973 // keep strong reference on the playback thread so that
4974 // it is not destroyed while exit() is executed
4975 sp <PlaybackThread> thread;
4976 {
4977 Mutex::Autolock _l(mLock);
4978 thread = checkPlaybackThread_l(output);
4979 if (thread == NULL) {
4980 return BAD_VALUE;
4981 }
4982
Steve Block3856b092011-10-20 11:56:00 +01004983 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004985 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004987 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4989 dupThread->removeOutputTrack((MixerThread *)thread.get());
4990 }
4991 }
4992 }
Glenn Kastena0d68332012-01-27 16:47:15 -08004993 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004994 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4995 mPlaybackThreads.removeItem(output);
4996 }
4997 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08004998 // The thread entity (active unit of execution) is no longer running here,
4999 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005001 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005002 AudioStreamOut *out = thread->clearOutput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005003 assert(out != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005004 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005005 out->hwDev->close_output_stream(out->hwDev, out->stream);
5006 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 }
5008 return NO_ERROR;
5009}
5010
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005011status_t AudioFlinger::suspendOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005012{
5013 Mutex::Autolock _l(mLock);
5014 PlaybackThread *thread = checkPlaybackThread_l(output);
5015
5016 if (thread == NULL) {
5017 return BAD_VALUE;
5018 }
5019
Steve Block3856b092011-10-20 11:56:00 +01005020 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 thread->suspend();
5022
5023 return NO_ERROR;
5024}
5025
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005026status_t AudioFlinger::restoreOutput(audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005027{
5028 Mutex::Autolock _l(mLock);
5029 PlaybackThread *thread = checkPlaybackThread_l(output);
5030
5031 if (thread == NULL) {
5032 return BAD_VALUE;
5033 }
5034
Steve Block3856b092011-10-20 11:56:00 +01005035 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036
5037 thread->restore();
5038
5039 return NO_ERROR;
5040}
5041
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005042audio_io_handle_t AudioFlinger::openInput(uint32_t *pDevices,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005043 uint32_t *pSamplingRate,
Glenn Kasten58f30212012-01-12 12:27:51 -08005044 audio_format_t *pFormat,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 uint32_t *pChannels,
Glenn Kastende9719b2012-01-27 12:32:34 -08005046 audio_in_acoustics_t acoustics)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047{
5048 status_t status;
5049 RecordThread *thread = NULL;
5050 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
Glenn Kasten58f30212012-01-12 12:27:51 -08005051 audio_format_t format = pFormat ? *pFormat : AUDIO_FORMAT_DEFAULT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 uint32_t channels = pChannels ? *pChannels : 0;
5053 uint32_t reqSamplingRate = samplingRate;
Glenn Kasten58f30212012-01-12 12:27:51 -08005054 audio_format_t reqFormat = format;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005056 audio_stream_in_t *inStream;
5057 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058
5059 if (pDevices == NULL || *pDevices == 0) {
5060 return 0;
5061 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005062
Mathias Agopian65ab4712010-07-14 17:59:35 -07005063 Mutex::Autolock _l(mLock);
5064
Dima Zavin799a70e2011-04-18 16:57:27 -07005065 inHwDev = findSuitableHwDev_l(*pDevices);
5066 if (inHwDev == NULL)
5067 return 0;
5068
Glenn Kasten58f30212012-01-12 12:27:51 -08005069 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005070 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005071 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005073 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005074 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 samplingRate,
5076 format,
5077 channels,
5078 acoustics,
5079 status);
5080
5081 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5082 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5083 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005085 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005087 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005088 ALOGV("openInput() reopening with proposed sampling rate and channels");
Glenn Kasten58f30212012-01-12 12:27:51 -08005089 status = inHwDev->open_input_stream(inHwDev, *pDevices, &format,
Dima Zavin799a70e2011-04-18 16:57:27 -07005090 &channels, &samplingRate,
Glenn Kastende9719b2012-01-27 12:32:34 -08005091 acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005092 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 }
5094
Dima Zavin799a70e2011-04-18 16:57:27 -07005095 if (inStream != NULL) {
5096 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5097
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005098 audio_io_handle_t id = nextUniqueId();
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005099 // Start record thread
5100 // RecorThread require both input and output device indication to forward to audio
5101 // pre processing modules
5102 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5103 thread = new RecordThread(this,
5104 input,
5105 reqSamplingRate,
5106 reqChannels,
5107 id,
5108 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005110 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Glenn Kastena0d68332012-01-27 16:47:15 -08005111 if (pSamplingRate != NULL) *pSamplingRate = reqSamplingRate;
5112 if (pFormat != NULL) *pFormat = format;
5113 if (pChannels != NULL) *pChannels = reqChannels;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114
Dima Zavin799a70e2011-04-18 16:57:27 -07005115 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116
5117 // notify client processes of the new input creation
5118 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5119 return id;
5120 }
5121
5122 return 0;
5123}
5124
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005125status_t AudioFlinger::closeInput(audio_io_handle_t input)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005126{
5127 // keep strong reference on the record thread so that
5128 // it is not destroyed while exit() is executed
5129 sp <RecordThread> thread;
5130 {
5131 Mutex::Autolock _l(mLock);
5132 thread = checkRecordThread_l(input);
5133 if (thread == NULL) {
5134 return BAD_VALUE;
5135 }
5136
Steve Block3856b092011-10-20 11:56:00 +01005137 ALOGV("closeInput() %d", input);
Glenn Kastena0d68332012-01-27 16:47:15 -08005138 void *param2 = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005139 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5140 mRecordThreads.removeItem(input);
5141 }
5142 thread->exit();
Glenn Kastenb28686f2012-01-06 08:39:38 -08005143 // The thread entity (active unit of execution) is no longer running here,
5144 // but the ThreadBase container still exists.
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005146 AudioStreamIn *in = thread->clearInput();
Glenn Kastenaed850d2012-01-26 09:46:34 -08005147 assert(in != NULL);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005148 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005149 in->hwDev->close_input_stream(in->hwDev, in->stream);
5150 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151
5152 return NO_ERROR;
5153}
5154
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005155status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, audio_io_handle_t output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005156{
5157 Mutex::Autolock _l(mLock);
5158 MixerThread *dstThread = checkMixerThread_l(output);
5159 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005160 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 return BAD_VALUE;
5162 }
5163
Steve Block3856b092011-10-20 11:56:00 +01005164 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005165 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5166
Eric Laurent9f6530f2011-08-30 10:18:54 -07005167 dstThread->setStreamValid(stream, true);
5168
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5170 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5171 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005172 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005174 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176 }
Eric Laurentde070132010-07-13 04:45:46 -07005177 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178
5179 return NO_ERROR;
5180}
5181
5182
5183int AudioFlinger::newAudioSessionId()
5184{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005185 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186}
5187
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005188void AudioFlinger::acquireAudioSessionId(int audioSession)
5189{
5190 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005191 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005192 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005193 int num = mAudioSessionRefs.size();
5194 for (int i = 0; i< num; i++) {
5195 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5196 if (ref->sessionid == audioSession && ref->pid == caller) {
5197 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005198 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005199 return;
5200 }
5201 }
Glenn Kasten84afa3b2012-01-25 15:28:08 -08005202 mAudioSessionRefs.push(new AudioSessionRef(audioSession, caller));
5203 ALOGV(" added new entry for %d", audioSession);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005204}
5205
5206void AudioFlinger::releaseAudioSessionId(int audioSession)
5207{
5208 Mutex::Autolock _l(mLock);
Glenn Kastenbb001922012-02-03 11:10:26 -08005209 pid_t caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005210 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005211 int num = mAudioSessionRefs.size();
5212 for (int i = 0; i< num; i++) {
5213 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5214 if (ref->sessionid == audioSession && ref->pid == caller) {
5215 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005216 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005217 if (ref->cnt == 0) {
5218 mAudioSessionRefs.removeAt(i);
5219 delete ref;
5220 purgeStaleEffects_l();
5221 }
5222 return;
5223 }
5224 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005225 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005226}
5227
5228void AudioFlinger::purgeStaleEffects_l() {
5229
Steve Block3856b092011-10-20 11:56:00 +01005230 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005231
5232 Vector< sp<EffectChain> > chains;
5233
5234 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5235 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5236 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5237 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005238 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5239 chains.push(ec);
5240 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005241 }
5242 }
5243 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5244 sp<RecordThread> t = mRecordThreads.valueAt(i);
5245 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5246 sp<EffectChain> ec = t->mEffectChains[j];
5247 chains.push(ec);
5248 }
5249 }
5250
5251 for (size_t i = 0; i < chains.size(); i++) {
5252 sp<EffectChain> ec = chains[i];
5253 int sessionid = ec->sessionId();
5254 sp<ThreadBase> t = ec->mThread.promote();
5255 if (t == 0) {
5256 continue;
5257 }
5258 size_t numsessionrefs = mAudioSessionRefs.size();
5259 bool found = false;
5260 for (size_t k = 0; k < numsessionrefs; k++) {
5261 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5262 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005263 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005264 sessionid, ref->pid, ref->cnt);
5265 found = true;
5266 break;
5267 }
5268 }
5269 if (!found) {
5270 // remove all effects from the chain
5271 while (ec->mEffects.size()) {
5272 sp<EffectModule> effect = ec->mEffects[0];
5273 effect->unPin();
5274 Mutex::Autolock _l (t->mLock);
5275 t->removeEffect_l(effect);
5276 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5277 sp<EffectHandle> handle = effect->mHandles[j].promote();
5278 if (handle != 0) {
5279 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005280 if (handle->mHasControl && handle->mEnabled) {
5281 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5282 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005283 }
5284 }
5285 AudioSystem::unregisterEffect(effect->id());
5286 }
5287 }
5288 }
5289 return;
5290}
5291
Mathias Agopian65ab4712010-07-14 17:59:35 -07005292// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005293AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294{
5295 PlaybackThread *thread = NULL;
5296 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5297 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5298 }
5299 return thread;
5300}
5301
5302// checkMixerThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005303AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(audio_io_handle_t output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304{
5305 PlaybackThread *thread = checkPlaybackThread_l(output);
5306 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005307 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308 thread = NULL;
5309 }
5310 }
5311 return (MixerThread *)thread;
5312}
5313
5314// checkRecordThread_l() must be called with AudioFlinger::mLock held
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005315AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(audio_io_handle_t input) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005316{
5317 RecordThread *thread = NULL;
5318 if (mRecordThreads.indexOfKey(input) >= 0) {
5319 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5320 }
5321 return thread;
5322}
5323
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005324uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005326 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327}
5328
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005329AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5330{
5331 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5332 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005333 AudioStreamOut *output = thread->getOutput();
5334 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005335 return thread;
5336 }
5337 }
5338 return NULL;
5339}
5340
5341uint32_t AudioFlinger::primaryOutputDevice_l()
5342{
5343 PlaybackThread *thread = primaryPlaybackThread_l();
5344
5345 if (thread == NULL) {
5346 return 0;
5347 }
5348
5349 return thread->device();
5350}
5351
5352
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353// ----------------------------------------------------------------------------
5354// Effect management
5355// ----------------------------------------------------------------------------
5356
5357
Glenn Kastenf587ba52012-01-26 16:25:10 -08005358status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359{
5360 Mutex::Autolock _l(mLock);
5361 return EffectQueryNumberEffects(numEffects);
5362}
5363
Glenn Kastenf587ba52012-01-26 16:25:10 -08005364status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005365{
5366 Mutex::Autolock _l(mLock);
5367 return EffectQueryEffect(index, descriptor);
5368}
5369
Glenn Kasten5e92a782012-01-30 07:40:52 -08005370status_t AudioFlinger::getEffectDescriptor(const effect_uuid_t *pUuid,
Glenn Kastenf587ba52012-01-26 16:25:10 -08005371 effect_descriptor_t *descriptor) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372{
5373 Mutex::Autolock _l(mLock);
5374 return EffectGetDescriptor(pUuid, descriptor);
5375}
5376
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5379 effect_descriptor_t *pDesc,
5380 const sp<IEffectClient>& effectClient,
5381 int32_t priority,
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005382 audio_io_handle_t io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 int sessionId,
5384 status_t *status,
5385 int *id,
5386 int *enabled)
5387{
5388 status_t lStatus = NO_ERROR;
5389 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 effect_descriptor_t desc;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005392 ALOGV("createEffect pid %d, effectClient %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005393 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394
5395 if (pDesc == NULL) {
5396 lStatus = BAD_VALUE;
5397 goto Exit;
5398 }
5399
Eric Laurent84e9a102010-09-23 16:10:16 -07005400 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005401 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005402 lStatus = PERMISSION_DENIED;
5403 goto Exit;
5404 }
5405
Dima Zavinfce7a472011-04-19 22:30:36 -07005406 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005407 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005408 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005409 lStatus = PERMISSION_DENIED;
5410 goto Exit;
5411 }
5412
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005413 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005414 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005415 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005416 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005417 lStatus = BAD_VALUE;
5418 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005419 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005420 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005421 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005423 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 }
5425 }
5426
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 {
5428 Mutex::Autolock _l(mLock);
5429
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430
5431 if (!EffectIsNullUuid(&pDesc->uuid)) {
5432 // if uuid is specified, request effect descriptor
5433 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5434 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005435 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 goto Exit;
5437 }
5438 } else {
5439 // if uuid is not specified, look for an available implementation
5440 // of the required type in effect factory
5441 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005442 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005443 lStatus = BAD_VALUE;
5444 goto Exit;
5445 }
5446 uint32_t numEffects = 0;
5447 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005448 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 bool found = false;
5450
5451 lStatus = EffectQueryNumberEffects(&numEffects);
5452 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005453 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005454 goto Exit;
5455 }
5456 for (uint32_t i = 0; i < numEffects; i++) {
5457 lStatus = EffectQueryEffect(i, &desc);
5458 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005459 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 continue;
5461 }
5462 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5463 // If matching type found save effect descriptor. If the session is
5464 // 0 and the effect is not auxiliary, continue enumeration in case
5465 // an auxiliary version of this effect type is available
5466 found = true;
5467 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005468 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5470 break;
5471 }
5472 }
5473 }
5474 if (!found) {
5475 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005476 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 goto Exit;
5478 }
5479 // For same effect type, chose auxiliary version over insert version if
5480 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005481 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5483 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5484 }
5485 }
5486
5487 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005488 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5490 lStatus = INVALID_OPERATION;
5491 goto Exit;
5492 }
5493
Eric Laurent59255e42011-07-27 19:49:51 -07005494 // check recording permission for visualizer
5495 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5496 !recordingAllowed()) {
5497 lStatus = PERMISSION_DENIED;
5498 goto Exit;
5499 }
5500
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 // return effect descriptor
5502 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5503
5504 // If output is not specified try to find a matching audio session ID in one of the
5505 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005506 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5507 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005508 // Note: io is never 0 when creating an effect on an input
5509 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005510 // look for the thread where the specified audio session is present
5511 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5512 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005513 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005514 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005515 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005517 if (io == 0) {
5518 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5519 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5520 io = mRecordThreads.keyAt(i);
5521 break;
5522 }
5523 }
5524 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005525 // If no output thread contains the requested session ID, default to
5526 // first output. The effect chain will be moved to the correct output
5527 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005528 if (io == 0 && mPlaybackThreads.size()) {
5529 io = mPlaybackThreads.keyAt(0);
5530 }
Steve Block3856b092011-10-20 11:56:00 +01005531 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005532 }
5533 ThreadBase *thread = checkRecordThread_l(io);
5534 if (thread == NULL) {
5535 thread = checkPlaybackThread_l(io);
5536 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005537 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005538 lStatus = BAD_VALUE;
5539 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005540 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005541 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005542
Glenn Kasten98ec94c2012-01-25 14:28:29 -08005543 sp<Client> client = registerPid_l(pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005544
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005545 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005546 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5547 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 if (handle != 0 && id != NULL) {
5549 *id = handle->id();
5550 }
5551 }
5552
5553Exit:
5554 if(status) {
5555 *status = lStatus;
5556 }
5557 return handle;
5558}
5559
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005560status_t AudioFlinger::moveEffects(int sessionId, audio_io_handle_t srcOutput,
5561 audio_io_handle_t dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005562{
Steve Block3856b092011-10-20 11:56:00 +01005563 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005564 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005565 Mutex::Autolock _l(mLock);
5566 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005567 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005568 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569 }
Eric Laurentde070132010-07-13 04:45:46 -07005570 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5571 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005572 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005573 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574 }
Eric Laurentde070132010-07-13 04:45:46 -07005575 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5576 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005577 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005578 return BAD_VALUE;
5579 }
5580
5581 Mutex::Autolock _dl(dstThread->mLock);
5582 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005583 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005584
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585 return NO_ERROR;
5586}
5587
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005588// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005589status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005590 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005591 AudioFlinger::PlaybackThread *dstThread,
5592 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005593{
Steve Block3856b092011-10-20 11:56:00 +01005594 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005595 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005596
Eric Laurent59255e42011-07-27 19:49:51 -07005597 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005598 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005599 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005600 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005601 return INVALID_OPERATION;
5602 }
5603
Eric Laurent39e94f82010-07-28 01:32:47 -07005604 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005605 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005606 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005607 // removed.
5608 srcThread->removeEffectChain_l(chain);
5609
5610 // transfer all effects one by one so that new effect chain is created on new thread with
5611 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Glenn Kasten72ef00d2012-01-17 11:09:42 -08005612 audio_io_handle_t dstOutput = dstThread->id();
Eric Laurent39e94f82010-07-28 01:32:47 -07005613 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005614 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005615 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5616 while (effect != 0) {
5617 srcThread->removeEffect_l(effect);
5618 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005619 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5620 if (effect->state() == EffectModule::ACTIVE ||
5621 effect->state() == EffectModule::STOPPING) {
5622 effect->start();
5623 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005624 // if the move request is not received from audio policy manager, the effect must be
5625 // re-registered with the new strategy and output
5626 if (dstChain == 0) {
5627 dstChain = effect->chain().promote();
5628 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005629 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005630 srcThread->addEffect_l(effect);
5631 return NO_INIT;
5632 }
5633 strategy = dstChain->strategy();
5634 }
5635 if (reRegister) {
5636 AudioSystem::unregisterEffect(effect->id());
5637 AudioSystem::registerEffect(&effect->desc(),
5638 dstOutput,
5639 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005640 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005641 effect->id());
5642 }
Eric Laurentde070132010-07-13 04:45:46 -07005643 effect = chain->getEffectFromId_l(0);
5644 }
5645
5646 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647}
5648
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005649
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005651sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 const sp<AudioFlinger::Client>& client,
5653 const sp<IEffectClient>& effectClient,
5654 int32_t priority,
5655 int sessionId,
5656 effect_descriptor_t *desc,
5657 int *enabled,
5658 status_t *status
5659 )
5660{
5661 sp<EffectModule> effect;
5662 sp<EffectHandle> handle;
5663 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005665 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 bool effectCreated = false;
5667 bool effectRegistered = false;
5668
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005669 lStatus = initCheck();
5670 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005671 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 goto Exit;
5673 }
5674
5675 // Do not allow effects with session ID 0 on direct output or duplicating threads
5676 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005677 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005678 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005679 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 lStatus = BAD_VALUE;
5681 goto Exit;
5682 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005683 // Only Pre processor effects are allowed on input threads and only on input threads
5684 if ((mType == RECORD &&
5685 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5686 (mType != RECORD &&
5687 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005688 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005689 desc->name, desc->flags, mType);
5690 lStatus = BAD_VALUE;
5691 goto Exit;
5692 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693
Steve Block3856b092011-10-20 11:56:00 +01005694 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695
5696 { // scope for mLock
5697 Mutex::Autolock _l(mLock);
5698
5699 // check for existing effect chain with the requested audio session
5700 chain = getEffectChain_l(sessionId);
5701 if (chain == 0) {
5702 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005703 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 chain = new EffectChain(this, sessionId);
5705 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005706 chain->setStrategy(getStrategyForSession_l(sessionId));
5707 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005708 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005709 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 }
5711
Glenn Kasten7fc9a6f2012-01-10 10:46:34 -08005712 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713
5714 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005715 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005717 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 if (lStatus != NO_ERROR) {
5719 goto Exit;
5720 }
5721 effectRegistered = true;
5722 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005723 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 lStatus = effect->status();
5725 if (lStatus != NO_ERROR) {
5726 goto Exit;
5727 }
Eric Laurentcab11242010-07-15 12:50:15 -07005728 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 if (lStatus != NO_ERROR) {
5730 goto Exit;
5731 }
5732 effectCreated = true;
5733
5734 effect->setDevice(mDevice);
5735 effect->setMode(mAudioFlinger->getMode());
5736 }
5737 // create effect handle and connect it to effect module
5738 handle = new EffectHandle(effect, client, effectClient, priority);
5739 lStatus = effect->addHandle(handle);
Glenn Kastena0d68332012-01-27 16:47:15 -08005740 if (enabled != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741 *enabled = (int)effect->isEnabled();
5742 }
5743 }
5744
5745Exit:
5746 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005747 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005749 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 }
5751 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005752 AudioSystem::unregisterEffect(effect->id());
5753 }
5754 if (chainCreated) {
5755 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 }
5757 handle.clear();
5758 }
5759
5760 if(status) {
5761 *status = lStatus;
5762 }
5763 return handle;
5764}
5765
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005766sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5767{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005768 sp<EffectChain> chain = getEffectChain_l(sessionId);
Glenn Kasten090f0192012-01-30 13:00:02 -08005769 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005770}
5771
Eric Laurentde070132010-07-13 04:45:46 -07005772// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5773// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005774status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005775{
5776 // check for existing effect chain with the requested audio session
5777 int sessionId = effect->sessionId();
5778 sp<EffectChain> chain = getEffectChain_l(sessionId);
5779 bool chainCreated = false;
5780
5781 if (chain == 0) {
5782 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005783 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005784 chain = new EffectChain(this, sessionId);
5785 addEffectChain_l(chain);
5786 chain->setStrategy(getStrategyForSession_l(sessionId));
5787 chainCreated = true;
5788 }
Steve Block3856b092011-10-20 11:56:00 +01005789 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005790
5791 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005792 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005793 this, effect->desc().name, chain.get());
5794 return BAD_VALUE;
5795 }
5796
5797 status_t status = chain->addEffect_l(effect);
5798 if (status != NO_ERROR) {
5799 if (chainCreated) {
5800 removeEffectChain_l(chain);
5801 }
5802 return status;
5803 }
5804
5805 effect->setDevice(mDevice);
5806 effect->setMode(mAudioFlinger->getMode());
5807 return NO_ERROR;
5808}
5809
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005810void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005811
Steve Block3856b092011-10-20 11:56:00 +01005812 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005814 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5815 detachAuxEffect_l(effect->id());
5816 }
5817
5818 sp<EffectChain> chain = effect->chain().promote();
5819 if (chain != 0) {
5820 // remove effect chain if removing last effect
5821 if (chain->removeEffect_l(effect) == 0) {
5822 removeEffectChain_l(chain);
5823 }
5824 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005825 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005826 }
5827}
5828
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005829void AudioFlinger::ThreadBase::lockEffectChains_l(
5830 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5831{
5832 effectChains = mEffectChains;
5833 for (size_t i = 0; i < mEffectChains.size(); i++) {
5834 mEffectChains[i]->lock();
5835 }
5836}
5837
5838void AudioFlinger::ThreadBase::unlockEffectChains(
5839 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5840{
5841 for (size_t i = 0; i < effectChains.size(); i++) {
5842 effectChains[i]->unlock();
5843 }
5844}
5845
5846sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5847{
5848 Mutex::Autolock _l(mLock);
5849 return getEffectChain_l(sessionId);
5850}
5851
5852sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5853{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005854 size_t size = mEffectChains.size();
5855 for (size_t i = 0; i < size; i++) {
5856 if (mEffectChains[i]->sessionId() == sessionId) {
Glenn Kasten090f0192012-01-30 13:00:02 -08005857 return mEffectChains[i];
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005858 }
5859 }
Glenn Kasten090f0192012-01-30 13:00:02 -08005860 return 0;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005861}
5862
Glenn Kastenf78aee72012-01-04 11:00:47 -08005863void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005864{
5865 Mutex::Autolock _l(mLock);
5866 size_t size = mEffectChains.size();
5867 for (size_t i = 0; i < size; i++) {
5868 mEffectChains[i]->setMode_l(mode);
5869 }
5870}
5871
5872void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005873 const wp<EffectHandle>& handle,
Glenn Kasten58123c32012-02-03 10:32:24 -08005874 bool unpinIfLast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005875
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005877 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 // delete the effect module if removing last handle on it
5879 if (effect->removeHandle(handle) == 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08005880 if (!effect->isPinned() || unpinIfLast) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005881 removeEffect_l(effect);
5882 AudioSystem::unregisterEffect(effect->id());
5883 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 }
5885}
5886
5887status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5888{
5889 int session = chain->sessionId();
5890 int16_t *buffer = mMixBuffer;
5891 bool ownsBuffer = false;
5892
Steve Block3856b092011-10-20 11:56:00 +01005893 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 if (session > 0) {
5895 // Only one effect chain can be present in direct output thread and it uses
5896 // the mix buffer as input
5897 if (mType != DIRECT) {
5898 size_t numSamples = mFrameCount * mChannelCount;
5899 buffer = new int16_t[numSamples];
5900 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005901 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005902 ownsBuffer = true;
5903 }
5904
5905 // Attach all tracks with same session ID to this chain.
5906 for (size_t i = 0; i < mTracks.size(); ++i) {
5907 sp<Track> track = mTracks[i];
5908 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005909 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005911 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912 }
5913 }
5914
5915 // indicate all active tracks in the chain
5916 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5917 sp<Track> track = mActiveTracks[i].promote();
5918 if (track == 0) continue;
5919 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005920 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005921 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922 }
5923 }
5924 }
5925
5926 chain->setInBuffer(buffer, ownsBuffer);
5927 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005928 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005929 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005930 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5931 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005933 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5934 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005935 // Effect chain for other sessions are inserted at beginning of effect
5936 // chains list to be processed before output mix effects. Relative order between other
5937 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 size_t size = mEffectChains.size();
5939 size_t i = 0;
5940 for (i = 0; i < size; i++) {
5941 if (mEffectChains[i]->sessionId() < session) break;
5942 }
5943 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005944 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945
5946 return NO_ERROR;
5947}
5948
5949size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5950{
5951 int session = chain->sessionId();
5952
Steve Block3856b092011-10-20 11:56:00 +01005953 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954
5955 for (size_t i = 0; i < mEffectChains.size(); i++) {
5956 if (chain == mEffectChains[i]) {
5957 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005958 // detach all active tracks from the chain
5959 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5960 sp<Track> track = mActiveTracks[i].promote();
5961 if (track == 0) continue;
5962 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005963 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005964 chain.get(), session);
5965 chain->decActiveTrackCnt();
5966 }
5967 }
5968
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 // detach all tracks with same session ID from this chain
5970 for (size_t i = 0; i < mTracks.size(); ++i) {
5971 sp<Track> track = mTracks[i];
5972 if (session == track->sessionId()) {
5973 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005974 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005975 }
5976 }
Eric Laurentde070132010-07-13 04:45:46 -07005977 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 }
5979 }
5980 return mEffectChains.size();
5981}
5982
Eric Laurentde070132010-07-13 04:45:46 -07005983status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5984 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985{
5986 Mutex::Autolock _l(mLock);
5987 return attachAuxEffect_l(track, EffectId);
5988}
5989
Eric Laurentde070132010-07-13 04:45:46 -07005990status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5991 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992{
5993 status_t status = NO_ERROR;
5994
5995 if (EffectId == 0) {
5996 track->setAuxBuffer(0, NULL);
5997 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005998 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5999 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000 if (effect != 0) {
6001 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6002 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6003 } else {
6004 status = INVALID_OPERATION;
6005 }
6006 } else {
6007 status = BAD_VALUE;
6008 }
6009 }
6010 return status;
6011}
6012
6013void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6014{
6015 for (size_t i = 0; i < mTracks.size(); ++i) {
6016 sp<Track> track = mTracks[i];
6017 if (track->auxEffectId() == effectId) {
6018 attachAuxEffect_l(track, 0);
6019 }
6020 }
6021}
6022
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006023status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6024{
6025 // only one chain per input thread
6026 if (mEffectChains.size() != 0) {
6027 return INVALID_OPERATION;
6028 }
Steve Block3856b092011-10-20 11:56:00 +01006029 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006030
6031 chain->setInBuffer(NULL);
6032 chain->setOutBuffer(NULL);
6033
Eric Laurent59255e42011-07-27 19:49:51 -07006034 checkSuspendOnAddEffectChain_l(chain);
6035
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036 mEffectChains.add(chain);
6037
6038 return NO_ERROR;
6039}
6040
6041size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6042{
Steve Block3856b092011-10-20 11:56:00 +01006043 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006044 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006045 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6046 chain.get(), mEffectChains.size(), this);
6047 if (mEffectChains.size() == 1) {
6048 mEffectChains.removeAt(0);
6049 }
6050 return 0;
6051}
6052
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053// ----------------------------------------------------------------------------
6054// EffectModule implementation
6055// ----------------------------------------------------------------------------
6056
6057#undef LOG_TAG
6058#define LOG_TAG "AudioFlinger::EffectModule"
6059
6060AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6061 const wp<AudioFlinger::EffectChain>& chain,
6062 effect_descriptor_t *desc,
6063 int id,
6064 int sessionId)
6065 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006066 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006067{
Steve Block3856b092011-10-20 11:56:00 +01006068 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069 int lStatus;
6070 sp<ThreadBase> thread = mThread.promote();
6071 if (thread == 0) {
6072 return;
6073 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074
6075 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6076
6077 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006078 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079
6080 if (mStatus != NO_ERROR) {
6081 return;
6082 }
6083 lStatus = init();
6084 if (lStatus < 0) {
6085 mStatus = lStatus;
6086 goto Error;
6087 }
6088
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006089 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6090 mPinned = true;
6091 }
Steve Block3856b092011-10-20 11:56:00 +01006092 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 return;
6094Error:
6095 EffectRelease(mEffectInterface);
6096 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006097 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098}
6099
6100AudioFlinger::EffectModule::~EffectModule()
6101{
Steve Block3856b092011-10-20 11:56:00 +01006102 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006104 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6105 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6106 sp<ThreadBase> thread = mThread.promote();
6107 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006108 audio_stream_t *stream = thread->stream();
6109 if (stream != NULL) {
6110 stream->remove_audio_effect(stream, mEffectInterface);
6111 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006112 }
6113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114 // release effect engine
6115 EffectRelease(mEffectInterface);
6116 }
6117}
6118
Glenn Kasten435dbe62012-01-30 10:15:48 -08006119status_t AudioFlinger::EffectModule::addHandle(const sp<EffectHandle>& handle)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120{
6121 status_t status;
6122
6123 Mutex::Autolock _l(mLock);
6124 // First handle in mHandles has highest priority and controls the effect module
6125 int priority = handle->priority();
6126 size_t size = mHandles.size();
6127 sp<EffectHandle> h;
6128 size_t i;
6129 for (i = 0; i < size; i++) {
6130 h = mHandles[i].promote();
6131 if (h == 0) continue;
6132 if (h->priority() <= priority) break;
6133 }
6134 // if inserted in first place, move effect control from previous owner to this handle
6135 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006136 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006138 enabled = h->enabled();
6139 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006140 }
Eric Laurent59255e42011-07-27 19:49:51 -07006141 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 status = NO_ERROR;
6143 } else {
6144 status = ALREADY_EXISTS;
6145 }
Steve Block3856b092011-10-20 11:56:00 +01006146 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147 mHandles.insertAt(handle, i);
6148 return status;
6149}
6150
6151size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6152{
6153 Mutex::Autolock _l(mLock);
6154 size_t size = mHandles.size();
6155 size_t i;
6156 for (i = 0; i < size; i++) {
6157 if (mHandles[i] == handle) break;
6158 }
6159 if (i == size) {
6160 return size;
6161 }
Steve Block3856b092011-10-20 11:56:00 +01006162 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006163
6164 bool enabled = false;
6165 EffectHandle *hdl = handle.unsafe_get();
Glenn Kastena0d68332012-01-27 16:47:15 -08006166 if (hdl != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006168 enabled = hdl->enabled();
6169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 mHandles.removeAt(i);
6171 size = mHandles.size();
6172 // if removed from first place, move effect control from this handle to next in line
6173 if (i == 0 && size != 0) {
6174 sp<EffectHandle> h = mHandles[0].promote();
6175 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006176 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 }
6178 }
6179
Eric Laurentec437d82011-07-26 20:54:46 -07006180 // Prevent calls to process() and other functions on effect interface from now on.
6181 // The effect engine will be released by the destructor when the last strong reference on
6182 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006183 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006184 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006185 }
6186
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 return size;
6188}
6189
Eric Laurent59255e42011-07-27 19:49:51 -07006190sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6191{
6192 Mutex::Autolock _l(mLock);
Glenn Kasten090f0192012-01-30 13:00:02 -08006193 return mHandles.size() != 0 ? mHandles[0].promote() : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07006194}
6195
Glenn Kasten58123c32012-02-03 10:32:24 -08006196void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpinIfLast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006197{
Glenn Kasten90bebef2012-01-27 15:24:38 -08006198 ALOGV("disconnect() %p handle %p", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199 // keep a strong reference on this EffectModule to avoid calling the
6200 // destructor before we exit
6201 sp<EffectModule> keep(this);
6202 {
6203 sp<ThreadBase> thread = mThread.promote();
6204 if (thread != 0) {
Glenn Kasten58123c32012-02-03 10:32:24 -08006205 thread->disconnectEffect(keep, handle, unpinIfLast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 }
6207 }
6208}
6209
6210void AudioFlinger::EffectModule::updateState() {
6211 Mutex::Autolock _l(mLock);
6212
6213 switch (mState) {
6214 case RESTART:
6215 reset_l();
6216 // FALL THROUGH
6217
6218 case STARTING:
6219 // clear auxiliary effect input buffer for next accumulation
6220 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6221 memset(mConfig.inputCfg.buffer.raw,
6222 0,
6223 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6224 }
6225 start_l();
6226 mState = ACTIVE;
6227 break;
6228 case STOPPING:
6229 stop_l();
6230 mDisableWaitCnt = mMaxDisableWaitCnt;
6231 mState = STOPPED;
6232 break;
6233 case STOPPED:
6234 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6235 // turn off sequence.
6236 if (--mDisableWaitCnt == 0) {
6237 reset_l();
6238 mState = IDLE;
6239 }
6240 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006241 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 break;
6243 }
6244}
6245
6246void AudioFlinger::EffectModule::process()
6247{
6248 Mutex::Autolock _l(mLock);
6249
Eric Laurentec437d82011-07-26 20:54:46 -07006250 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 mConfig.inputCfg.buffer.raw == NULL ||
6252 mConfig.outputCfg.buffer.raw == NULL) {
6253 return;
6254 }
6255
Eric Laurent8f45bd72010-08-31 13:50:07 -07006256 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006257 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6258 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006259 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006261 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 }
6263
6264 // do the actual processing in the effect engine
6265 int ret = (*mEffectInterface)->process(mEffectInterface,
6266 &mConfig.inputCfg.buffer,
6267 &mConfig.outputCfg.buffer);
6268
6269 // force transition to IDLE state when engine is ready
6270 if (mState == STOPPED && ret == -ENODATA) {
6271 mDisableWaitCnt = 1;
6272 }
6273
6274 // clear auxiliary effect input buffer for next accumulation
6275 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006276 memset(mConfig.inputCfg.buffer.raw, 0,
6277 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 }
6279 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006280 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6281 // If an insert effect is idle and input buffer is different from output buffer,
6282 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006284 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006285 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6286 int16_t *in = mConfig.inputCfg.buffer.s16;
6287 int16_t *out = mConfig.outputCfg.buffer.s16;
6288 for (size_t i = 0; i < frameCnt; i++) {
6289 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006291 }
6292 }
6293}
6294
6295void AudioFlinger::EffectModule::reset_l()
6296{
6297 if (mEffectInterface == NULL) {
6298 return;
6299 }
6300 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6301}
6302
6303status_t AudioFlinger::EffectModule::configure()
6304{
6305 uint32_t channels;
6306 if (mEffectInterface == NULL) {
6307 return NO_INIT;
6308 }
6309
6310 sp<ThreadBase> thread = mThread.promote();
6311 if (thread == 0) {
6312 return DEAD_OBJECT;
6313 }
6314
6315 // TODO: handle configuration of effects replacing track process
6316 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006317 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006318 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006319 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006320 }
6321
6322 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006323 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 } else {
6325 mConfig.inputCfg.channels = channels;
6326 }
6327 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006328 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6329 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006330 mConfig.inputCfg.samplingRate = thread->sampleRate();
6331 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6332 mConfig.inputCfg.bufferProvider.cookie = NULL;
6333 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6334 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6335 mConfig.outputCfg.bufferProvider.cookie = NULL;
6336 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6337 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6338 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6339 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006340 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006341 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342 // - in other sessions:
6343 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6344 // other effect: overwrites output buffer: input buffer == output buffer
6345 // Auxiliary effect:
6346 // accumulates in output buffer: input buffer != output buffer
6347 // Therefore: accumulate <=> input buffer != output buffer
6348 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6349 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6350 } else {
6351 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6352 }
6353 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6354 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6355 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6356 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6357
Steve Block3856b092011-10-20 11:56:00 +01006358 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006359 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6360
Mathias Agopian65ab4712010-07-14 17:59:35 -07006361 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006362 uint32_t size = sizeof(int);
6363 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006364 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006365 sizeof(effect_config_t),
6366 &mConfig,
6367 &size,
6368 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006369 if (status == 0) {
6370 status = cmdStatus;
6371 }
6372
6373 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6374 (1000 * mConfig.outputCfg.buffer.frameCount);
6375
6376 return status;
6377}
6378
6379status_t AudioFlinger::EffectModule::init()
6380{
6381 Mutex::Autolock _l(mLock);
6382 if (mEffectInterface == NULL) {
6383 return NO_INIT;
6384 }
6385 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006386 uint32_t size = sizeof(status_t);
6387 status_t status = (*mEffectInterface)->command(mEffectInterface,
6388 EFFECT_CMD_INIT,
6389 0,
6390 NULL,
6391 &size,
6392 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006393 if (status == 0) {
6394 status = cmdStatus;
6395 }
6396 return status;
6397}
6398
Eric Laurentec35a142011-10-05 17:42:25 -07006399status_t AudioFlinger::EffectModule::start()
6400{
6401 Mutex::Autolock _l(mLock);
6402 return start_l();
6403}
6404
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405status_t AudioFlinger::EffectModule::start_l()
6406{
6407 if (mEffectInterface == NULL) {
6408 return NO_INIT;
6409 }
6410 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006411 uint32_t size = sizeof(status_t);
6412 status_t status = (*mEffectInterface)->command(mEffectInterface,
6413 EFFECT_CMD_ENABLE,
6414 0,
6415 NULL,
6416 &size,
6417 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006418 if (status == 0) {
6419 status = cmdStatus;
6420 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006421 if (status == 0 &&
6422 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6423 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6424 sp<ThreadBase> thread = mThread.promote();
6425 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006426 audio_stream_t *stream = thread->stream();
6427 if (stream != NULL) {
6428 stream->add_audio_effect(stream, mEffectInterface);
6429 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006430 }
6431 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006432 return status;
6433}
6434
Eric Laurentec437d82011-07-26 20:54:46 -07006435status_t AudioFlinger::EffectModule::stop()
6436{
6437 Mutex::Autolock _l(mLock);
6438 return stop_l();
6439}
6440
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441status_t AudioFlinger::EffectModule::stop_l()
6442{
6443 if (mEffectInterface == NULL) {
6444 return NO_INIT;
6445 }
6446 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006447 uint32_t size = sizeof(status_t);
6448 status_t status = (*mEffectInterface)->command(mEffectInterface,
6449 EFFECT_CMD_DISABLE,
6450 0,
6451 NULL,
6452 &size,
6453 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 if (status == 0) {
6455 status = cmdStatus;
6456 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006457 if (status == 0 &&
6458 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6459 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6460 sp<ThreadBase> thread = mThread.promote();
6461 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006462 audio_stream_t *stream = thread->stream();
6463 if (stream != NULL) {
6464 stream->remove_audio_effect(stream, mEffectInterface);
6465 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006466 }
6467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 return status;
6469}
6470
Eric Laurent25f43952010-07-28 05:40:18 -07006471status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6472 uint32_t cmdSize,
6473 void *pCmdData,
6474 uint32_t *replySize,
6475 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476{
6477 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006478// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006479
Eric Laurentec437d82011-07-26 20:54:46 -07006480 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 return NO_INIT;
6482 }
Eric Laurent25f43952010-07-28 05:40:18 -07006483 status_t status = (*mEffectInterface)->command(mEffectInterface,
6484 cmdCode,
6485 cmdSize,
6486 pCmdData,
6487 replySize,
6488 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006490 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491 for (size_t i = 1; i < mHandles.size(); i++) {
6492 sp<EffectHandle> h = mHandles[i].promote();
6493 if (h != 0) {
6494 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6495 }
6496 }
6497 }
6498 return status;
6499}
6500
6501status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6502{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006503
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006505 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506
6507 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006508 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6509 if (enabled && status != NO_ERROR) {
6510 return status;
6511 }
6512
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513 switch (mState) {
6514 // going from disabled to enabled
6515 case IDLE:
6516 mState = STARTING;
6517 break;
6518 case STOPPED:
6519 mState = RESTART;
6520 break;
6521 case STOPPING:
6522 mState = ACTIVE;
6523 break;
6524
6525 // going from enabled to disabled
6526 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006527 mState = STOPPED;
6528 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529 case STARTING:
6530 mState = IDLE;
6531 break;
6532 case ACTIVE:
6533 mState = STOPPING;
6534 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006535 case DESTROYED:
6536 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006537 }
6538 for (size_t i = 1; i < mHandles.size(); i++) {
6539 sp<EffectHandle> h = mHandles[i].promote();
6540 if (h != 0) {
6541 h->setEnabled(enabled);
6542 }
6543 }
6544 }
6545 return NO_ERROR;
6546}
6547
Glenn Kastenc59c0042012-02-02 14:06:11 -08006548bool AudioFlinger::EffectModule::isEnabled() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549{
6550 switch (mState) {
6551 case RESTART:
6552 case STARTING:
6553 case ACTIVE:
6554 return true;
6555 case IDLE:
6556 case STOPPING:
6557 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006558 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 default:
6560 return false;
6561 }
6562}
6563
Glenn Kastenc59c0042012-02-02 14:06:11 -08006564bool AudioFlinger::EffectModule::isProcessEnabled() const
Eric Laurent8f45bd72010-08-31 13:50:07 -07006565{
6566 switch (mState) {
6567 case RESTART:
6568 case ACTIVE:
6569 case STOPPING:
6570 case STOPPED:
6571 return true;
6572 case IDLE:
6573 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006574 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006575 default:
6576 return false;
6577 }
6578}
6579
Mathias Agopian65ab4712010-07-14 17:59:35 -07006580status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6581{
6582 Mutex::Autolock _l(mLock);
6583 status_t status = NO_ERROR;
6584
6585 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6586 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006587 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006588 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6589 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 status_t cmdStatus;
6591 uint32_t volume[2];
6592 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006593 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594 volume[0] = *left;
6595 volume[1] = *right;
6596 if (controller) {
6597 pVolume = volume;
6598 }
Eric Laurent25f43952010-07-28 05:40:18 -07006599 status = (*mEffectInterface)->command(mEffectInterface,
6600 EFFECT_CMD_SET_VOLUME,
6601 size,
6602 volume,
6603 &size,
6604 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006605 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6606 *left = volume[0];
6607 *right = volume[1];
6608 }
6609 }
6610 return status;
6611}
6612
6613status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6614{
6615 Mutex::Autolock _l(mLock);
6616 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006617 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6618 // audio pre processing modules on RecordThread can receive both output and
6619 // input device indication in the same call
6620 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6621 if (dev) {
6622 status_t cmdStatus;
6623 uint32_t size = sizeof(status_t);
6624
6625 status = (*mEffectInterface)->command(mEffectInterface,
6626 EFFECT_CMD_SET_DEVICE,
6627 sizeof(uint32_t),
6628 &dev,
6629 &size,
6630 &cmdStatus);
6631 if (status == NO_ERROR) {
6632 status = cmdStatus;
6633 }
6634 }
6635 dev = device & AUDIO_DEVICE_IN_ALL;
6636 if (dev) {
6637 status_t cmdStatus;
6638 uint32_t size = sizeof(status_t);
6639
6640 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6641 EFFECT_CMD_SET_INPUT_DEVICE,
6642 sizeof(uint32_t),
6643 &dev,
6644 &size,
6645 &cmdStatus);
6646 if (status2 == NO_ERROR) {
6647 status2 = cmdStatus;
6648 }
6649 if (status == NO_ERROR) {
6650 status = status2;
6651 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006652 }
6653 }
6654 return status;
6655}
6656
Glenn Kastenf78aee72012-01-04 11:00:47 -08006657status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006658{
6659 Mutex::Autolock _l(mLock);
6660 status_t status = NO_ERROR;
6661 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006662 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006663 uint32_t size = sizeof(status_t);
6664 status = (*mEffectInterface)->command(mEffectInterface,
6665 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006666 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006667 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006668 &size,
6669 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 if (status == NO_ERROR) {
6671 status = cmdStatus;
6672 }
6673 }
6674 return status;
6675}
6676
Eric Laurent59255e42011-07-27 19:49:51 -07006677void AudioFlinger::EffectModule::setSuspended(bool suspended)
6678{
6679 Mutex::Autolock _l(mLock);
6680 mSuspended = suspended;
6681}
Glenn Kastena3a85482012-01-04 11:01:11 -08006682
6683bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006684{
6685 Mutex::Autolock _l(mLock);
6686 return mSuspended;
6687}
6688
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6690{
6691 const size_t SIZE = 256;
6692 char buffer[SIZE];
6693 String8 result;
6694
6695 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6696 result.append(buffer);
6697
6698 bool locked = tryLock(mLock);
6699 // failed to lock - AudioFlinger is probably deadlocked
6700 if (!locked) {
6701 result.append("\t\tCould not lock Fx mutex:\n");
6702 }
6703
6704 result.append("\t\tSession Status State Engine:\n");
6705 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6706 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6707 result.append(buffer);
6708
6709 result.append("\t\tDescriptor:\n");
6710 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6711 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6712 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6713 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6714 result.append(buffer);
6715 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6716 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6717 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6718 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6719 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006720 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006721 mDescriptor.apiVersion,
6722 mDescriptor.flags);
6723 result.append(buffer);
6724 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6725 mDescriptor.name);
6726 result.append(buffer);
6727 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6728 mDescriptor.implementor);
6729 result.append(buffer);
6730
6731 result.append("\t\t- Input configuration:\n");
6732 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6733 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6734 (uint32_t)mConfig.inputCfg.buffer.raw,
6735 mConfig.inputCfg.buffer.frameCount,
6736 mConfig.inputCfg.samplingRate,
6737 mConfig.inputCfg.channels,
6738 mConfig.inputCfg.format);
6739 result.append(buffer);
6740
6741 result.append("\t\t- Output configuration:\n");
6742 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6743 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6744 (uint32_t)mConfig.outputCfg.buffer.raw,
6745 mConfig.outputCfg.buffer.frameCount,
6746 mConfig.outputCfg.samplingRate,
6747 mConfig.outputCfg.channels,
6748 mConfig.outputCfg.format);
6749 result.append(buffer);
6750
6751 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6752 result.append(buffer);
6753 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6754 for (size_t i = 0; i < mHandles.size(); ++i) {
6755 sp<EffectHandle> handle = mHandles[i].promote();
6756 if (handle != 0) {
6757 handle->dump(buffer, SIZE);
6758 result.append(buffer);
6759 }
6760 }
6761
6762 result.append("\n");
6763
6764 write(fd, result.string(), result.length());
6765
6766 if (locked) {
6767 mLock.unlock();
6768 }
6769
6770 return NO_ERROR;
6771}
6772
6773// ----------------------------------------------------------------------------
6774// EffectHandle implementation
6775// ----------------------------------------------------------------------------
6776
6777#undef LOG_TAG
6778#define LOG_TAG "AudioFlinger::EffectHandle"
6779
6780AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6781 const sp<AudioFlinger::Client>& client,
6782 const sp<IEffectClient>& effectClient,
6783 int32_t priority)
6784 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006785 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006786 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787{
Steve Block3856b092011-10-20 11:56:00 +01006788 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006789
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006790 if (client == 0) {
6791 return;
6792 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006793 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6794 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6795 if (mCblkMemory != 0) {
6796 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6797
Glenn Kastena0d68332012-01-27 16:47:15 -08006798 if (mCblk != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799 new(mCblk) effect_param_cblk_t();
6800 mBuffer = (uint8_t *)mCblk + bufOffset;
6801 }
6802 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006803 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006804 return;
6805 }
6806}
6807
6808AudioFlinger::EffectHandle::~EffectHandle()
6809{
Steve Block3856b092011-10-20 11:56:00 +01006810 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006811 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006812 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813}
6814
6815status_t AudioFlinger::EffectHandle::enable()
6816{
Steve Block3856b092011-10-20 11:56:00 +01006817 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006818 if (!mHasControl) return INVALID_OPERATION;
6819 if (mEffect == 0) return DEAD_OBJECT;
6820
Eric Laurentdb7c0792011-08-10 10:37:50 -07006821 if (mEnabled) {
6822 return NO_ERROR;
6823 }
6824
Eric Laurent59255e42011-07-27 19:49:51 -07006825 mEnabled = true;
6826
6827 sp<ThreadBase> thread = mEffect->thread().promote();
6828 if (thread != 0) {
6829 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6830 }
6831
6832 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6833 if (mEffect->suspended()) {
6834 return NO_ERROR;
6835 }
6836
Eric Laurentdb7c0792011-08-10 10:37:50 -07006837 status_t status = mEffect->setEnabled(true);
6838 if (status != NO_ERROR) {
6839 if (thread != 0) {
6840 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6841 }
6842 mEnabled = false;
6843 }
6844 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006845}
6846
6847status_t AudioFlinger::EffectHandle::disable()
6848{
Steve Block3856b092011-10-20 11:56:00 +01006849 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006850 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006851 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852
Eric Laurentdb7c0792011-08-10 10:37:50 -07006853 if (!mEnabled) {
6854 return NO_ERROR;
6855 }
Eric Laurent59255e42011-07-27 19:49:51 -07006856 mEnabled = false;
6857
6858 if (mEffect->suspended()) {
6859 return NO_ERROR;
6860 }
6861
6862 status_t status = mEffect->setEnabled(false);
6863
6864 sp<ThreadBase> thread = mEffect->thread().promote();
6865 if (thread != 0) {
6866 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6867 }
6868
6869 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870}
6871
6872void AudioFlinger::EffectHandle::disconnect()
6873{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006874 disconnect(true);
6875}
6876
Glenn Kasten58123c32012-02-03 10:32:24 -08006877void AudioFlinger::EffectHandle::disconnect(bool unpinIfLast)
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006878{
Glenn Kasten58123c32012-02-03 10:32:24 -08006879 ALOGV("disconnect(%s)", unpinIfLast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 if (mEffect == 0) {
6881 return;
6882 }
Glenn Kasten58123c32012-02-03 10:32:24 -08006883 mEffect->disconnect(this, unpinIfLast);
Eric Laurent59255e42011-07-27 19:49:51 -07006884
Eric Laurenta85a74a2011-10-19 11:44:54 -07006885 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006886 sp<ThreadBase> thread = mEffect->thread().promote();
6887 if (thread != 0) {
6888 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6889 }
Eric Laurent59255e42011-07-27 19:49:51 -07006890 }
6891
Mathias Agopian65ab4712010-07-14 17:59:35 -07006892 // release sp on module => module destructor can be called now
6893 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 if (mClient != 0) {
Glenn Kastena0d68332012-01-27 16:47:15 -08006895 if (mCblk != NULL) {
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -08006896 // unlike ~TrackBase(), mCblk is never a local new, so don't delete
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006897 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6898 }
Glenn Kastendbfafaf2012-01-25 15:27:15 -08006899 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to
Glenn Kasten98ec94c2012-01-25 14:28:29 -08006900 // Client destructor must run with AudioFlinger mutex locked
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6902 mClient.clear();
6903 }
6904}
6905
Eric Laurent25f43952010-07-28 05:40:18 -07006906status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6907 uint32_t cmdSize,
6908 void *pCmdData,
6909 uint32_t *replySize,
6910 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911{
Steve Block3856b092011-10-20 11:56:00 +01006912// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006913// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914
6915 // only get parameter command is permitted for applications not controlling the effect
6916 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6917 return INVALID_OPERATION;
6918 }
6919 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006920 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921
6922 // handle commands that are not forwarded transparently to effect engine
6923 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6924 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6925 // no risk to block the whole media server process or mixer threads is we are stuck here
6926 Mutex::Autolock _l(mCblk->lock);
6927 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6928 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6929 mCblk->serverIndex = 0;
6930 mCblk->clientIndex = 0;
6931 return BAD_VALUE;
6932 }
6933 status_t status = NO_ERROR;
6934 while (mCblk->serverIndex < mCblk->clientIndex) {
6935 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006936 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006937 int *p = (int *)(mBuffer + mCblk->serverIndex);
6938 int size = *p++;
6939 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006940 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941 break;
6942 }
6943 effect_param_t *param = (effect_param_t *)p;
6944 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006945 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006946 mCblk->serverIndex += size;
6947 continue;
6948 }
Eric Laurent25f43952010-07-28 05:40:18 -07006949 uint32_t psize = sizeof(effect_param_t) +
6950 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6951 param->vsize;
6952 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6953 psize,
6954 p,
6955 &rsize,
6956 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006957 // stop at first error encountered
6958 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006960 *(int *)pReplyData = reply;
6961 break;
6962 } else if (reply != NO_ERROR) {
6963 *(int *)pReplyData = reply;
6964 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965 }
6966 mCblk->serverIndex += size;
6967 }
6968 mCblk->serverIndex = 0;
6969 mCblk->clientIndex = 0;
6970 return status;
6971 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006972 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 return enable();
6974 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006975 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 return disable();
6977 }
6978
6979 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6980}
6981
Eric Laurent59255e42011-07-27 19:49:51 -07006982void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983{
Steve Block3856b092011-10-20 11:56:00 +01006984 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985
6986 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006987 mEnabled = enabled;
6988
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 if (signal && mEffectClient != 0) {
6990 mEffectClient->controlStatusChanged(hasControl);
6991 }
6992}
6993
Eric Laurent25f43952010-07-28 05:40:18 -07006994void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6995 uint32_t cmdSize,
6996 void *pCmdData,
6997 uint32_t replySize,
6998 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999{
7000 if (mEffectClient != 0) {
7001 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7002 }
7003}
7004
7005
7006
7007void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7008{
7009 if (mEffectClient != 0) {
7010 mEffectClient->enableStatusChanged(enabled);
7011 }
7012}
7013
7014status_t AudioFlinger::EffectHandle::onTransact(
7015 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7016{
7017 return BnEffect::onTransact(code, data, reply, flags);
7018}
7019
7020
7021void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7022{
Glenn Kastena0d68332012-01-27 16:47:15 -08007023 bool locked = mCblk != NULL && tryLock(mCblk->lock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024
7025 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
Glenn Kasten7378ca52012-01-20 13:44:40 -08007026 (mClient == 0) ? getpid() : mClient->pid(),
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 mPriority,
7028 mHasControl,
7029 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007030 mCblk ? mCblk->clientIndex : 0,
7031 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 );
7033
7034 if (locked) {
7035 mCblk->lock.unlock();
7036 }
7037}
7038
7039#undef LOG_TAG
7040#define LOG_TAG "AudioFlinger::EffectChain"
7041
7042AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7043 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007044 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007045 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7046 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047{
Dima Zavinfce7a472011-04-19 22:30:36 -07007048 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007049 sp<ThreadBase> thread = mThread.promote();
7050 if (thread == 0) {
7051 return;
7052 }
7053 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7054 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055}
7056
7057AudioFlinger::EffectChain::~EffectChain()
7058{
7059 if (mOwnInBuffer) {
7060 delete mInBuffer;
7061 }
7062
7063}
7064
Eric Laurent59255e42011-07-27 19:49:51 -07007065// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007066sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068 size_t size = mEffects.size();
7069
7070 for (size_t i = 0; i < size; i++) {
7071 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007072 return mEffects[i];
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073 }
7074 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007075 return 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076}
7077
Eric Laurent59255e42011-07-27 19:49:51 -07007078// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007079sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080{
Mathias Agopian65ab4712010-07-14 17:59:35 -07007081 size_t size = mEffects.size();
7082
7083 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007084 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7085 if (id == 0 || mEffects[i]->id() == id) {
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// getEffectFromType_l() must be called with ThreadBase::mLock held
7093sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7094 const effect_uuid_t *type)
7095{
Eric Laurent59255e42011-07-27 19:49:51 -07007096 size_t size = mEffects.size();
7097
7098 for (size_t i = 0; i < size; i++) {
7099 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
Glenn Kasten090f0192012-01-30 13:00:02 -08007100 return mEffects[i];
Eric Laurent59255e42011-07-27 19:49:51 -07007101 }
7102 }
Glenn Kasten090f0192012-01-30 13:00:02 -08007103 return 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007104}
7105
Mathias Agopian65ab4712010-07-14 17:59:35 -07007106// Must be called with EffectChain::mLock locked
7107void AudioFlinger::EffectChain::process_l()
7108{
Eric Laurentdac69112010-09-28 14:09:57 -07007109 sp<ThreadBase> thread = mThread.promote();
7110 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007111 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007112 return;
7113 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007114 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7115 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007116 // always process effects unless no more tracks are on the session and the effect tail
7117 // has been rendered
7118 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007119 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007120 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007121
Eric Laurent544fe9b2011-11-11 15:42:52 -08007122 if (!tracksOnSession && mTailBufferCount == 0) {
7123 doProcess = false;
7124 }
7125
7126 if (activeTrackCnt() == 0) {
7127 // if no track is active and the effect tail has not been rendered,
7128 // the input buffer must be cleared here as the mixer process will not do it
7129 if (tracksOnSession || mTailBufferCount > 0) {
7130 size_t numSamples = thread->frameCount() * thread->channelCount();
7131 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7132 if (mTailBufferCount > 0) {
7133 mTailBufferCount--;
7134 }
7135 }
7136 }
Eric Laurentdac69112010-09-28 14:09:57 -07007137 }
7138
Mathias Agopian65ab4712010-07-14 17:59:35 -07007139 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007140 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007141 for (size_t i = 0; i < size; i++) {
7142 mEffects[i]->process();
7143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144 }
7145 for (size_t i = 0; i < size; i++) {
7146 mEffects[i]->updateState();
7147 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148}
7149
Eric Laurentcab11242010-07-15 12:50:15 -07007150// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007151status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152{
7153 effect_descriptor_t desc = effect->desc();
7154 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7155
7156 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007157 effect->setChain(this);
7158 sp<ThreadBase> thread = mThread.promote();
7159 if (thread == 0) {
7160 return NO_INIT;
7161 }
7162 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163
7164 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7165 // Auxiliary effects are inserted at the beginning of mEffects vector as
7166 // they are processed first and accumulated in chain input buffer
7167 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007168
Mathias Agopian65ab4712010-07-14 17:59:35 -07007169 // the input buffer for auxiliary effect contains mono samples in
7170 // 32 bit format. This is to avoid saturation in AudoMixer
7171 // accumulation stage. Saturation is done in EffectModule::process() before
7172 // calling the process in effect engine
7173 size_t numSamples = thread->frameCount();
7174 int32_t *buffer = new int32_t[numSamples];
7175 memset(buffer, 0, numSamples * sizeof(int32_t));
7176 effect->setInBuffer((int16_t *)buffer);
7177 // auxiliary effects output samples to chain input buffer for further processing
7178 // by insert effects
7179 effect->setOutBuffer(mInBuffer);
7180 } else {
7181 // Insert effects are inserted at the end of mEffects vector as they are processed
7182 // after track and auxiliary effects.
7183 // Insert effect order as a function of indicated preference:
7184 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7185 // another effect is present
7186 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7187 // last effect claiming first position
7188 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7189 // first effect claiming last position
7190 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7191 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7192 // already present
7193
7194 int size = (int)mEffects.size();
7195 int idx_insert = size;
7196 int idx_insert_first = -1;
7197 int idx_insert_last = -1;
7198
7199 for (int i = 0; i < size; i++) {
7200 effect_descriptor_t d = mEffects[i]->desc();
7201 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7202 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7203 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7204 // check invalid effect chaining combinations
7205 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7206 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007207 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 return INVALID_OPERATION;
7209 }
7210 // remember position of first insert effect and by default
7211 // select this as insert position for new effect
7212 if (idx_insert == size) {
7213 idx_insert = i;
7214 }
7215 // remember position of last insert effect claiming
7216 // first position
7217 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7218 idx_insert_first = i;
7219 }
7220 // remember position of first insert effect claiming
7221 // last position
7222 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7223 idx_insert_last == -1) {
7224 idx_insert_last = i;
7225 }
7226 }
7227 }
7228
7229 // modify idx_insert from first position if needed
7230 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7231 if (idx_insert_last != -1) {
7232 idx_insert = idx_insert_last;
7233 } else {
7234 idx_insert = size;
7235 }
7236 } else {
7237 if (idx_insert_first != -1) {
7238 idx_insert = idx_insert_first + 1;
7239 }
7240 }
7241
7242 // always read samples from chain input buffer
7243 effect->setInBuffer(mInBuffer);
7244
7245 // if last effect in the chain, output samples to chain
7246 // output buffer, otherwise to chain input buffer
7247 if (idx_insert == size) {
7248 if (idx_insert != 0) {
7249 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7250 mEffects[idx_insert-1]->configure();
7251 }
7252 effect->setOutBuffer(mOutBuffer);
7253 } else {
7254 effect->setOutBuffer(mInBuffer);
7255 }
7256 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257
Steve Block3856b092011-10-20 11:56:00 +01007258 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007259 }
7260 effect->configure();
7261 return NO_ERROR;
7262}
7263
Eric Laurentcab11242010-07-15 12:50:15 -07007264// removeEffect_l() must be called with PlaybackThread::mLock held
7265size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266{
7267 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007268 int size = (int)mEffects.size();
7269 int i;
7270 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7271
7272 for (i = 0; i < size; i++) {
7273 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007274 // calling stop here will remove pre-processing effect from the audio HAL.
7275 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7276 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007277 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7278 mEffects[i]->state() == EffectModule::STOPPING) {
7279 mEffects[i]->stop();
7280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7282 delete[] effect->inBuffer();
7283 } else {
7284 if (i == size - 1 && i != 0) {
7285 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7286 mEffects[i - 1]->configure();
7287 }
7288 }
7289 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007290 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007291 break;
7292 }
7293 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007294
7295 return mEffects.size();
7296}
7297
Eric Laurentcab11242010-07-15 12:50:15 -07007298// setDevice_l() must be called with PlaybackThread::mLock held
7299void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300{
7301 size_t size = mEffects.size();
7302 for (size_t i = 0; i < size; i++) {
7303 mEffects[i]->setDevice(device);
7304 }
7305}
7306
Eric Laurentcab11242010-07-15 12:50:15 -07007307// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007308void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309{
7310 size_t size = mEffects.size();
7311 for (size_t i = 0; i < size; i++) {
7312 mEffects[i]->setMode(mode);
7313 }
7314}
7315
Eric Laurentcab11242010-07-15 12:50:15 -07007316// setVolume_l() must be called with PlaybackThread::mLock held
7317bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318{
7319 uint32_t newLeft = *left;
7320 uint32_t newRight = *right;
7321 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007322 int ctrlIdx = -1;
7323 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324
Eric Laurentcab11242010-07-15 12:50:15 -07007325 // first update volume controller
7326 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007327 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007328 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7329 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007330 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007331 break;
7332 }
7333 }
7334
7335 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007336 if (hasControl) {
7337 *left = mNewLeftVolume;
7338 *right = mNewRightVolume;
7339 }
7340 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007341 }
7342
7343 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007344 mLeftVolume = newLeft;
7345 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007346
7347 // second get volume update from volume controller
7348 if (ctrlIdx >= 0) {
7349 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007350 mNewLeftVolume = newLeft;
7351 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352 }
7353 // then indicate volume to all other effects in chain.
7354 // Pass altered volume to effects before volume controller
7355 // and requested volume to effects after controller
7356 uint32_t lVol = newLeft;
7357 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007358
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007360 if ((int)i == ctrlIdx) continue;
7361 // this also works for ctrlIdx == -1 when there is no volume controller
7362 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007363 lVol = *left;
7364 rVol = *right;
7365 }
7366 mEffects[i]->setVolume(&lVol, &rVol, false);
7367 }
7368 *left = newLeft;
7369 *right = newRight;
7370
7371 return hasControl;
7372}
7373
Mathias Agopian65ab4712010-07-14 17:59:35 -07007374status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7375{
7376 const size_t SIZE = 256;
7377 char buffer[SIZE];
7378 String8 result;
7379
7380 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7381 result.append(buffer);
7382
7383 bool locked = tryLock(mLock);
7384 // failed to lock - AudioFlinger is probably deadlocked
7385 if (!locked) {
7386 result.append("\tCould not lock mutex:\n");
7387 }
7388
Eric Laurentcab11242010-07-15 12:50:15 -07007389 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7390 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007391 mEffects.size(),
7392 (uint32_t)mInBuffer,
7393 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007394 mActiveTrackCnt);
7395 result.append(buffer);
7396 write(fd, result.string(), result.size());
7397
7398 for (size_t i = 0; i < mEffects.size(); ++i) {
7399 sp<EffectModule> effect = mEffects[i];
7400 if (effect != 0) {
7401 effect->dump(fd, args);
7402 }
7403 }
7404
7405 if (locked) {
7406 mLock.unlock();
7407 }
7408
7409 return NO_ERROR;
7410}
7411
Eric Laurent59255e42011-07-27 19:49:51 -07007412// must be called with ThreadBase::mLock held
7413void AudioFlinger::EffectChain::setEffectSuspended_l(
7414 const effect_uuid_t *type, bool suspend)
7415{
7416 sp<SuspendedEffectDesc> desc;
7417 // use effect type UUID timelow as key as there is no real risk of identical
7418 // timeLow fields among effect type UUIDs.
7419 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7420 if (suspend) {
7421 if (index >= 0) {
7422 desc = mSuspendedEffects.valueAt(index);
7423 } else {
7424 desc = new SuspendedEffectDesc();
7425 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7426 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007427 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007428 }
7429 if (desc->mRefCount++ == 0) {
7430 sp<EffectModule> effect = getEffectIfEnabled(type);
7431 if (effect != 0) {
7432 desc->mEffect = effect;
7433 effect->setSuspended(true);
7434 effect->setEnabled(false);
7435 }
7436 }
7437 } else {
7438 if (index < 0) {
7439 return;
7440 }
7441 desc = mSuspendedEffects.valueAt(index);
7442 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007443 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007444 desc->mRefCount = 1;
7445 }
7446 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007447 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007448 if (desc->mEffect != 0) {
7449 sp<EffectModule> effect = desc->mEffect.promote();
7450 if (effect != 0) {
7451 effect->setSuspended(false);
7452 sp<EffectHandle> handle = effect->controlHandle();
7453 if (handle != 0) {
7454 effect->setEnabled(handle->enabled());
7455 }
7456 }
7457 desc->mEffect.clear();
7458 }
7459 mSuspendedEffects.removeItemsAt(index);
7460 }
7461 }
7462}
7463
7464// must be called with ThreadBase::mLock held
7465void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7466{
7467 sp<SuspendedEffectDesc> desc;
7468
7469 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7470 if (suspend) {
7471 if (index >= 0) {
7472 desc = mSuspendedEffects.valueAt(index);
7473 } else {
7474 desc = new SuspendedEffectDesc();
7475 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007476 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007477 }
7478 if (desc->mRefCount++ == 0) {
Glenn Kastend0539712012-01-30 12:56:03 -08007479 Vector< sp<EffectModule> > effects;
7480 getSuspendEligibleEffects(effects);
Eric Laurent59255e42011-07-27 19:49:51 -07007481 for (size_t i = 0; i < effects.size(); i++) {
7482 setEffectSuspended_l(&effects[i]->desc().type, true);
7483 }
7484 }
7485 } else {
7486 if (index < 0) {
7487 return;
7488 }
7489 desc = mSuspendedEffects.valueAt(index);
7490 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007491 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007492 desc->mRefCount = 1;
7493 }
7494 if (--desc->mRefCount == 0) {
7495 Vector<const effect_uuid_t *> types;
7496 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7497 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7498 continue;
7499 }
7500 types.add(&mSuspendedEffects.valueAt(i)->mType);
7501 }
7502 for (size_t i = 0; i < types.size(); i++) {
7503 setEffectSuspended_l(types[i], false);
7504 }
Steve Block3856b092011-10-20 11:56:00 +01007505 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007506 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7507 }
7508 }
7509}
7510
Eric Laurent6bffdb82011-09-23 08:40:41 -07007511
7512// The volume effect is used for automated tests only
7513#ifndef OPENSL_ES_H_
7514static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7515 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7516const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7517#endif //OPENSL_ES_H_
7518
Eric Laurentdb7c0792011-08-10 10:37:50 -07007519bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7520{
7521 // auxiliary effects and visualizer are never suspended on output mix
7522 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7523 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007524 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7525 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007526 return false;
7527 }
7528 return true;
7529}
7530
Glenn Kastend0539712012-01-30 12:56:03 -08007531void AudioFlinger::EffectChain::getSuspendEligibleEffects(Vector< sp<AudioFlinger::EffectModule> > &effects)
Eric Laurent59255e42011-07-27 19:49:51 -07007532{
Glenn Kastend0539712012-01-30 12:56:03 -08007533 effects.clear();
Eric Laurent59255e42011-07-27 19:49:51 -07007534 for (size_t i = 0; i < mEffects.size(); i++) {
Glenn Kastend0539712012-01-30 12:56:03 -08007535 if (isEffectEligibleForSuspend(mEffects[i]->desc())) {
7536 effects.add(mEffects[i]);
Eric Laurent59255e42011-07-27 19:49:51 -07007537 }
Eric Laurent59255e42011-07-27 19:49:51 -07007538 }
Eric Laurent59255e42011-07-27 19:49:51 -07007539}
7540
7541sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7542 const effect_uuid_t *type)
7543{
Glenn Kasten090f0192012-01-30 13:00:02 -08007544 sp<EffectModule> effect = getEffectFromType_l(type);
7545 return effect != 0 && effect->isEnabled() ? effect : 0;
Eric Laurent59255e42011-07-27 19:49:51 -07007546}
7547
7548void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7549 bool enabled)
7550{
7551 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7552 if (enabled) {
7553 if (index < 0) {
7554 // if the effect is not suspend check if all effects are suspended
7555 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7556 if (index < 0) {
7557 return;
7558 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007559 if (!isEffectEligibleForSuspend(effect->desc())) {
7560 return;
7561 }
Eric Laurent59255e42011-07-27 19:49:51 -07007562 setEffectSuspended_l(&effect->desc().type, enabled);
7563 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007564 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007565 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007566 return;
7567 }
Eric Laurent59255e42011-07-27 19:49:51 -07007568 }
Steve Block3856b092011-10-20 11:56:00 +01007569 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007570 effect->desc().type.timeLow);
7571 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7572 // if effect is requested to suspended but was not yet enabled, supend it now.
7573 if (desc->mEffect == 0) {
7574 desc->mEffect = effect;
7575 effect->setEnabled(false);
7576 effect->setSuspended(true);
7577 }
7578 } else {
7579 if (index < 0) {
7580 return;
7581 }
Steve Block3856b092011-10-20 11:56:00 +01007582 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007583 effect->desc().type.timeLow);
7584 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7585 desc->mEffect.clear();
7586 effect->setSuspended(false);
7587 }
7588}
7589
Mathias Agopian65ab4712010-07-14 17:59:35 -07007590#undef LOG_TAG
7591#define LOG_TAG "AudioFlinger"
7592
7593// ----------------------------------------------------------------------------
7594
7595status_t AudioFlinger::onTransact(
7596 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7597{
7598 return BnAudioFlinger::onTransact(code, data, reply, flags);
7599}
7600
Mathias Agopian65ab4712010-07-14 17:59:35 -07007601}; // namespace android