blob: cf925b03928931c552c11f544e4a51603014bae4 [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
40#include <media/AudioTrack.h>
41#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080042#include <media/IMediaPlayerService.h>
Glenn Kasten25b248e2012-01-03 15:28:29 -080043#include <media/IMediaDeathNotifier.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044
45#include <private/media/AudioTrackShared.h>
46#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070047
Dima Zavin64760242011-05-11 14:15:23 -070048#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070049#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050
51#include "AudioMixer.h"
52#include "AudioFlinger.h"
53
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070055#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070056#include <audio_effects/effect_ns.h>
57#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070058
Glenn Kasten3b21c502011-12-15 09:52:39 -080059#include <audio_utils/primitives.h>
60
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070062#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070063// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
64
Mathias Agopian65ab4712010-07-14 17:59:35 -070065// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070066
Eric Laurentde070132010-07-13 04:45:46 -070067
Mathias Agopian65ab4712010-07-14 17:59:35 -070068namespace android {
69
Glenn Kastenec1d6b52011-12-12 09:04:45 -080070static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
71static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070072
73//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
74static const float MAX_GAIN = 4096.0f;
75static const float MAX_GAIN_INT = 0x1000;
76
77// retry counts for buffer fill timeout
78// 50 * ~20msecs = 1 second
79static const int8_t kMaxTrackRetries = 50;
80static const int8_t kMaxTrackStartupRetries = 50;
81// allow less retry attempts on direct output thread.
82// direct outputs can be a scarce resource in audio hardware and should
83// be released as quickly as possible.
84static const int8_t kMaxTrackRetriesDirect = 2;
85
86static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080087static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Glenn Kasten7dede872011-12-13 11:04:14 -080089// don't warn about blocked writes or record buffer overflows more often than this
90static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070091
Eric Laurent7c7f10b2011-06-17 21:29:58 -070092// RecordThread loop sleep time upon application overrun or audio HAL read error
93static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
Glenn Kasten7dede872011-12-13 11:04:14 -080095// maximum time to wait for setParameters to complete
96static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070097
Eric Laurent7cafbb32011-11-22 18:50:29 -080098// minimum sleep time for the mixer thread loop when tracks are active but in underrun
99static const uint32_t kMinThreadSleepTimeUs = 5000;
100// maximum divider applied to the active sleep time in the mixer thread loop
101static const uint32_t kMaxThreadSleepTimeShift = 2;
102
103
Mathias Agopian65ab4712010-07-14 17:59:35 -0700104// ----------------------------------------------------------------------------
105
106static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
108 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
Steve Block29357bc2012-01-06 19:20:56 +0000109 if (!ok) ALOGE("Request requires android.permission.RECORD_AUDIO");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111}
112
113static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
115 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
Steve Block29357bc2012-01-06 19:20:56 +0000116 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118}
119
Gloria Wang9ee159b2011-02-24 14:51:45 -0800120// To collect the amplifier usage
121static void addBatteryData(uint32_t params) {
Glenn Kasten25b248e2012-01-03 15:28:29 -0800122 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
123 if (service == NULL) {
124 // it already logged
Gloria Wang9ee159b2011-02-24 14:51:45 -0800125 return;
126 }
127
128 service->addBatteryData(params);
129}
130
Dima Zavin799a70e2011-04-18 16:57:27 -0700131static int load_audio_interface(const char *if_name, const hw_module_t **mod,
132 audio_hw_device_t **dev)
133{
134 int rc;
135
136 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
137 if (rc)
138 goto out;
139
140 rc = audio_hw_device_open(*mod, dev);
Steve Block29357bc2012-01-06 19:20:56 +0000141 ALOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
Dima Zavin799a70e2011-04-18 16:57:27 -0700142 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
143 if (rc)
144 goto out;
145
146 return 0;
147
148out:
149 *mod = NULL;
150 *dev = NULL;
151 return rc;
152}
153
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800154static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700155 "primary",
156 "a2dp",
157 "usb",
158};
159#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
160
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161// ----------------------------------------------------------------------------
162
163AudioFlinger::AudioFlinger()
164 : BnAudioFlinger(),
Glenn Kastene0feee32011-12-13 11:53:26 -0800165 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700166 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin799a70e2011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700173
Eric Laurent93575202011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin799a70e2011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177 mHardwareStatus = AUDIO_HW_IDLE;
178
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 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Dima Zavin799a70e2011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261
262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
Glenn Kastena4454b42012-01-04 11:02:33 -0800297 hardware_call_state hardwareStatus = mHardwareStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700298
299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328 }
329 return locked;
330}
331
332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
334 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
335 dumpPermissionDenial(fd, args);
336 } else {
337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
352 }
353
354 dumpClients(fd, args);
355 dumpInternals(fd, args);
356
357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
359 mPlaybackThreads.valueAt(i)->dump(fd, args);
360 }
361
362 // dump record threads
363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
364 mRecordThreads.valueAt(i)->dump(fd, args);
365 }
366
Dima Zavin799a70e2011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 if (locked) mLock.unlock();
373 }
374 return NO_ERROR;
375}
376
377
378// IAudioFlinger interface
379
380
381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
Glenn Kastenfff6d712012-01-12 16:38:12 -0800383 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700384 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700385 uint32_t format,
386 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
390 int output,
391 int *sessionId,
392 status_t *status)
393{
394 sp<PlaybackThread::Track> track;
395 sp<TrackHandle> trackHandle;
396 sp<Client> client;
397 wp<Client> wclient;
398 status_t lStatus;
399 int lSessionId;
400
Glenn Kasten263709e2012-01-06 08:40:01 -0800401 // client AudioTrack::set already implements AUDIO_STREAM_DEFAULT => AUDIO_STREAM_MUSIC,
402 // but if someone uses binder directly they could bypass that and cause us to crash
403 if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000404 ALOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700405 lStatus = BAD_VALUE;
406 goto Exit;
407 }
408
409 {
410 Mutex::Autolock _l(mLock);
411 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700412 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700413 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +0000414 ALOGE("unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700415 lStatus = BAD_VALUE;
416 goto Exit;
417 }
418
419 wclient = mClients.valueFor(pid);
420
421 if (wclient != NULL) {
422 client = wclient.promote();
423 } else {
424 client = new Client(this, pid);
425 mClients.add(pid, client);
426 }
427
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
483uint32_t AudioFlinger::sampleRate(int output) const
484{
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
494int AudioFlinger::channelCount(int output) const
495{
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
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700505uint32_t AudioFlinger::format(int 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);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700511 return 0;
512 }
513 return thread->format();
514}
515
516size_t AudioFlinger::frameCount(int output) const
517{
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
527uint32_t AudioFlinger::latency(int output) const
528{
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
568status_t AudioFlinger::setMode(int mode)
569{
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 Kastenfff6d712012-01-12 16:38:12 -0800661status_t AudioFlinger::setStreamVolume(audio_stream_type_t stream, float value, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662{
663 // check calling permissions
664 if (!settingsAllowed()) {
665 return PERMISSION_DENIED;
666 }
667
Glenn Kasten263709e2012-01-06 08:40:01 -0800668 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Steve Block29357bc2012-01-06 19:20:56 +0000669 ALOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 return BAD_VALUE;
671 }
672
673 AutoMutex lock(mLock);
674 PlaybackThread *thread = NULL;
675 if (output) {
676 thread = checkPlaybackThread_l(output);
677 if (thread == NULL) {
678 return BAD_VALUE;
679 }
680 }
681
682 mStreamTypes[stream].volume = value;
683
684 if (thread == NULL) {
685 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
686 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
687 }
688 } else {
689 thread->setStreamVolume(stream, value);
690 }
691
692 return NO_ERROR;
693}
694
Glenn Kastenfff6d712012-01-12 16:38:12 -0800695status_t AudioFlinger::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696{
697 // check calling permissions
698 if (!settingsAllowed()) {
699 return PERMISSION_DENIED;
700 }
701
Glenn Kasten263709e2012-01-06 08:40:01 -0800702 if (uint32_t(stream) >= AUDIO_STREAM_CNT ||
Dima Zavinfce7a472011-04-19 22:30:36 -0700703 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Steve Block29357bc2012-01-06 19:20:56 +0000704 ALOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 return BAD_VALUE;
706 }
707
Eric Laurent93575202011-01-18 18:39:02 -0800708 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 mStreamTypes[stream].mute = muted;
710 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
711 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
712
713 return NO_ERROR;
714}
715
Glenn Kastenfff6d712012-01-12 16:38:12 -0800716float AudioFlinger::streamVolume(audio_stream_type_t stream, int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700717{
Glenn Kasten263709e2012-01-06 08:40:01 -0800718 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 return 0.0f;
720 }
721
722 AutoMutex lock(mLock);
723 float volume;
724 if (output) {
725 PlaybackThread *thread = checkPlaybackThread_l(output);
726 if (thread == NULL) {
727 return 0.0f;
728 }
729 volume = thread->streamVolume(stream);
730 } else {
731 volume = mStreamTypes[stream].volume;
732 }
733
734 return volume;
735}
736
Glenn Kastenfff6d712012-01-12 16:38:12 -0800737bool AudioFlinger::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738{
Glenn Kasten263709e2012-01-06 08:40:01 -0800739 if (uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 return true;
741 }
742
743 return mStreamTypes[stream].mute;
744}
745
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
747{
748 status_t result;
749
Steve Block3856b092011-10-20 11:56:00 +0100750 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700751 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
752 // check calling permissions
753 if (!settingsAllowed()) {
754 return PERMISSION_DENIED;
755 }
756
Mathias Agopian65ab4712010-07-14 17:59:35 -0700757 // ioHandle == 0 means the parameters are global to the audio hardware interface
758 if (ioHandle == 0) {
759 AutoMutex lock(mHardwareLock);
760 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700761 status_t final_result = NO_ERROR;
762 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
763 audio_hw_device_t *dev = mAudioHwDevs[i];
764 result = dev->set_parameters(dev, keyValuePairs.string());
765 final_result = result ?: final_result;
766 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700767 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700768 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
769 AudioParameter param = AudioParameter(keyValuePairs);
770 String8 value;
771 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
772 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700773 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
774 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700775 for (size_t i = 0; i < mRecordThreads.size(); i++) {
776 sp<RecordThread> thread = mRecordThreads.valueAt(i);
777 RecordThread::RecordTrack *track = thread->track();
778 if (track != NULL) {
779 audio_devices_t device = (audio_devices_t)(
780 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700781 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700782 thread->setEffectSuspended(FX_IID_AEC,
783 suspend,
784 track->sessionId());
785 thread->setEffectSuspended(FX_IID_NS,
786 suspend,
787 track->sessionId());
788 }
789 }
Eric Laurentbee53372011-08-29 12:42:48 -0700790 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700791 }
792 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700793 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700794 }
795
796 // hold a strong ref on thread in case closeOutput() or closeInput() is called
797 // and the thread is exited once the lock is released
798 sp<ThreadBase> thread;
799 {
800 Mutex::Autolock _l(mLock);
801 thread = checkPlaybackThread_l(ioHandle);
802 if (thread == NULL) {
803 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700804 } else if (thread.get() == primaryPlaybackThread_l()) {
805 // indicate output device change to all input threads for pre processing
806 AudioParameter param = AudioParameter(keyValuePairs);
807 int value;
808 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
809 for (size_t i = 0; i < mRecordThreads.size(); i++) {
810 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
811 }
812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 }
814 }
815 if (thread != NULL) {
816 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817 return result;
818 }
819 return BAD_VALUE;
820}
821
822String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
823{
Steve Block3856b092011-10-20 11:56:00 +0100824// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700825// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
826
827 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700828 String8 out_s8;
829
Dima Zavin799a70e2011-04-18 16:57:27 -0700830 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
831 audio_hw_device_t *dev = mAudioHwDevs[i];
832 char *s = dev->get_parameters(dev, keys.string());
833 out_s8 += String8(s);
834 free(s);
835 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700836 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837 }
838
839 Mutex::Autolock _l(mLock);
840
841 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
842 if (playbackThread != NULL) {
843 return playbackThread->getParameters(keys);
844 }
845 RecordThread *recordThread = checkRecordThread_l(ioHandle);
846 if (recordThread != NULL) {
847 return recordThread->getParameters(keys);
848 }
849 return String8("");
850}
851
852size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
853{
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
862unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
863{
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
897status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
898{
899 status_t status;
900
901 Mutex::Autolock _l(mLock);
902
903 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
904 if (playbackThread != NULL) {
905 return playbackThread->getRenderPosition(halFrames, dspFrames);
906 }
907
908 return BAD_VALUE;
909}
910
911void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
912{
913
914 Mutex::Autolock _l(mLock);
915
916 int pid = IPCThreadState::self()->getCallingPid();
917 if (mNotificationClients.indexOfKey(pid) < 0) {
918 sp<NotificationClient> notificationClient = new NotificationClient(this,
919 client,
920 pid);
Steve Block3856b092011-10-20 11:56:00 +0100921 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700922
923 mNotificationClients.add(pid, notificationClient);
924
925 sp<IBinder> binder = client->asBinder();
926 binder->linkToDeath(notificationClient);
927
928 // the config change is always sent from playback or record threads to avoid deadlock
929 // with AudioSystem::gLock
930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
931 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
932 }
933
934 for (size_t i = 0; i < mRecordThreads.size(); i++) {
935 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
936 }
937 }
938}
939
940void AudioFlinger::removeNotificationClient(pid_t pid)
941{
942 Mutex::Autolock _l(mLock);
943
944 int index = mNotificationClients.indexOfKey(pid);
945 if (index >= 0) {
946 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700948 mNotificationClients.removeItem(pid);
949 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950
Steve Block3856b092011-10-20 11:56:00 +0100951 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700952 int num = mAudioSessionRefs.size();
953 bool removed = false;
954 for (int i = 0; i< num; i++) {
955 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100956 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700957 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100958 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700959 mAudioSessionRefs.removeAt(i);
960 delete ref;
961 removed = true;
962 i--;
963 num--;
964 }
965 }
966 if (removed) {
967 purgeStaleEffects_l();
968 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700969}
970
971// audioConfigChanged_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
973{
974 size_t size = mNotificationClients.size();
975 for (size_t i = 0; i < size; i++) {
976 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
977 }
978}
979
980// removeClient_l() must be called with AudioFlinger::mLock held
981void AudioFlinger::removeClient_l(pid_t pid)
982{
Steve Block3856b092011-10-20 11:56:00 +0100983 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984 mClients.removeItem(pid);
985}
986
987
988// ----------------------------------------------------------------------------
989
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700990AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991 : Thread(false),
992 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700993 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
994 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700995{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700996 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700997}
998
999AudioFlinger::ThreadBase::~ThreadBase()
1000{
1001 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001002 // do not lock the mutex in destructor
1003 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001004 if (mPowerManager != 0) {
1005 sp<IBinder> binder = mPowerManager->asBinder();
1006 binder->unlinkToDeath(mDeathRecipient);
1007 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001008}
1009
1010void AudioFlinger::ThreadBase::exit()
1011{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001012 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 // destroyed in the middle of requestExitAndWait()
1014 sp <ThreadBase> strongMe = this;
1015
Steve Block3856b092011-10-20 11:56:00 +01001016 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08001018 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 mExiting = true;
1020 requestExit();
1021 mWaitWorkCV.signal();
1022 }
1023 requestExitAndWait();
1024}
1025
1026uint32_t AudioFlinger::ThreadBase::sampleRate() const
1027{
1028 return mSampleRate;
1029}
1030
1031int AudioFlinger::ThreadBase::channelCount() const
1032{
1033 return (int)mChannelCount;
1034}
1035
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001036uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001037{
1038 return mFormat;
1039}
1040
1041size_t AudioFlinger::ThreadBase::frameCount() const
1042{
1043 return mFrameCount;
1044}
1045
1046status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1047{
1048 status_t status;
1049
Steve Block3856b092011-10-20 11:56:00 +01001050 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 Mutex::Autolock _l(mLock);
1052
1053 mNewParameters.add(keyValuePairs);
1054 mWaitWorkCV.signal();
1055 // wait condition with timeout in case the thread loop has exited
1056 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001057 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058 status = mParamStatus;
1059 mWaitWorkCV.signal();
1060 } else {
1061 status = TIMED_OUT;
1062 }
1063 return status;
1064}
1065
1066void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1067{
1068 Mutex::Autolock _l(mLock);
1069 sendConfigEvent_l(event, param);
1070}
1071
1072// sendConfigEvent_l() must be called with ThreadBase::mLock held
1073void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1074{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001075 ConfigEvent configEvent;
1076 configEvent.mEvent = event;
1077 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001078 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 mWaitWorkCV.signal();
1081}
1082
1083void AudioFlinger::ThreadBase::processConfigEvents()
1084{
1085 mLock.lock();
1086 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001087 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001088 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001089 mConfigEvents.removeAt(0);
1090 // release mLock before locking AudioFlinger mLock: lock order is always
1091 // AudioFlinger then ThreadBase to avoid cross deadlock
1092 mLock.unlock();
1093 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001094 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001095 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001096 mLock.lock();
1097 }
1098 mLock.unlock();
1099}
1100
1101status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1102{
1103 const size_t SIZE = 256;
1104 char buffer[SIZE];
1105 String8 result;
1106
1107 bool locked = tryLock(mLock);
1108 if (!locked) {
1109 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1110 write(fd, buffer, strlen(buffer));
1111 }
1112
1113 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1116 result.append(buffer);
1117 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1118 result.append(buffer);
1119 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1120 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001121 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1122 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001123 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1124 result.append(buffer);
Glenn Kastenb9980652012-01-11 09:48:27 -08001125 snprintf(buffer, SIZE, "Frame size: %u\n", mFrameSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001126 result.append(buffer);
1127
1128 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1129 result.append(buffer);
1130 result.append(" Index Command");
1131 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1132 snprintf(buffer, SIZE, "\n %02d ", i);
1133 result.append(buffer);
1134 result.append(mNewParameters[i]);
1135 }
1136
1137 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1138 result.append(buffer);
1139 snprintf(buffer, SIZE, " Index event param\n");
1140 result.append(buffer);
1141 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001142 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001143 result.append(buffer);
1144 }
1145 result.append("\n");
1146
1147 write(fd, result.string(), result.size());
1148
1149 if (locked) {
1150 mLock.unlock();
1151 }
1152 return NO_ERROR;
1153}
1154
Eric Laurent1d2bff02011-07-24 17:49:51 -07001155status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1156{
1157 const size_t SIZE = 256;
1158 char buffer[SIZE];
1159 String8 result;
1160
1161 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1162 write(fd, buffer, strlen(buffer));
1163
1164 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1165 sp<EffectChain> chain = mEffectChains[i];
1166 if (chain != 0) {
1167 chain->dump(fd, args);
1168 }
1169 }
1170 return NO_ERROR;
1171}
1172
Eric Laurentfeb0db62011-07-22 09:04:31 -07001173void AudioFlinger::ThreadBase::acquireWakeLock()
1174{
1175 Mutex::Autolock _l(mLock);
1176 acquireWakeLock_l();
1177}
1178
1179void AudioFlinger::ThreadBase::acquireWakeLock_l()
1180{
1181 if (mPowerManager == 0) {
1182 // use checkService() to avoid blocking if power service is not up yet
1183 sp<IBinder> binder =
1184 defaultServiceManager()->checkService(String16("power"));
1185 if (binder == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001186 ALOGW("Thread %s cannot connect to the power manager service", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001187 } else {
1188 mPowerManager = interface_cast<IPowerManager>(binder);
1189 binder->linkToDeath(mDeathRecipient);
1190 }
1191 }
1192 if (mPowerManager != 0) {
1193 sp<IBinder> binder = new BBinder();
1194 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1195 binder,
1196 String16(mName));
1197 if (status == NO_ERROR) {
1198 mWakeLockToken = binder;
1199 }
Steve Block3856b092011-10-20 11:56:00 +01001200 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001201 }
1202}
1203
1204void AudioFlinger::ThreadBase::releaseWakeLock()
1205{
1206 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001207 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001208}
1209
1210void AudioFlinger::ThreadBase::releaseWakeLock_l()
1211{
1212 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001213 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001214 if (mPowerManager != 0) {
1215 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1216 }
1217 mWakeLockToken.clear();
1218 }
1219}
1220
1221void AudioFlinger::ThreadBase::clearPowerManager()
1222{
1223 Mutex::Autolock _l(mLock);
1224 releaseWakeLock_l();
1225 mPowerManager.clear();
1226}
1227
1228void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1229{
1230 sp<ThreadBase> thread = mThread.promote();
1231 if (thread != 0) {
1232 thread->clearPowerManager();
1233 }
Steve Block5ff1dd52012-01-05 23:22:43 +00001234 ALOGW("power manager service died !!!");
Eric Laurentfeb0db62011-07-22 09:04:31 -07001235}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001236
Eric Laurent59255e42011-07-27 19:49:51 -07001237void AudioFlinger::ThreadBase::setEffectSuspended(
1238 const effect_uuid_t *type, bool suspend, int sessionId)
1239{
1240 Mutex::Autolock _l(mLock);
1241 setEffectSuspended_l(type, suspend, sessionId);
1242}
1243
1244void AudioFlinger::ThreadBase::setEffectSuspended_l(
1245 const effect_uuid_t *type, bool suspend, int sessionId)
1246{
1247 sp<EffectChain> chain;
1248 chain = getEffectChain_l(sessionId);
1249 if (chain != 0) {
1250 if (type != NULL) {
1251 chain->setEffectSuspended_l(type, suspend);
1252 } else {
1253 chain->setEffectSuspendedAll_l(suspend);
1254 }
1255 }
1256
1257 updateSuspendedSessions_l(type, suspend, sessionId);
1258}
1259
1260void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1261{
1262 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1263 if (index < 0) {
1264 return;
1265 }
1266
1267 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1268 mSuspendedSessions.editValueAt(index);
1269
1270 for (size_t i = 0; i < sessionEffects.size(); i++) {
1271 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1272 for (int j = 0; j < desc->mRefCount; j++) {
1273 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1274 chain->setEffectSuspendedAll_l(true);
1275 } else {
Steve Block3856b092011-10-20 11:56:00 +01001276 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001277 desc->mType.timeLow);
1278 chain->setEffectSuspended_l(&desc->mType, true);
1279 }
1280 }
1281 }
1282}
1283
Eric Laurent59255e42011-07-27 19:49:51 -07001284void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1285 bool suspend,
1286 int sessionId)
1287{
1288 int index = mSuspendedSessions.indexOfKey(sessionId);
1289
1290 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1291
1292 if (suspend) {
1293 if (index >= 0) {
1294 sessionEffects = mSuspendedSessions.editValueAt(index);
1295 } else {
1296 mSuspendedSessions.add(sessionId, sessionEffects);
1297 }
1298 } else {
1299 if (index < 0) {
1300 return;
1301 }
1302 sessionEffects = mSuspendedSessions.editValueAt(index);
1303 }
1304
1305
1306 int key = EffectChain::kKeyForSuspendAll;
1307 if (type != NULL) {
1308 key = type->timeLow;
1309 }
1310 index = sessionEffects.indexOfKey(key);
1311
1312 sp <SuspendedSessionDesc> desc;
1313 if (suspend) {
1314 if (index >= 0) {
1315 desc = sessionEffects.valueAt(index);
1316 } else {
1317 desc = new SuspendedSessionDesc();
1318 if (type != NULL) {
1319 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1320 }
1321 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001322 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001323 }
1324 desc->mRefCount++;
1325 } else {
1326 if (index < 0) {
1327 return;
1328 }
1329 desc = sessionEffects.valueAt(index);
1330 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001331 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001332 sessionEffects.removeItemsAt(index);
1333 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001334 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001335 sessionId);
1336 mSuspendedSessions.removeItem(sessionId);
1337 }
1338 }
1339 }
1340 if (!sessionEffects.isEmpty()) {
1341 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1342 }
1343}
1344
1345void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1346 bool enabled,
1347 int sessionId)
1348{
1349 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001350 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1351}
Eric Laurent59255e42011-07-27 19:49:51 -07001352
Eric Laurenta85a74a2011-10-19 11:44:54 -07001353void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1354 bool enabled,
1355 int sessionId)
1356{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001357 if (mType != RECORD) {
1358 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1359 // another session. This gives the priority to well behaved effect control panels
1360 // and applications not using global effects.
1361 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1362 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1363 }
1364 }
Eric Laurent59255e42011-07-27 19:49:51 -07001365
1366 sp<EffectChain> chain = getEffectChain_l(sessionId);
1367 if (chain != 0) {
1368 chain->checkSuspendOnEffectEnabled(effect, enabled);
1369 }
1370}
1371
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372// ----------------------------------------------------------------------------
1373
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001374AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1375 AudioStreamOut* output,
1376 int id,
1377 uint32_t device)
1378 : ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001379 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001380 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001382 snprintf(mName, kNameLength, "AudioOut_%d", id);
1383
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 readOutputParameters();
1385
Glenn Kasten98067102011-12-13 11:47:54 -08001386 // Assumes constructor is called by AudioFlinger with it's mLock held,
1387 // but it would be safer to explicitly pass these as parameters
1388 mMasterVolume = mAudioFlinger->masterVolume_l();
1389 mMasterMute = mAudioFlinger->masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390
Glenn Kasten263709e2012-01-06 08:40:01 -08001391 // mStreamTypes[AUDIO_STREAM_CNT] is initialized by stream_type_t default constructor
Glenn Kastenfff6d712012-01-12 16:38:12 -08001392 // There is no AUDIO_STREAM_MIN, and ++ operator does not compile
1393 for (audio_stream_type_t stream = (audio_stream_type_t) 0; stream < AUDIO_STREAM_CNT;
1394 stream = (audio_stream_type_t) (stream + 1)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001395 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1396 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Glenn Kasten263709e2012-01-06 08:40:01 -08001397 // initialized by stream_type_t default constructor
1398 // mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001399 }
1400}
1401
1402AudioFlinger::PlaybackThread::~PlaybackThread()
1403{
1404 delete [] mMixBuffer;
1405}
1406
1407status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1408{
1409 dumpInternals(fd, args);
1410 dumpTracks(fd, args);
1411 dumpEffectChains(fd, args);
1412 return NO_ERROR;
1413}
1414
1415status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1416{
1417 const size_t SIZE = 256;
1418 char buffer[SIZE];
1419 String8 result;
1420
1421 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1422 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001423 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 -07001424 for (size_t i = 0; i < mTracks.size(); ++i) {
1425 sp<Track> track = mTracks[i];
1426 if (track != 0) {
1427 track->dump(buffer, SIZE);
1428 result.append(buffer);
1429 }
1430 }
1431
1432 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1433 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001434 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 -07001435 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1436 wp<Track> wTrack = mActiveTracks[i];
1437 if (wTrack != 0) {
1438 sp<Track> track = wTrack.promote();
1439 if (track != 0) {
1440 track->dump(buffer, SIZE);
1441 result.append(buffer);
1442 }
1443 }
1444 }
1445 write(fd, result.string(), result.size());
1446 return NO_ERROR;
1447}
1448
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1450{
1451 const size_t SIZE = 256;
1452 char buffer[SIZE];
1453 String8 result;
1454
1455 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1456 result.append(buffer);
1457 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1458 result.append(buffer);
1459 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1460 result.append(buffer);
1461 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1462 result.append(buffer);
1463 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1464 result.append(buffer);
1465 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1466 result.append(buffer);
1467 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1468 result.append(buffer);
1469 write(fd, result.string(), result.size());
1470
1471 dumpBase(fd, args);
1472
1473 return NO_ERROR;
1474}
1475
1476// Thread virtuals
1477status_t AudioFlinger::PlaybackThread::readyToRun()
1478{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001479 status_t status = initCheck();
1480 if (status == NO_ERROR) {
Steve Blockdf64d152012-01-04 20:05:49 +00001481 ALOGI("AudioFlinger's thread %p ready to run", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001482 } else {
Steve Block29357bc2012-01-06 19:20:56 +00001483 ALOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001485 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486}
1487
1488void AudioFlinger::PlaybackThread::onFirstRef()
1489{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001490 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491}
1492
1493// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1494sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1495 const sp<AudioFlinger::Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08001496 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001498 uint32_t format,
1499 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001500 int frameCount,
1501 const sp<IMemory>& sharedBuffer,
1502 int sessionId,
1503 status_t *status)
1504{
1505 sp<Track> track;
1506 status_t lStatus;
1507
1508 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001509 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1510 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Steve Block29357bc2012-01-06 19:20:56 +00001511 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001512 "for output %p with format %d",
1513 sampleRate, format, channelMask, mOutput, mFormat);
1514 lStatus = BAD_VALUE;
1515 goto Exit;
1516 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 }
1518 } else {
1519 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1520 if (sampleRate > mSampleRate*2) {
Steve Block29357bc2012-01-06 19:20:56 +00001521 ALOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001522 lStatus = BAD_VALUE;
1523 goto Exit;
1524 }
1525 }
1526
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001527 lStatus = initCheck();
1528 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00001529 ALOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530 goto Exit;
1531 }
1532
1533 { // scope for mLock
1534 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001535
1536 // all tracks in same audio session must share the same routing strategy otherwise
1537 // conflicts will happen when tracks are moved from one output to another by audio policy
1538 // manager
1539 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001540 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001541 for (size_t i = 0; i < mTracks.size(); ++i) {
1542 sp<Track> t = mTracks[i];
1543 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001544 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1545 if (sessionId == t->sessionId() && strategy != actual) {
Steve Block29357bc2012-01-06 19:20:56 +00001546 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
Glenn Kastend8796012011-10-28 10:31:42 -07001547 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001548 lStatus = BAD_VALUE;
1549 goto Exit;
1550 }
1551 }
1552 }
1553
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001555 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 if (track->getCblk() == NULL || track->name() < 0) {
1557 lStatus = NO_MEMORY;
1558 goto Exit;
1559 }
1560 mTracks.add(track);
1561
1562 sp<EffectChain> chain = getEffectChain_l(sessionId);
1563 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001564 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001566 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001567 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001569
1570 // invalidate track immediately if the stream type was moved to another thread since
1571 // createTrack() was called by the client process.
1572 if (!mStreamTypes[streamType].valid) {
Steve Block5ff1dd52012-01-05 23:22:43 +00001573 ALOGW("createTrack_l() on thread %p: invalidating track on stream %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07001574 this, streamType);
1575 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1576 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577 }
1578 lStatus = NO_ERROR;
1579
1580Exit:
1581 if(status) {
1582 *status = lStatus;
1583 }
1584 return track;
1585}
1586
1587uint32_t AudioFlinger::PlaybackThread::latency() const
1588{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001589 Mutex::Autolock _l(mLock);
1590 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001591 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001592 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 return 0;
1594 }
1595}
1596
1597status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1598{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001599 mMasterVolume = value;
1600 return NO_ERROR;
1601}
1602
1603status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1604{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001605 mMasterMute = muted;
1606 return NO_ERROR;
1607}
1608
1609float AudioFlinger::PlaybackThread::masterVolume() const
1610{
1611 return mMasterVolume;
1612}
1613
1614bool AudioFlinger::PlaybackThread::masterMute() const
1615{
1616 return mMasterMute;
1617}
1618
Glenn Kastenfff6d712012-01-12 16:38:12 -08001619status_t AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001620{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621 mStreamTypes[stream].volume = value;
1622 return NO_ERROR;
1623}
1624
Glenn Kastenfff6d712012-01-12 16:38:12 -08001625status_t AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 mStreamTypes[stream].mute = muted;
1628 return NO_ERROR;
1629}
1630
Glenn Kastenfff6d712012-01-12 16:38:12 -08001631float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632{
1633 return mStreamTypes[stream].volume;
1634}
1635
Glenn Kastenfff6d712012-01-12 16:38:12 -08001636bool AudioFlinger::PlaybackThread::streamMute(audio_stream_type_t stream) const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637{
1638 return mStreamTypes[stream].mute;
1639}
1640
Mathias Agopian65ab4712010-07-14 17:59:35 -07001641// addTrack_l() must be called with ThreadBase::mLock held
1642status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1643{
1644 status_t status = ALREADY_EXISTS;
1645
1646 // set retry count for buffer fill
1647 track->mRetryCount = kMaxTrackStartupRetries;
1648 if (mActiveTracks.indexOf(track) < 0) {
1649 // the track is newly added, make sure it fills up all its
1650 // buffers before playing. This is to ensure the client will
1651 // effectively get the latency it requested.
1652 track->mFillingUpStatus = Track::FS_FILLING;
1653 track->mResetDone = false;
1654 mActiveTracks.add(track);
1655 if (track->mainBuffer() != mMixBuffer) {
1656 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1657 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001658 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001659 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 }
1661 }
1662
1663 status = NO_ERROR;
1664 }
1665
Steve Block3856b092011-10-20 11:56:00 +01001666 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001667 mWaitWorkCV.broadcast();
1668
1669 return status;
1670}
1671
1672// destroyTrack_l() must be called with ThreadBase::mLock held
1673void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1674{
1675 track->mState = TrackBase::TERMINATED;
1676 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001677 removeTrack_l(track);
1678 }
1679}
1680
1681void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1682{
1683 mTracks.remove(track);
1684 deleteTrackName_l(track->name());
1685 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1686 if (chain != 0) {
1687 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688 }
1689}
1690
1691String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1692{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001693 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001694 char *s;
1695
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001696 Mutex::Autolock _l(mLock);
1697 if (initCheck() != NO_ERROR) {
1698 return out_s8;
1699 }
1700
Dima Zavin799a70e2011-04-18 16:57:27 -07001701 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001702 out_s8 = String8(s);
1703 free(s);
1704 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705}
1706
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001707// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1709 AudioSystem::OutputDescriptor desc;
1710 void *param2 = 0;
1711
Steve Block3856b092011-10-20 11:56:00 +01001712 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713
1714 switch (event) {
1715 case AudioSystem::OUTPUT_OPENED:
1716 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001717 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001718 desc.samplingRate = mSampleRate;
1719 desc.format = mFormat;
1720 desc.frameCount = mFrameCount;
1721 desc.latency = latency();
1722 param2 = &desc;
1723 break;
1724
1725 case AudioSystem::STREAM_CONFIG_CHANGED:
1726 param2 = &param;
1727 case AudioSystem::OUTPUT_CLOSED:
1728 default:
1729 break;
1730 }
1731 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1732}
1733
1734void AudioFlinger::PlaybackThread::readOutputParameters()
1735{
Dima Zavin799a70e2011-04-18 16:57:27 -07001736 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001737 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1738 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001739 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08001740 mFrameSize = audio_stream_frame_size(&mOutput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07001741 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
1743 // FIXME - Current mixer implementation only supports stereo output: Always
1744 // Allocate a stereo buffer even if HW output is mono.
1745 if (mMixBuffer != NULL) delete[] mMixBuffer;
1746 mMixBuffer = new int16_t[mFrameCount * 2];
1747 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1748
Eric Laurentde070132010-07-13 04:45:46 -07001749 // force reconfiguration of effect chains and engines to take new buffer size and audio
1750 // parameters into account
1751 // Note that mLock is not held when readOutputParameters() is called from the constructor
1752 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1753 // matter.
1754 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1755 Vector< sp<EffectChain> > effectChains = mEffectChains;
1756 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001757 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759}
1760
1761status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1762{
1763 if (halFrames == 0 || dspFrames == 0) {
1764 return BAD_VALUE;
1765 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001766 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001767 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 return INVALID_OPERATION;
1769 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001770 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771
Dima Zavin799a70e2011-04-18 16:57:27 -07001772 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773}
1774
Eric Laurent39e94f82010-07-28 01:32:47 -07001775uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776{
1777 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001778 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001780 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781 }
1782
1783 for (size_t i = 0; i < mTracks.size(); ++i) {
1784 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001785 if (sessionId == track->sessionId() &&
1786 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001787 result |= TRACK_SESSION;
1788 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001789 }
1790 }
1791
Eric Laurent39e94f82010-07-28 01:32:47 -07001792 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001793}
1794
Eric Laurentde070132010-07-13 04:45:46 -07001795uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1796{
Dima Zavinfce7a472011-04-19 22:30:36 -07001797 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001798 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001799 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1800 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001801 }
1802 for (size_t i = 0; i < mTracks.size(); i++) {
1803 sp<Track> track = mTracks[i];
1804 if (sessionId == track->sessionId() &&
1805 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001806 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001807 }
1808 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001809 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001810}
1811
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001813AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1814{
1815 Mutex::Autolock _l(mLock);
1816 return mOutput;
1817}
1818
1819AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1820{
1821 Mutex::Autolock _l(mLock);
1822 AudioStreamOut *output = mOutput;
1823 mOutput = NULL;
1824 return output;
1825}
1826
1827// this method must always be called either with ThreadBase mLock held or inside the thread loop
1828audio_stream_t* AudioFlinger::PlaybackThread::stream()
1829{
1830 if (mOutput == NULL) {
1831 return NULL;
1832 }
1833 return &mOutput->stream->common;
1834}
1835
Eric Laurent162b40b2011-12-05 09:47:19 -08001836uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1837{
1838 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1839 // decoding and transfer time. So sleeping for half of the latency would likely cause
1840 // underruns
1841 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1842 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1843 } else {
1844 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1845 }
1846}
1847
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848// ----------------------------------------------------------------------------
1849
Dima Zavin799a70e2011-04-18 16:57:27 -07001850AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001852 mAudioMixer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001854 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001855 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1856
1857 // FIXME - Current mixer implementation only supports stereo output
1858 if (mChannelCount == 1) {
Steve Block29357bc2012-01-06 19:20:56 +00001859 ALOGE("Invalid audio hardware channel count");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001860 }
1861}
1862
1863AudioFlinger::MixerThread::~MixerThread()
1864{
1865 delete mAudioMixer;
1866}
1867
1868bool AudioFlinger::MixerThread::threadLoop()
1869{
1870 Vector< sp<Track> > tracksToRemove;
1871 uint32_t mixerStatus = MIXER_IDLE;
1872 nsecs_t standbyTime = systemTime();
1873 size_t mixBufferSize = mFrameCount * mFrameSize;
1874 // FIXME: Relaxed timing because of a certain device that can't meet latency
1875 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001876 // increase threshold again due to low power audio mode. The way this warning threshold is
1877 // calculated and its usefulness should be reconsidered anyway.
1878 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 nsecs_t lastWarning = 0;
1880 bool longStandbyExit = false;
1881 uint32_t activeSleepTime = activeSleepTimeUs();
1882 uint32_t idleSleepTime = idleSleepTimeUs();
1883 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001884 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001886#ifdef DEBUG_CPU_USAGE
1887 ThreadCpuUsage cpu;
1888 const CentralTendencyStatistics& stats = cpu.statistics();
1889#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890
Eric Laurentfeb0db62011-07-22 09:04:31 -07001891 acquireWakeLock();
1892
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 while (!exitPending())
1894 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001895#ifdef DEBUG_CPU_USAGE
1896 cpu.sampleAndEnable();
1897 unsigned n = stats.n();
1898 // cpu.elapsed() is expensive, so don't call it every loop
1899 if ((n & 127) == 1) {
1900 long long elapsed = cpu.elapsed();
1901 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1902 double perLoop = elapsed / (double) n;
1903 double perLoop100 = perLoop * 0.01;
1904 double mean = stats.mean();
1905 double stddev = stats.stddev();
1906 double minimum = stats.minimum();
1907 double maximum = stats.maximum();
1908 cpu.resetStatistics();
Steve Blockdf64d152012-01-04 20:05:49 +00001909 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 -07001910 elapsed * .000000001, n, perLoop * .000001,
1911 mean * .001,
1912 stddev * .001,
1913 minimum * .001,
1914 maximum * .001,
1915 mean / perLoop100,
1916 stddev / perLoop100,
1917 minimum / perLoop100,
1918 maximum / perLoop100);
1919 }
1920 }
1921#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 processConfigEvents();
1923
1924 mixerStatus = MIXER_IDLE;
1925 { // scope for mLock
1926
1927 Mutex::Autolock _l(mLock);
1928
1929 if (checkForNewParameters_l()) {
1930 mixBufferSize = mFrameCount * mFrameSize;
1931 // FIXME: Relaxed timing because of a certain device that can't meet latency
1932 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001933 // increase threshold again due to low power audio mode. The way this warning
1934 // threshold is calculated and its usefulness should be reconsidered anyway.
1935 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 activeSleepTime = activeSleepTimeUs();
1937 idleSleepTime = idleSleepTimeUs();
1938 }
1939
1940 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1941
1942 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001943 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1944 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001945 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001946 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001947 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001948 mStandby = true;
1949 mBytesWritten = 0;
1950 }
1951
1952 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1953 // we're about to wait, flush the binder command buffer
1954 IPCThreadState::self()->flushCommands();
1955
1956 if (exitPending()) break;
1957
Eric Laurentfeb0db62011-07-22 09:04:31 -07001958 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001959 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001960 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001962 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001963 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964
1965 if (mMasterMute == false) {
1966 char value[PROPERTY_VALUE_MAX];
1967 property_get("ro.audio.silent", value, "0");
1968 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001969 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 setMasterMute(true);
1971 }
1972 }
1973
1974 standbyTime = systemTime() + kStandbyTimeInNsecs;
1975 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001976 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 continue;
1978 }
1979 }
1980
1981 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1982
1983 // prevent any changes in effect chain list and in each effect chain
1984 // during mixing and effect process as the audio buffers could be deleted
1985 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001986 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988
Glenn Kastenf6b16782011-12-15 09:51:17 -08001989 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 // mix buffers...
1991 mAudioMixer->process();
1992 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001993 // increase sleep time progressively when application underrun condition clears
1994 if (sleepTimeShift > 0) {
1995 sleepTimeShift--;
1996 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 standbyTime = systemTime() + kStandbyTimeInNsecs;
1998 //TODO: delay standby when effects have a tail
1999 } else {
2000 // If no tracks are ready, sleep once for the duration of an output
2001 // buffer size, then write 0s to the output
2002 if (sleepTime == 0) {
2003 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08002004 sleepTime = activeSleepTime >> sleepTimeShift;
2005 if (sleepTime < kMinThreadSleepTimeUs) {
2006 sleepTime = kMinThreadSleepTimeUs;
2007 }
2008 // reduce sleep time in case of consecutive application underruns to avoid
2009 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2010 // duration we would end up writing less data than needed by the audio HAL if
2011 // the condition persists.
2012 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2013 sleepTimeShift++;
2014 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002015 } else {
2016 sleepTime = idleSleepTime;
2017 }
2018 } else if (mBytesWritten != 0 ||
2019 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2020 memset (mMixBuffer, 0, mixBufferSize);
2021 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002022 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002023 }
2024 // TODO add standby time extension fct of effect tail
2025 }
2026
2027 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002028 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002029 }
2030 // sleepTime == 0 means we must write to audio hardware
2031 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002032 for (size_t i = 0; i < effectChains.size(); i ++) {
2033 effectChains[i]->process_l();
2034 }
2035 // enable changes in effect chain
2036 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037 mLastWriteTime = systemTime();
2038 mInWrite = true;
2039 mBytesWritten += mixBufferSize;
2040
Dima Zavin799a70e2011-04-18 16:57:27 -07002041 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2043 mNumWrites++;
2044 mInWrite = false;
2045 nsecs_t now = systemTime();
2046 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002047 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002048 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002049 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00002050 ALOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002051 ns2ms(delta), mNumDelayedWrites, this);
2052 lastWarning = now;
2053 }
2054 if (mStandby) {
2055 longStandbyExit = true;
2056 }
2057 }
2058 mStandby = false;
2059 } else {
2060 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002061 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 usleep(sleepTime);
2063 }
2064
2065 // finally let go of all our tracks, without the lock held
2066 // since we can't guarantee the destructors won't acquire that
2067 // same lock.
2068 tracksToRemove.clear();
2069
2070 // Effect chains will be actually deleted here if they were removed from
2071 // mEffectChains list during mixing or effects processing
2072 effectChains.clear();
2073 }
2074
2075 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002076 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002077 }
2078
Eric Laurentfeb0db62011-07-22 09:04:31 -07002079 releaseWakeLock();
2080
Steve Block3856b092011-10-20 11:56:00 +01002081 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 return false;
2083}
2084
2085// prepareTracks_l() must be called with ThreadBase::mLock held
2086uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2087{
2088
2089 uint32_t mixerStatus = MIXER_IDLE;
2090 // find out which tracks need to be processed
2091 size_t count = activeTracks.size();
2092 size_t mixedTracks = 0;
2093 size_t tracksWithEffect = 0;
2094
2095 float masterVolume = mMasterVolume;
2096 bool masterMute = mMasterMute;
2097
Eric Laurent571d49c2010-08-11 05:20:11 -07002098 if (masterMute) {
2099 masterVolume = 0;
2100 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002102 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002104 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002105 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 masterVolume = (float)((v + (1 << 23)) >> 24);
2107 chain.clear();
2108 }
2109
2110 for (size_t i=0 ; i<count ; i++) {
2111 sp<Track> t = activeTracks[i].promote();
2112 if (t == 0) continue;
2113
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002114 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115 Track* const track = t.get();
2116 audio_track_cblk_t* cblk = track->cblk();
2117
2118 // The first time a track is added we wait
2119 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002120 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002121 // make sure that we have enough frames to mix one full buffer.
2122 // enforce this condition only once to enable draining the buffer in case the client
2123 // app does not call stop() and relies on underrun to stop:
2124 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2125 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002126 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002127 if (!track->isStopped() && !track->isPausing() &&
2128 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002129 if (t->sampleRate() == (int)mSampleRate) {
2130 minFrames = mFrameCount;
2131 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002132 // +1 for rounding and +1 for additional sample needed for interpolation
2133 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2134 // add frames already consumed but not yet released by the resampler
2135 // because cblk->framesReady() will include these frames
2136 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2137 // the minimum track buffer size is normally twice the number of frames necessary
2138 // to fill one buffer and the resampler should not leave more than one buffer worth
2139 // of unreleased frames after each pass, but just in case...
Steve Blockc1dc1cb2012-01-09 18:35:44 +00002140 ALOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002141 }
2142 }
2143 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 !track->isPaused() && !track->isTerminated())
2145 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002146 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002147
2148 mixedTracks++;
2149
2150 // track->mainBuffer() != mMixBuffer means there is an effect chain
2151 // connected to the track
2152 chain.clear();
2153 if (track->mainBuffer() != mMixBuffer) {
2154 chain = getEffectChain_l(track->sessionId());
2155 // Delegate volume control to effect in track effect chain if needed
2156 if (chain != 0) {
2157 tracksWithEffect++;
2158 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00002159 ALOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002160 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 }
2162 }
2163
2164
2165 int param = AudioMixer::VOLUME;
2166 if (track->mFillingUpStatus == Track::FS_FILLED) {
2167 // no ramp for the first volume setting
2168 track->mFillingUpStatus = Track::FS_ACTIVE;
2169 if (track->mState == TrackBase::RESUMING) {
2170 track->mState = TrackBase::ACTIVE;
2171 param = AudioMixer::RAMP_VOLUME;
2172 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002173 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 } else if (cblk->server != 0) {
2175 // If the track is stopped before the first frame was mixed,
2176 // do not apply ramp
2177 param = AudioMixer::RAMP_VOLUME;
2178 }
2179
2180 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002181 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002182 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002183 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002184 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 if (track->isPausing()) {
2186 track->setPaused();
2187 }
2188 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002189
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190 // read original volumes with volume control
2191 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002193 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2194 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002195
Glenn Kasten05632a52012-01-03 14:22:33 -08002196 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2197 // send level comes from shared memory and so may be corrupt
2198 if (sendLevel >= 0x1000) {
2199 ALOGV("Track send level out of range: %04X", sendLevel);
2200 sendLevel = 0x1000;
2201 }
2202 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002204 // Delegate volume control to effect in track effect chain if needed
2205 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2206 // Do not ramp volume if volume is controlled by effect
2207 param = AudioMixer::VOLUME;
2208 track->mHasVolumeController = true;
2209 } else {
2210 // force no volume ramp when volume controller was just disabled or removed
2211 // from effect chain to avoid volume spike
2212 if (track->mHasVolumeController) {
2213 param = AudioMixer::VOLUME;
2214 }
2215 track->mHasVolumeController = false;
2216 }
2217
2218 // Convert volumes from 8.24 to 4.12 format
2219 int16_t left, right, aux;
2220 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2221 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2222 left = int16_t(v_clamped);
2223 v_clamped = (vr + (1 << 11)) >> 12;
2224 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2225 right = int16_t(v_clamped);
2226
2227 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2228 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002231 mAudioMixer->setBufferProvider(name, track);
2232 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002234 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2235 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2236 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002238 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002239 AudioMixer::TRACK,
2240 AudioMixer::FORMAT, (void *)track->format());
2241 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002242 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002244 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002246 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 AudioMixer::RESAMPLE,
2248 AudioMixer::SAMPLE_RATE,
2249 (void *)(cblk->sampleRate));
2250 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002251 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 AudioMixer::TRACK,
2253 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2254 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002255 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002256 AudioMixer::TRACK,
2257 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2258
2259 // reset retry count
2260 track->mRetryCount = kMaxTrackRetries;
2261 mixerStatus = MIXER_TRACKS_READY;
2262 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002263 //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 -07002264 if (track->isStopped()) {
2265 track->reset();
2266 }
2267 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2268 // We have consumed all the buffers of this track.
2269 // Remove it from the list of active tracks.
2270 tracksToRemove->add(track);
2271 } else {
2272 // No buffers for this track. Give it a few chances to
2273 // fill a buffer, then remove it from active list.
2274 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002275 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002276 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002277 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002278 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 } else if (mixerStatus != MIXER_TRACKS_READY) {
2280 mixerStatus = MIXER_TRACKS_ENABLED;
2281 }
2282 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002283 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 }
2285 }
2286
2287 // remove all the tracks that need to be...
2288 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002289 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 for (size_t i=0 ; i<count ; i++) {
2291 const sp<Track>& track = tracksToRemove->itemAt(i);
2292 mActiveTracks.remove(track);
2293 if (track->mainBuffer() != mMixBuffer) {
2294 chain = getEffectChain_l(track->sessionId());
2295 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002296 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002297 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 }
2299 }
2300 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002301 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002302 }
2303 }
2304 }
2305
2306 // mix buffer must be cleared if all tracks are connected to an
2307 // effect chain as in this case the mixer will not write to
2308 // mix buffer and track effects will accumulate into it
2309 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2310 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2311 }
2312
2313 return mixerStatus;
2314}
2315
Glenn Kastenfff6d712012-01-12 16:38:12 -08002316void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317{
Steve Block3856b092011-10-20 11:56:00 +01002318 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002319 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002321
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 size_t size = mTracks.size();
2323 for (size_t i = 0; i < size; i++) {
2324 sp<Track> t = mTracks[i];
2325 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002326 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 }
2329 }
2330}
2331
Glenn Kastenfff6d712012-01-12 16:38:12 -08002332void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002333{
Steve Block3856b092011-10-20 11:56:00 +01002334 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002335 this, streamType, valid);
2336 Mutex::Autolock _l(mLock);
2337
2338 mStreamTypes[streamType].valid = valid;
2339}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340
2341// getTrackName_l() must be called with ThreadBase::mLock held
2342int AudioFlinger::MixerThread::getTrackName_l()
2343{
2344 return mAudioMixer->getTrackName();
2345}
2346
2347// deleteTrackName_l() must be called with ThreadBase::mLock held
2348void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2349{
Steve Block3856b092011-10-20 11:56:00 +01002350 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002351 mAudioMixer->deleteTrackName(name);
2352}
2353
2354// checkForNewParameters_l() must be called with ThreadBase::mLock held
2355bool AudioFlinger::MixerThread::checkForNewParameters_l()
2356{
2357 bool reconfig = false;
2358
2359 while (!mNewParameters.isEmpty()) {
2360 status_t status = NO_ERROR;
2361 String8 keyValuePair = mNewParameters[0];
2362 AudioParameter param = AudioParameter(keyValuePair);
2363 int value;
2364
2365 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2366 reconfig = true;
2367 }
2368 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002369 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002370 status = BAD_VALUE;
2371 } else {
2372 reconfig = true;
2373 }
2374 }
2375 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002376 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002377 status = BAD_VALUE;
2378 } else {
2379 reconfig = true;
2380 }
2381 }
2382 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2383 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002384 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 // if frame count is changed after track creation
2386 if (!mTracks.isEmpty()) {
2387 status = INVALID_OPERATION;
2388 } else {
2389 reconfig = true;
2390 }
2391 }
2392 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002393 // when changing the audio output device, call addBatteryData to notify
2394 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002395 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002396 uint32_t params = 0;
2397 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002398 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002399 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2400 }
2401
2402 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002403 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002404 // check if any other device (except speaker) is on
2405 if (value & deviceWithoutSpeaker ) {
2406 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2407 }
2408
2409 if (params != 0) {
2410 addBatteryData(params);
2411 }
2412 }
2413
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 // forward device change to effects that have requested to be
2415 // aware of attached audio device.
2416 mDevice = (uint32_t)value;
2417 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002418 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002419 }
2420 }
2421
2422 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002423 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002424 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002426 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002427 mStandby = true;
2428 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002429 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002430 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002431 }
2432 if (status == NO_ERROR && reconfig) {
2433 delete mAudioMixer;
2434 readOutputParameters();
2435 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2436 for (size_t i = 0; i < mTracks.size() ; i++) {
2437 int name = getTrackName_l();
2438 if (name < 0) break;
2439 mTracks[i]->mName = name;
2440 // limit track sample rate to 2 x new output sample rate
2441 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2442 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2443 }
2444 }
2445 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2446 }
2447 }
2448
2449 mNewParameters.removeAt(0);
2450
2451 mParamStatus = status;
2452 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002453 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2454 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002455 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456 }
2457 return reconfig;
2458}
2459
2460status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2461{
2462 const size_t SIZE = 256;
2463 char buffer[SIZE];
2464 String8 result;
2465
2466 PlaybackThread::dumpInternals(fd, args);
2467
2468 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2469 result.append(buffer);
2470 write(fd, result.string(), result.size());
2471 return NO_ERROR;
2472}
2473
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2475{
Eric Laurent60e18242010-07-29 06:50:24 -07002476 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477}
2478
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002479uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2480{
2481 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2482}
2483
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002485AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 : PlaybackThread(audioFlinger, output, id, device)
2487{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002488 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489}
2490
2491AudioFlinger::DirectOutputThread::~DirectOutputThread()
2492{
2493}
2494
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495static inline
2496int32_t mul(int16_t in, int16_t v)
2497{
2498#if defined(__arm__) && !defined(__thumb__)
2499 int32_t out;
2500 asm( "smulbb %[out], %[in], %[v] \n"
2501 : [out]"=r"(out)
2502 : [in]"%r"(in), [v]"r"(v)
2503 : );
2504 return out;
2505#else
2506 return in * int32_t(v);
2507#endif
2508}
2509
2510void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2511{
2512 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002513 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002514 return;
2515 }
2516
2517 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002518 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519 size_t count = mFrameCount * mChannelCount;
2520 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2521 int16_t *dst = mMixBuffer + count-1;
2522 while(count--) {
2523 *dst-- = (int16_t)(*src--^0x80) << 8;
2524 }
2525 }
2526
2527 size_t frameCount = mFrameCount;
2528 int16_t *out = mMixBuffer;
2529 if (ramp) {
2530 if (mChannelCount == 1) {
2531 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2532 int32_t vlInc = d / (int32_t)frameCount;
2533 int32_t vl = ((int32_t)mLeftVolShort << 16);
2534 do {
2535 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2536 out++;
2537 vl += vlInc;
2538 } while (--frameCount);
2539
2540 } else {
2541 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2542 int32_t vlInc = d / (int32_t)frameCount;
2543 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2544 int32_t vrInc = d / (int32_t)frameCount;
2545 int32_t vl = ((int32_t)mLeftVolShort << 16);
2546 int32_t vr = ((int32_t)mRightVolShort << 16);
2547 do {
2548 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2549 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2550 out += 2;
2551 vl += vlInc;
2552 vr += vrInc;
2553 } while (--frameCount);
2554 }
2555 } else {
2556 if (mChannelCount == 1) {
2557 do {
2558 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2559 out++;
2560 } while (--frameCount);
2561 } else {
2562 do {
2563 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2564 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2565 out += 2;
2566 } while (--frameCount);
2567 }
2568 }
2569
2570 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002571 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002572 size_t count = mFrameCount * mChannelCount;
2573 int16_t *src = mMixBuffer;
2574 uint8_t *dst = (uint8_t *)mMixBuffer;
2575 while(count--) {
2576 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2577 }
2578 }
2579
2580 mLeftVolShort = leftVol;
2581 mRightVolShort = rightVol;
2582}
2583
2584bool AudioFlinger::DirectOutputThread::threadLoop()
2585{
2586 uint32_t mixerStatus = MIXER_IDLE;
2587 sp<Track> trackToRemove;
2588 sp<Track> activeTrack;
2589 nsecs_t standbyTime = systemTime();
2590 int8_t *curBuf;
2591 size_t mixBufferSize = mFrameCount*mFrameSize;
2592 uint32_t activeSleepTime = activeSleepTimeUs();
2593 uint32_t idleSleepTime = idleSleepTimeUs();
2594 uint32_t sleepTime = idleSleepTime;
2595 // use shorter standby delay as on normal output to release
2596 // hardware resources as soon as possible
2597 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2598
Eric Laurentfeb0db62011-07-22 09:04:31 -07002599 acquireWakeLock();
2600
Mathias Agopian65ab4712010-07-14 17:59:35 -07002601 while (!exitPending())
2602 {
2603 bool rampVolume;
2604 uint16_t leftVol;
2605 uint16_t rightVol;
2606 Vector< sp<EffectChain> > effectChains;
2607
2608 processConfigEvents();
2609
2610 mixerStatus = MIXER_IDLE;
2611
2612 { // scope for the mLock
2613
2614 Mutex::Autolock _l(mLock);
2615
2616 if (checkForNewParameters_l()) {
2617 mixBufferSize = mFrameCount*mFrameSize;
2618 activeSleepTime = activeSleepTimeUs();
2619 idleSleepTime = idleSleepTimeUs();
2620 standbyDelay = microseconds(activeSleepTime*2);
2621 }
2622
2623 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002624 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2625 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002626 // wait until we have something to do...
2627 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002628 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002629 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 mStandby = true;
2631 mBytesWritten = 0;
2632 }
2633
2634 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2635 // we're about to wait, flush the binder command buffer
2636 IPCThreadState::self()->flushCommands();
2637
2638 if (exitPending()) break;
2639
Eric Laurentfeb0db62011-07-22 09:04:31 -07002640 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002641 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002643 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002644 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645
2646 if (mMasterMute == false) {
2647 char value[PROPERTY_VALUE_MAX];
2648 property_get("ro.audio.silent", value, "0");
2649 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002650 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002651 setMasterMute(true);
2652 }
2653 }
2654
2655 standbyTime = systemTime() + standbyDelay;
2656 sleepTime = idleSleepTime;
2657 continue;
2658 }
2659 }
2660
2661 effectChains = mEffectChains;
2662
2663 // find out which tracks need to be processed
2664 if (mActiveTracks.size() != 0) {
2665 sp<Track> t = mActiveTracks[0].promote();
2666 if (t == 0) continue;
2667
2668 Track* const track = t.get();
2669 audio_track_cblk_t* cblk = track->cblk();
2670
2671 // The first time a track is added we wait
2672 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002673 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002674 !track->isPaused() && !track->isTerminated())
2675 {
Steve Block3856b092011-10-20 11:56:00 +01002676 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002677
2678 if (track->mFillingUpStatus == Track::FS_FILLED) {
2679 track->mFillingUpStatus = Track::FS_ACTIVE;
2680 mLeftVolFloat = mRightVolFloat = 0;
2681 mLeftVolShort = mRightVolShort = 0;
2682 if (track->mState == TrackBase::RESUMING) {
2683 track->mState = TrackBase::ACTIVE;
2684 rampVolume = true;
2685 }
2686 } else if (cblk->server != 0) {
2687 // If the track is stopped before the first frame was mixed,
2688 // do not apply ramp
2689 rampVolume = true;
2690 }
2691 // compute volume for this track
2692 float left, right;
2693 if (track->isMuted() || mMasterMute || track->isPausing() ||
2694 mStreamTypes[track->type()].mute) {
2695 left = right = 0;
2696 if (track->isPausing()) {
2697 track->setPaused();
2698 }
2699 } else {
2700 float typeVolume = mStreamTypes[track->type()].volume;
2701 float v = mMasterVolume * typeVolume;
2702 float v_clamped = v * cblk->volume[0];
2703 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2704 left = v_clamped/MAX_GAIN;
2705 v_clamped = v * cblk->volume[1];
2706 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2707 right = v_clamped/MAX_GAIN;
2708 }
2709
2710 if (left != mLeftVolFloat || right != mRightVolFloat) {
2711 mLeftVolFloat = left;
2712 mRightVolFloat = right;
2713
2714 // If audio HAL implements volume control,
2715 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002716 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002717 left = 1.0f;
2718 right = 1.0f;
2719 }
2720
2721 // Convert volumes from float to 8.24
2722 uint32_t vl = (uint32_t)(left * (1 << 24));
2723 uint32_t vr = (uint32_t)(right * (1 << 24));
2724
2725 // Delegate volume control to effect in track effect chain if needed
2726 // only one effect chain can be present on DirectOutputThread, so if
2727 // there is one, the track is connected to it
2728 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002729 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002730 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 rampVolume = false;
2732 }
2733 }
2734
2735 // Convert volumes from 8.24 to 4.12 format
2736 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2737 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2738 leftVol = (uint16_t)v_clamped;
2739 v_clamped = (vr + (1 << 11)) >> 12;
2740 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2741 rightVol = (uint16_t)v_clamped;
2742 } else {
2743 leftVol = mLeftVolShort;
2744 rightVol = mRightVolShort;
2745 rampVolume = false;
2746 }
2747
2748 // reset retry count
2749 track->mRetryCount = kMaxTrackRetriesDirect;
2750 activeTrack = t;
2751 mixerStatus = MIXER_TRACKS_READY;
2752 } else {
Steve Block3856b092011-10-20 11:56:00 +01002753 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 if (track->isStopped()) {
2755 track->reset();
2756 }
2757 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2758 // We have consumed all the buffers of this track.
2759 // Remove it from the list of active tracks.
2760 trackToRemove = track;
2761 } else {
2762 // No buffers for this track. Give it a few chances to
2763 // fill a buffer, then remove it from active list.
2764 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002765 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002766 trackToRemove = track;
2767 } else {
2768 mixerStatus = MIXER_TRACKS_ENABLED;
2769 }
2770 }
2771 }
2772 }
2773
2774 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002775 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002776 mActiveTracks.remove(trackToRemove);
2777 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002778 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002779 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002780 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781 }
2782 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002783 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002784 }
2785 }
2786
Eric Laurentde070132010-07-13 04:45:46 -07002787 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 }
2789
Glenn Kastenf6b16782011-12-15 09:51:17 -08002790 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 AudioBufferProvider::Buffer buffer;
2792 size_t frameCount = mFrameCount;
2793 curBuf = (int8_t *)mMixBuffer;
2794 // output audio to hardware
2795 while (frameCount) {
2796 buffer.frameCount = frameCount;
2797 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002798 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799 memset(curBuf, 0, frameCount * mFrameSize);
2800 break;
2801 }
2802 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2803 frameCount -= buffer.frameCount;
2804 curBuf += buffer.frameCount * mFrameSize;
2805 activeTrack->releaseBuffer(&buffer);
2806 }
2807 sleepTime = 0;
2808 standbyTime = systemTime() + standbyDelay;
2809 } else {
2810 if (sleepTime == 0) {
2811 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2812 sleepTime = activeSleepTime;
2813 } else {
2814 sleepTime = idleSleepTime;
2815 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002816 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002817 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2818 sleepTime = 0;
2819 }
2820 }
2821
2822 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002823 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 }
2825 // sleepTime == 0 means we must write to audio hardware
2826 if (sleepTime == 0) {
2827 if (mixerStatus == MIXER_TRACKS_READY) {
2828 applyVolume(leftVol, rightVol, rampVolume);
2829 }
2830 for (size_t i = 0; i < effectChains.size(); i ++) {
2831 effectChains[i]->process_l();
2832 }
Eric Laurentde070132010-07-13 04:45:46 -07002833 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834
2835 mLastWriteTime = systemTime();
2836 mInWrite = true;
2837 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002838 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2840 mNumWrites++;
2841 mInWrite = false;
2842 mStandby = false;
2843 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002844 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 usleep(sleepTime);
2846 }
2847
2848 // finally let go of removed track, without the lock held
2849 // since we can't guarantee the destructors won't acquire that
2850 // same lock.
2851 trackToRemove.clear();
2852 activeTrack.clear();
2853
2854 // Effect chains will be actually deleted here if they were removed from
2855 // mEffectChains list during mixing or effects processing
2856 effectChains.clear();
2857 }
2858
2859 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002860 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002861 }
2862
Eric Laurentfeb0db62011-07-22 09:04:31 -07002863 releaseWakeLock();
2864
Steve Block3856b092011-10-20 11:56:00 +01002865 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866 return false;
2867}
2868
2869// getTrackName_l() must be called with ThreadBase::mLock held
2870int AudioFlinger::DirectOutputThread::getTrackName_l()
2871{
2872 return 0;
2873}
2874
2875// deleteTrackName_l() must be called with ThreadBase::mLock held
2876void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2877{
2878}
2879
2880// checkForNewParameters_l() must be called with ThreadBase::mLock held
2881bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2882{
2883 bool reconfig = false;
2884
2885 while (!mNewParameters.isEmpty()) {
2886 status_t status = NO_ERROR;
2887 String8 keyValuePair = mNewParameters[0];
2888 AudioParameter param = AudioParameter(keyValuePair);
2889 int value;
2890
2891 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2892 // do not accept frame count changes if tracks are open as the track buffer
2893 // size depends on frame count and correct behavior would not be garantied
2894 // if frame count is changed after track creation
2895 if (!mTracks.isEmpty()) {
2896 status = INVALID_OPERATION;
2897 } else {
2898 reconfig = true;
2899 }
2900 }
2901 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002902 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002903 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002904 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002905 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 mStandby = true;
2907 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002908 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002909 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002910 }
2911 if (status == NO_ERROR && reconfig) {
2912 readOutputParameters();
2913 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2914 }
2915 }
2916
2917 mNewParameters.removeAt(0);
2918
2919 mParamStatus = status;
2920 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002921 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2922 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002923 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 }
2925 return reconfig;
2926}
2927
2928uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2929{
2930 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002931 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002932 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933 } else {
2934 time = 10000;
2935 }
2936 return time;
2937}
2938
2939uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2940{
2941 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002942 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002943 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 } else {
2945 time = 10000;
2946 }
2947 return time;
2948}
2949
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002950uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2951{
2952 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002953 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002954 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2955 } else {
2956 time = 10000;
2957 }
2958 return time;
2959}
2960
2961
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962// ----------------------------------------------------------------------------
2963
2964AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2965 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2966{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002967 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002968 addOutputTrack(mainThread);
2969}
2970
2971AudioFlinger::DuplicatingThread::~DuplicatingThread()
2972{
2973 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2974 mOutputTracks[i]->destroy();
2975 }
2976 mOutputTracks.clear();
2977}
2978
2979bool AudioFlinger::DuplicatingThread::threadLoop()
2980{
2981 Vector< sp<Track> > tracksToRemove;
2982 uint32_t mixerStatus = MIXER_IDLE;
2983 nsecs_t standbyTime = systemTime();
2984 size_t mixBufferSize = mFrameCount*mFrameSize;
2985 SortedVector< sp<OutputTrack> > outputTracks;
2986 uint32_t writeFrames = 0;
2987 uint32_t activeSleepTime = activeSleepTimeUs();
2988 uint32_t idleSleepTime = idleSleepTimeUs();
2989 uint32_t sleepTime = idleSleepTime;
2990 Vector< sp<EffectChain> > effectChains;
2991
Eric Laurentfeb0db62011-07-22 09:04:31 -07002992 acquireWakeLock();
2993
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 while (!exitPending())
2995 {
2996 processConfigEvents();
2997
2998 mixerStatus = MIXER_IDLE;
2999 { // scope for the mLock
3000
3001 Mutex::Autolock _l(mLock);
3002
3003 if (checkForNewParameters_l()) {
3004 mixBufferSize = mFrameCount*mFrameSize;
3005 updateWaitTime();
3006 activeSleepTime = activeSleepTimeUs();
3007 idleSleepTime = idleSleepTimeUs();
3008 }
3009
3010 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3011
3012 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3013 outputTracks.add(mOutputTracks[i]);
3014 }
3015
3016 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003017 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3018 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 if (!mStandby) {
3020 for (size_t i = 0; i < outputTracks.size(); i++) {
3021 outputTracks[i]->stop();
3022 }
3023 mStandby = true;
3024 mBytesWritten = 0;
3025 }
3026
3027 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3028 // we're about to wait, flush the binder command buffer
3029 IPCThreadState::self()->flushCommands();
3030 outputTracks.clear();
3031
3032 if (exitPending()) break;
3033
Eric Laurentfeb0db62011-07-22 09:04:31 -07003034 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003035 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003037 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003038 acquireWakeLock_l();
3039
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 if (mMasterMute == false) {
3041 char value[PROPERTY_VALUE_MAX];
3042 property_get("ro.audio.silent", value, "0");
3043 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003044 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003045 setMasterMute(true);
3046 }
3047 }
3048
3049 standbyTime = systemTime() + kStandbyTimeInNsecs;
3050 sleepTime = idleSleepTime;
3051 continue;
3052 }
3053 }
3054
3055 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3056
3057 // prevent any changes in effect chain list and in each effect chain
3058 // during mixing and effect process as the audio buffers could be deleted
3059 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003060 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 }
3062
Glenn Kastenf6b16782011-12-15 09:51:17 -08003063 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 // mix buffers...
3065 if (outputsReady(outputTracks)) {
3066 mAudioMixer->process();
3067 } else {
3068 memset(mMixBuffer, 0, mixBufferSize);
3069 }
3070 sleepTime = 0;
3071 writeFrames = mFrameCount;
3072 } else {
3073 if (sleepTime == 0) {
3074 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3075 sleepTime = activeSleepTime;
3076 } else {
3077 sleepTime = idleSleepTime;
3078 }
3079 } else if (mBytesWritten != 0) {
3080 // flush remaining overflow buffers in output tracks
3081 for (size_t i = 0; i < outputTracks.size(); i++) {
3082 if (outputTracks[i]->isActive()) {
3083 sleepTime = 0;
3084 writeFrames = 0;
3085 memset(mMixBuffer, 0, mixBufferSize);
3086 break;
3087 }
3088 }
3089 }
3090 }
3091
3092 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003093 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094 }
3095 // sleepTime == 0 means we must write to audio hardware
3096 if (sleepTime == 0) {
3097 for (size_t i = 0; i < effectChains.size(); i ++) {
3098 effectChains[i]->process_l();
3099 }
3100 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003101 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003102
3103 standbyTime = systemTime() + kStandbyTimeInNsecs;
3104 for (size_t i = 0; i < outputTracks.size(); i++) {
3105 outputTracks[i]->write(mMixBuffer, writeFrames);
3106 }
3107 mStandby = false;
3108 mBytesWritten += mixBufferSize;
3109 } else {
3110 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003111 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112 usleep(sleepTime);
3113 }
3114
3115 // finally let go of all our tracks, without the lock held
3116 // since we can't guarantee the destructors won't acquire that
3117 // same lock.
3118 tracksToRemove.clear();
3119 outputTracks.clear();
3120
3121 // Effect chains will be actually deleted here if they were removed from
3122 // mEffectChains list during mixing or effects processing
3123 effectChains.clear();
3124 }
3125
Eric Laurentfeb0db62011-07-22 09:04:31 -07003126 releaseWakeLock();
3127
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128 return false;
3129}
3130
3131void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3132{
3133 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3134 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3135 this,
3136 mSampleRate,
3137 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003138 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139 frameCount);
3140 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003141 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003143 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003144 updateWaitTime();
3145 }
3146}
3147
3148void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3149{
3150 Mutex::Autolock _l(mLock);
3151 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3152 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3153 mOutputTracks[i]->destroy();
3154 mOutputTracks.removeAt(i);
3155 updateWaitTime();
3156 return;
3157 }
3158 }
Steve Block3856b092011-10-20 11:56:00 +01003159 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003160}
3161
3162void AudioFlinger::DuplicatingThread::updateWaitTime()
3163{
3164 mWaitTimeMs = UINT_MAX;
3165 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3166 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3167 if (strong != NULL) {
3168 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3169 if (waitTimeMs < mWaitTimeMs) {
3170 mWaitTimeMs = waitTimeMs;
3171 }
3172 }
3173 }
3174}
3175
3176
3177bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3178{
3179 for (size_t i = 0; i < outputTracks.size(); i++) {
3180 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3181 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003182 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 return false;
3184 }
3185 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3186 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003187 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003188 return false;
3189 }
3190 }
3191 return true;
3192}
3193
3194uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3195{
3196 return (mWaitTimeMs * 1000) / 2;
3197}
3198
3199// ----------------------------------------------------------------------------
3200
3201// TrackBase constructor must be called with AudioFlinger::mLock held
3202AudioFlinger::ThreadBase::TrackBase::TrackBase(
3203 const wp<ThreadBase>& thread,
3204 const sp<Client>& client,
3205 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003206 uint32_t format,
3207 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003208 int frameCount,
3209 uint32_t flags,
3210 const sp<IMemory>& sharedBuffer,
3211 int sessionId)
3212 : RefBase(),
3213 mThread(thread),
3214 mClient(client),
3215 mCblk(0),
3216 mFrameCount(0),
3217 mState(IDLE),
3218 mClientTid(-1),
3219 mFormat(format),
3220 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3221 mSessionId(sessionId)
3222{
Steve Block3856b092011-10-20 11:56:00 +01003223 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003224
Steve Blockb8a80522011-12-20 16:23:08 +00003225 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003226 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003227 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3229 if (sharedBuffer == 0) {
3230 size += bufferSize;
3231 }
3232
3233 if (client != NULL) {
3234 mCblkMemory = client->heap()->allocate(size);
3235 if (mCblkMemory != 0) {
3236 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3237 if (mCblk) { // construct the shared structure in-place.
3238 new(mCblk) audio_track_cblk_t();
3239 // clear all buffers
3240 mCblk->frameCount = frameCount;
3241 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003242 mChannelCount = channelCount;
3243 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003244 if (sharedBuffer == 0) {
3245 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3246 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3247 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003248 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mCblk->flags = CBLK_UNDERRUN_ON;
3250 } else {
3251 mBuffer = sharedBuffer->pointer();
3252 }
3253 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3254 }
3255 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003256 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003257 client->heap()->dump("AudioTrack");
3258 return;
3259 }
3260 } else {
3261 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003262 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003263 new(mCblk) audio_track_cblk_t();
3264 // clear all buffers
3265 mCblk->frameCount = frameCount;
3266 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003267 mChannelCount = channelCount;
3268 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003269 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3270 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3271 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003272 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 mCblk->flags = CBLK_UNDERRUN_ON;
3274 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 }
3276}
3277
3278AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3279{
3280 if (mCblk) {
3281 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3282 if (mClient == NULL) {
3283 delete mCblk;
3284 }
3285 }
3286 mCblkMemory.clear(); // and free the shared memory
3287 if (mClient != NULL) {
3288 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3289 mClient.clear();
3290 }
3291}
3292
3293void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3294{
Glenn Kastene0feee32011-12-13 11:53:26 -08003295 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 mFrameCount = buffer->frameCount;
3297 step();
3298 buffer->frameCount = 0;
3299}
3300
3301bool AudioFlinger::ThreadBase::TrackBase::step() {
3302 bool result;
3303 audio_track_cblk_t* cblk = this->cblk();
3304
3305 result = cblk->stepServer(mFrameCount);
3306 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003307 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 mFlags |= STEPSERVER_FAILED;
3309 }
3310 return result;
3311}
3312
3313void AudioFlinger::ThreadBase::TrackBase::reset() {
3314 audio_track_cblk_t* cblk = this->cblk();
3315
3316 cblk->user = 0;
3317 cblk->server = 0;
3318 cblk->userBase = 0;
3319 cblk->serverBase = 0;
3320 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003321 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003322}
3323
3324sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3325{
3326 return mCblkMemory;
3327}
3328
3329int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3330 return (int)mCblk->sampleRate;
3331}
3332
3333int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003334 return (const int)mChannelCount;
3335}
3336
3337uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3338 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339}
3340
3341void* 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);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354 return 0;
3355 }
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,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003368 uint32_t format,
3369 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 }
Steve Block3856b092011-10-20 11:56:00 +01003384 ALOGV("Track constructor name %d, calling thread %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 }
3388 mVolume[0] = 1.0f;
3389 mVolume[1] = 1.0f;
3390 mStreamType = streamType;
3391 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3392 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003393 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 }
3395}
3396
3397AudioFlinger::PlaybackThread::Track::~Track()
3398{
Steve Block3856b092011-10-20 11:56:00 +01003399 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 sp<ThreadBase> thread = mThread.promote();
3401 if (thread != 0) {
3402 Mutex::Autolock _l(thread->mLock);
3403 mState = TERMINATED;
3404 }
3405}
3406
3407void AudioFlinger::PlaybackThread::Track::destroy()
3408{
3409 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3410 // by removing it from mTracks vector, so there is a risk that this Tracks's
3411 // desctructor is called. As the destructor needs to lock mLock,
3412 // we must acquire a strong reference on this Track before locking mLock
3413 // here so that the destructor is called only when exiting this function.
3414 // On the other hand, as long as Track::destroy() is only called by
3415 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3416 // this Track with its member mTrack.
3417 sp<Track> keep(this);
3418 { // scope for mLock
3419 sp<ThreadBase> thread = mThread.promote();
3420 if (thread != 0) {
3421 if (!isOutputTrack()) {
3422 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003423 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003424 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003425 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003426
3427 // to track the speaker usage
3428 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003429 }
3430 AudioSystem::releaseOutput(thread->id());
3431 }
3432 Mutex::Autolock _l(thread->mLock);
3433 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3434 playbackThread->destroyTrack_l(this);
3435 }
3436 }
3437}
3438
3439void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3440{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003441 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 -07003442 mName - AudioMixer::TRACK0,
3443 (mClient == NULL) ? getpid() : mClient->pid(),
3444 mStreamType,
3445 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003446 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 mSessionId,
3448 mFrameCount,
3449 mState,
3450 mMute,
3451 mFillingUpStatus,
3452 mCblk->sampleRate,
3453 mCblk->volume[0],
3454 mCblk->volume[1],
3455 mCblk->server,
3456 mCblk->user,
3457 (int)mMainBuffer,
3458 (int)mAuxBuffer);
3459}
3460
3461status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3462{
3463 audio_track_cblk_t* cblk = this->cblk();
3464 uint32_t framesReady;
3465 uint32_t framesReq = buffer->frameCount;
3466
3467 // Check if last stepServer failed, try to step now
3468 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3469 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003470 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3472 }
3473
3474 framesReady = cblk->framesReady();
3475
Glenn Kastenf6b16782011-12-15 09:51:17 -08003476 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 uint32_t s = cblk->server;
3478 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3479
3480 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3481 if (framesReq > framesReady) {
3482 framesReq = framesReady;
3483 }
3484 if (s + framesReq > bufferEnd) {
3485 framesReq = bufferEnd - s;
3486 }
3487
3488 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003489 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003490
3491 buffer->frameCount = framesReq;
3492 return NO_ERROR;
3493 }
3494
3495getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003496 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003498 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003499 return NOT_ENOUGH_DATA;
3500}
3501
3502bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003503 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504
3505 if (mCblk->framesReady() >= mCblk->frameCount ||
3506 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3507 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003508 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 return true;
3510 }
3511 return false;
3512}
3513
3514status_t AudioFlinger::PlaybackThread::Track::start()
3515{
3516 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003517 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003518 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003519 sp<ThreadBase> thread = mThread.promote();
3520 if (thread != 0) {
3521 Mutex::Autolock _l(thread->mLock);
3522 int state = mState;
3523 // here the track could be either new, or restarted
3524 // in both cases "unstop" the track
3525 if (mState == PAUSED) {
3526 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003527 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003528 } else {
3529 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003530 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003531 }
3532
3533 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3534 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003535 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003536 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003537 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003539
3540 // to track the speaker usage
3541 if (status == NO_ERROR) {
3542 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544 }
3545 if (status == NO_ERROR) {
3546 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3547 playbackThread->addTrack_l(this);
3548 } else {
3549 mState = state;
3550 }
3551 } else {
3552 status = BAD_VALUE;
3553 }
3554 return status;
3555}
3556
3557void AudioFlinger::PlaybackThread::Track::stop()
3558{
Steve Block3856b092011-10-20 11:56:00 +01003559 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 sp<ThreadBase> thread = mThread.promote();
3561 if (thread != 0) {
3562 Mutex::Autolock _l(thread->mLock);
3563 int state = mState;
3564 if (mState > STOPPED) {
3565 mState = STOPPED;
3566 // If the track is not active (PAUSED and buffers full), flush buffers
3567 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3568 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3569 reset();
3570 }
Steve Block3856b092011-10-20 11:56:00 +01003571 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572 }
3573 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3574 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003575 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003576 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003577 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003579
3580 // to track the speaker usage
3581 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 }
3583 }
3584}
3585
3586void AudioFlinger::PlaybackThread::Track::pause()
3587{
Steve Block3856b092011-10-20 11:56:00 +01003588 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 sp<ThreadBase> thread = mThread.promote();
3590 if (thread != 0) {
3591 Mutex::Autolock _l(thread->mLock);
3592 if (mState == ACTIVE || mState == RESUMING) {
3593 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003594 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 if (!isOutputTrack()) {
3596 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003597 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003598 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003599 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003600 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003601
3602 // to track the speaker usage
3603 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 }
3605 }
3606 }
3607}
3608
3609void AudioFlinger::PlaybackThread::Track::flush()
3610{
Steve Block3856b092011-10-20 11:56:00 +01003611 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003612 sp<ThreadBase> thread = mThread.promote();
3613 if (thread != 0) {
3614 Mutex::Autolock _l(thread->mLock);
3615 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3616 return;
3617 }
3618 // No point remaining in PAUSED state after a flush => go to
3619 // STOPPED state
3620 mState = STOPPED;
3621
Eric Laurent38ccae22011-03-28 18:37:07 -07003622 // do not reset the track if it is still in the process of being stopped or paused.
3623 // this will be done by prepareTracks_l() when the track is stopped.
3624 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3625 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3626 reset();
3627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 }
3629}
3630
3631void AudioFlinger::PlaybackThread::Track::reset()
3632{
3633 // Do not reset twice to avoid discarding data written just after a flush and before
3634 // the audioflinger thread detects the track is stopped.
3635 if (!mResetDone) {
3636 TrackBase::reset();
3637 // Force underrun condition to avoid false underrun callback until first data is
3638 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003639 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3640 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003641 mFillingUpStatus = FS_FILLING;
3642 mResetDone = true;
3643 }
3644}
3645
3646void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3647{
3648 mMute = muted;
3649}
3650
3651void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3652{
3653 mVolume[0] = left;
3654 mVolume[1] = right;
3655}
3656
3657status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3658{
3659 status_t status = DEAD_OBJECT;
3660 sp<ThreadBase> thread = mThread.promote();
3661 if (thread != 0) {
3662 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3663 status = playbackThread->attachAuxEffect(this, EffectId);
3664 }
3665 return status;
3666}
3667
3668void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3669{
3670 mAuxEffectId = EffectId;
3671 mAuxBuffer = buffer;
3672}
3673
3674// ----------------------------------------------------------------------------
3675
3676// RecordTrack constructor must be called with AudioFlinger::mLock held
3677AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3678 const wp<ThreadBase>& thread,
3679 const sp<Client>& client,
3680 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003681 uint32_t format,
3682 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003683 int frameCount,
3684 uint32_t flags,
3685 int sessionId)
3686 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003687 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 mOverflow(false)
3689{
3690 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003691 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003692 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003693 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003694 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003695 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 } else {
3697 mCblk->frameSize = sizeof(int8_t);
3698 }
3699 }
3700}
3701
3702AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3703{
3704 sp<ThreadBase> thread = mThread.promote();
3705 if (thread != 0) {
3706 AudioSystem::releaseInput(thread->id());
3707 }
3708}
3709
3710status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3711{
3712 audio_track_cblk_t* cblk = this->cblk();
3713 uint32_t framesAvail;
3714 uint32_t framesReq = buffer->frameCount;
3715
3716 // Check if last stepServer failed, try to step now
3717 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3718 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003719 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3721 }
3722
3723 framesAvail = cblk->framesAvailable_l();
3724
Glenn Kastenf6b16782011-12-15 09:51:17 -08003725 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726 uint32_t s = cblk->server;
3727 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3728
3729 if (framesReq > framesAvail) {
3730 framesReq = framesAvail;
3731 }
3732 if (s + framesReq > bufferEnd) {
3733 framesReq = bufferEnd - s;
3734 }
3735
3736 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003737 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003738
3739 buffer->frameCount = framesReq;
3740 return NO_ERROR;
3741 }
3742
3743getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003744 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003745 buffer->frameCount = 0;
3746 return NOT_ENOUGH_DATA;
3747}
3748
3749status_t AudioFlinger::RecordThread::RecordTrack::start()
3750{
3751 sp<ThreadBase> thread = mThread.promote();
3752 if (thread != 0) {
3753 RecordThread *recordThread = (RecordThread *)thread.get();
3754 return recordThread->start(this);
3755 } else {
3756 return BAD_VALUE;
3757 }
3758}
3759
3760void AudioFlinger::RecordThread::RecordTrack::stop()
3761{
3762 sp<ThreadBase> thread = mThread.promote();
3763 if (thread != 0) {
3764 RecordThread *recordThread = (RecordThread *)thread.get();
3765 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003766 TrackBase::reset();
3767 // Force overerrun condition to avoid false overrun callback until first data is
3768 // read from buffer
3769 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770 }
3771}
3772
3773void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3774{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003775 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 (mClient == NULL) ? getpid() : mClient->pid(),
3777 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003778 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779 mSessionId,
3780 mFrameCount,
3781 mState,
3782 mCblk->sampleRate,
3783 mCblk->server,
3784 mCblk->user);
3785}
3786
3787
3788// ----------------------------------------------------------------------------
3789
3790AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3791 const wp<ThreadBase>& thread,
3792 DuplicatingThread *sourceThread,
3793 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003794 uint32_t format,
3795 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003796 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003797 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003798 mActive(false), mSourceThread(sourceThread)
3799{
3800
3801 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3802 if (mCblk != NULL) {
3803 mCblk->flags |= CBLK_DIRECTION_OUT;
3804 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3805 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3806 mOutBuffer.frameCount = 0;
3807 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003808 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003809 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3810 mCblk, mBuffer, mCblk->buffers,
3811 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003813 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 }
3815}
3816
3817AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3818{
3819 clearBufferQueue();
3820}
3821
3822status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3823{
3824 status_t status = Track::start();
3825 if (status != NO_ERROR) {
3826 return status;
3827 }
3828
3829 mActive = true;
3830 mRetryCount = 127;
3831 return status;
3832}
3833
3834void AudioFlinger::PlaybackThread::OutputTrack::stop()
3835{
3836 Track::stop();
3837 clearBufferQueue();
3838 mOutBuffer.frameCount = 0;
3839 mActive = false;
3840}
3841
3842bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3843{
3844 Buffer *pInBuffer;
3845 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003846 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847 bool outputBufferFull = false;
3848 inBuffer.frameCount = frames;
3849 inBuffer.i16 = data;
3850
3851 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3852
3853 if (!mActive && frames != 0) {
3854 start();
3855 sp<ThreadBase> thread = mThread.promote();
3856 if (thread != 0) {
3857 MixerThread *mixerThread = (MixerThread *)thread.get();
3858 if (mCblk->frameCount > frames){
3859 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3860 uint32_t startFrames = (mCblk->frameCount - frames);
3861 pInBuffer = new Buffer;
3862 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3863 pInBuffer->frameCount = startFrames;
3864 pInBuffer->i16 = pInBuffer->mBuffer;
3865 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3866 mBufferQueue.add(pInBuffer);
3867 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003868 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 }
3870 }
3871 }
3872 }
3873
3874 while (waitTimeLeftMs) {
3875 // First write pending buffers, then new data
3876 if (mBufferQueue.size()) {
3877 pInBuffer = mBufferQueue.itemAt(0);
3878 } else {
3879 pInBuffer = &inBuffer;
3880 }
3881
3882 if (pInBuffer->frameCount == 0) {
3883 break;
3884 }
3885
3886 if (mOutBuffer.frameCount == 0) {
3887 mOutBuffer.frameCount = pInBuffer->frameCount;
3888 nsecs_t startTime = systemTime();
3889 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003890 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003891 outputBufferFull = true;
3892 break;
3893 }
3894 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3895 if (waitTimeLeftMs >= waitTimeMs) {
3896 waitTimeLeftMs -= waitTimeMs;
3897 } else {
3898 waitTimeLeftMs = 0;
3899 }
3900 }
3901
3902 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3903 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3904 mCblk->stepUser(outFrames);
3905 pInBuffer->frameCount -= outFrames;
3906 pInBuffer->i16 += outFrames * channelCount;
3907 mOutBuffer.frameCount -= outFrames;
3908 mOutBuffer.i16 += outFrames * channelCount;
3909
3910 if (pInBuffer->frameCount == 0) {
3911 if (mBufferQueue.size()) {
3912 mBufferQueue.removeAt(0);
3913 delete [] pInBuffer->mBuffer;
3914 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003915 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916 } else {
3917 break;
3918 }
3919 }
3920 }
3921
3922 // If we could not write all frames, allocate a buffer and queue it for next time.
3923 if (inBuffer.frameCount) {
3924 sp<ThreadBase> thread = mThread.promote();
3925 if (thread != 0 && !thread->standby()) {
3926 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3927 pInBuffer = new Buffer;
3928 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3929 pInBuffer->frameCount = inBuffer.frameCount;
3930 pInBuffer->i16 = pInBuffer->mBuffer;
3931 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3932 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003933 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003935 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936 }
3937 }
3938 }
3939
3940 // Calling write() with a 0 length buffer, means that no more data will be written:
3941 // If no more buffers are pending, fill output track buffer to make sure it is started
3942 // by output mixer.
3943 if (frames == 0 && mBufferQueue.size() == 0) {
3944 if (mCblk->user < mCblk->frameCount) {
3945 frames = mCblk->frameCount - mCblk->user;
3946 pInBuffer = new Buffer;
3947 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3948 pInBuffer->frameCount = frames;
3949 pInBuffer->i16 = pInBuffer->mBuffer;
3950 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3951 mBufferQueue.add(pInBuffer);
3952 } else if (mActive) {
3953 stop();
3954 }
3955 }
3956
3957 return outputBufferFull;
3958}
3959
3960status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3961{
3962 int active;
3963 status_t result;
3964 audio_track_cblk_t* cblk = mCblk;
3965 uint32_t framesReq = buffer->frameCount;
3966
Steve Block3856b092011-10-20 11:56:00 +01003967// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968 buffer->frameCount = 0;
3969
3970 uint32_t framesAvail = cblk->framesAvailable();
3971
3972
3973 if (framesAvail == 0) {
3974 Mutex::Autolock _l(cblk->lock);
3975 goto start_loop_here;
3976 while (framesAvail == 0) {
3977 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003978 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003979 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003980 return AudioTrack::NO_MORE_BUFFERS;
3981 }
3982 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3983 if (result != NO_ERROR) {
3984 return AudioTrack::NO_MORE_BUFFERS;
3985 }
3986 // read the server count again
3987 start_loop_here:
3988 framesAvail = cblk->framesAvailable_l();
3989 }
3990 }
3991
3992// if (framesAvail < framesReq) {
3993// return AudioTrack::NO_MORE_BUFFERS;
3994// }
3995
3996 if (framesReq > framesAvail) {
3997 framesReq = framesAvail;
3998 }
3999
4000 uint32_t u = cblk->user;
4001 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4002
4003 if (u + framesReq > bufferEnd) {
4004 framesReq = bufferEnd - u;
4005 }
4006
4007 buffer->frameCount = framesReq;
4008 buffer->raw = (void *)cblk->buffer(u);
4009 return NO_ERROR;
4010}
4011
4012
4013void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4014{
4015 size_t size = mBufferQueue.size();
4016 Buffer *pBuffer;
4017
4018 for (size_t i = 0; i < size; i++) {
4019 pBuffer = mBufferQueue.itemAt(i);
4020 delete [] pBuffer->mBuffer;
4021 delete pBuffer;
4022 }
4023 mBufferQueue.clear();
4024}
4025
4026// ----------------------------------------------------------------------------
4027
4028AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4029 : RefBase(),
4030 mAudioFlinger(audioFlinger),
4031 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4032 mPid(pid)
4033{
4034 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4035}
4036
4037// Client destructor must be called with AudioFlinger::mLock held
4038AudioFlinger::Client::~Client()
4039{
4040 mAudioFlinger->removeClient_l(mPid);
4041}
4042
4043const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4044{
4045 return mMemoryDealer;
4046}
4047
4048// ----------------------------------------------------------------------------
4049
4050AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4051 const sp<IAudioFlingerClient>& client,
4052 pid_t pid)
4053 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4054{
4055}
4056
4057AudioFlinger::NotificationClient::~NotificationClient()
4058{
4059 mClient.clear();
4060}
4061
4062void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4063{
4064 sp<NotificationClient> keep(this);
4065 {
4066 mAudioFlinger->removeNotificationClient(mPid);
4067 }
4068}
4069
4070// ----------------------------------------------------------------------------
4071
4072AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4073 : BnAudioTrack(),
4074 mTrack(track)
4075{
4076}
4077
4078AudioFlinger::TrackHandle::~TrackHandle() {
4079 // just stop the track on deletion, associated resources
4080 // will be freed from the main thread once all pending buffers have
4081 // been played. Unless it's not in the active track list, in which
4082 // case we free everything now...
4083 mTrack->destroy();
4084}
4085
4086status_t AudioFlinger::TrackHandle::start() {
4087 return mTrack->start();
4088}
4089
4090void AudioFlinger::TrackHandle::stop() {
4091 mTrack->stop();
4092}
4093
4094void AudioFlinger::TrackHandle::flush() {
4095 mTrack->flush();
4096}
4097
4098void AudioFlinger::TrackHandle::mute(bool e) {
4099 mTrack->mute(e);
4100}
4101
4102void AudioFlinger::TrackHandle::pause() {
4103 mTrack->pause();
4104}
4105
4106void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4107 mTrack->setVolume(left, right);
4108}
4109
4110sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4111 return mTrack->getCblk();
4112}
4113
4114status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4115{
4116 return mTrack->attachAuxEffect(EffectId);
4117}
4118
4119status_t AudioFlinger::TrackHandle::onTransact(
4120 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4121{
4122 return BnAudioTrack::onTransact(code, data, reply, flags);
4123}
4124
4125// ----------------------------------------------------------------------------
4126
4127sp<IAudioRecord> AudioFlinger::openRecord(
4128 pid_t pid,
4129 int input,
4130 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004131 uint32_t format,
4132 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133 int frameCount,
4134 uint32_t flags,
4135 int *sessionId,
4136 status_t *status)
4137{
4138 sp<RecordThread::RecordTrack> recordTrack;
4139 sp<RecordHandle> recordHandle;
4140 sp<Client> client;
4141 wp<Client> wclient;
4142 status_t lStatus;
4143 RecordThread *thread;
4144 size_t inFrameCount;
4145 int lSessionId;
4146
4147 // check calling permissions
4148 if (!recordingAllowed()) {
4149 lStatus = PERMISSION_DENIED;
4150 goto Exit;
4151 }
4152
4153 // add client to list
4154 { // scope for mLock
4155 Mutex::Autolock _l(mLock);
4156 thread = checkRecordThread_l(input);
4157 if (thread == NULL) {
4158 lStatus = BAD_VALUE;
4159 goto Exit;
4160 }
4161
4162 wclient = mClients.valueFor(pid);
4163 if (wclient != NULL) {
4164 client = wclient.promote();
4165 } else {
4166 client = new Client(this, pid);
4167 mClients.add(pid, client);
4168 }
4169
4170 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004171 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 lSessionId = *sessionId;
4173 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004174 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 if (sessionId != NULL) {
4176 *sessionId = lSessionId;
4177 }
4178 }
4179 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004180 recordTrack = thread->createRecordTrack_l(client,
4181 sampleRate,
4182 format,
4183 channelMask,
4184 frameCount,
4185 flags,
4186 lSessionId,
4187 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004189 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4191 // destructor is called by the TrackBase destructor with mLock held
4192 client.clear();
4193 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 goto Exit;
4195 }
4196
4197 // return to handle to client
4198 recordHandle = new RecordHandle(recordTrack);
4199 lStatus = NO_ERROR;
4200
4201Exit:
4202 if (status) {
4203 *status = lStatus;
4204 }
4205 return recordHandle;
4206}
4207
4208// ----------------------------------------------------------------------------
4209
4210AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4211 : BnAudioRecord(),
4212 mRecordTrack(recordTrack)
4213{
4214}
4215
4216AudioFlinger::RecordHandle::~RecordHandle() {
4217 stop();
4218}
4219
4220status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004221 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004222 return mRecordTrack->start();
4223}
4224
4225void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004226 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 mRecordTrack->stop();
4228}
4229
4230sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4231 return mRecordTrack->getCblk();
4232}
4233
4234status_t AudioFlinger::RecordHandle::onTransact(
4235 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4236{
4237 return BnAudioRecord::onTransact(code, data, reply, flags);
4238}
4239
4240// ----------------------------------------------------------------------------
4241
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004242AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4243 AudioStreamIn *input,
4244 uint32_t sampleRate,
4245 uint32_t channels,
4246 int id,
4247 uint32_t device) :
4248 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004249 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004250{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004251 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004252
4253 snprintf(mName, kNameLength, "AudioIn_%d", id);
4254
Dima Zavinfce7a472011-04-19 22:30:36 -07004255 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 mReqSampleRate = sampleRate;
4257 readInputParameters();
4258}
4259
4260
4261AudioFlinger::RecordThread::~RecordThread()
4262{
4263 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004264 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 delete mResampler;
4266 delete[] mRsmpOutBuffer;
4267 }
4268}
4269
4270void AudioFlinger::RecordThread::onFirstRef()
4271{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004272 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273}
4274
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004275status_t AudioFlinger::RecordThread::readyToRun()
4276{
4277 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004278 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004279 return status;
4280}
4281
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282bool AudioFlinger::RecordThread::threadLoop()
4283{
4284 AudioBufferProvider::Buffer buffer;
4285 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004286 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287
Eric Laurent44d98482010-09-30 16:12:31 -07004288 nsecs_t lastWarning = 0;
4289
Eric Laurentfeb0db62011-07-22 09:04:31 -07004290 acquireWakeLock();
4291
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 // start recording
4293 while (!exitPending()) {
4294
4295 processConfigEvents();
4296
4297 { // scope for mLock
4298 Mutex::Autolock _l(mLock);
4299 checkForNewParameters_l();
4300 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4301 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004302 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004303 mStandby = true;
4304 }
4305
4306 if (exitPending()) break;
4307
Eric Laurentfeb0db62011-07-22 09:04:31 -07004308 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004309 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 // go to sleep
4311 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004312 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004313 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 continue;
4315 }
4316 if (mActiveTrack != 0) {
4317 if (mActiveTrack->mState == TrackBase::PAUSING) {
4318 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004319 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 mStandby = true;
4321 }
4322 mActiveTrack.clear();
4323 mStartStopCond.broadcast();
4324 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4325 if (mReqChannelCount != mActiveTrack->channelCount()) {
4326 mActiveTrack.clear();
4327 mStartStopCond.broadcast();
4328 } else if (mBytesRead != 0) {
4329 // record start succeeds only if first read from audio input
4330 // succeeds
4331 if (mBytesRead > 0) {
4332 mActiveTrack->mState = TrackBase::ACTIVE;
4333 } else {
4334 mActiveTrack.clear();
4335 }
4336 mStartStopCond.broadcast();
4337 }
4338 mStandby = false;
4339 }
4340 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004341 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 }
4343
4344 if (mActiveTrack != 0) {
4345 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4346 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004347 unlockEffectChains(effectChains);
4348 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 continue;
4350 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004351 for (size_t i = 0; i < effectChains.size(); i ++) {
4352 effectChains[i]->process_l();
4353 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004354
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004356 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004357 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004358 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004359 // no resampling
4360 while (framesOut) {
4361 size_t framesIn = mFrameCount - mRsmpInIndex;
4362 if (framesIn) {
4363 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4364 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4365 if (framesIn > framesOut)
4366 framesIn = framesOut;
4367 mRsmpInIndex += framesIn;
4368 framesOut -= framesIn;
4369 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004370 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 memcpy(dst, src, framesIn * mFrameSize);
4372 } else {
4373 int16_t *src16 = (int16_t *)src;
4374 int16_t *dst16 = (int16_t *)dst;
4375 if (mChannelCount == 1) {
4376 while (framesIn--) {
4377 *dst16++ = *src16;
4378 *dst16++ = *src16++;
4379 }
4380 } else {
4381 while (framesIn--) {
4382 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4383 src16 += 2;
4384 }
4385 }
4386 }
4387 }
4388 if (framesOut && mFrameCount == mRsmpInIndex) {
4389 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004390 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004391 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004392 framesOut = 0;
4393 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004394 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004395 mRsmpInIndex = 0;
4396 }
4397 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004398 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004399 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4400 // Force input into standby so that it tries to
4401 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004402 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004403 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004404 }
4405 mRsmpInIndex = mFrameCount;
4406 framesOut = 0;
4407 buffer.frameCount = 0;
4408 }
4409 }
4410 }
4411 } else {
4412 // resampling
4413
4414 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4415 // alter output frame count as if we were expecting stereo samples
4416 if (mChannelCount == 1 && mReqChannelCount == 1) {
4417 framesOut >>= 1;
4418 }
4419 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4420 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4421 // are 32 bit aligned which should be always true.
4422 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004423 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 // the resampler always outputs stereo samples: do post stereo to mono conversion
4425 int16_t *src = (int16_t *)mRsmpOutBuffer;
4426 int16_t *dst = buffer.i16;
4427 while (framesOut--) {
4428 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4429 src += 2;
4430 }
4431 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004432 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 }
4434
4435 }
4436 mActiveTrack->releaseBuffer(&buffer);
4437 mActiveTrack->overflow();
4438 }
4439 // client isn't retrieving buffers fast enough
4440 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004441 if (!mActiveTrack->setOverflow()) {
4442 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004443 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004444 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004445 lastWarning = now;
4446 }
4447 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 // Release the processor for a while before asking for a new buffer.
4449 // This will give the application more chance to read from the buffer and
4450 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004451 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452 }
4453 }
Eric Laurentec437d82011-07-26 20:54:46 -07004454 // enable changes in effect chain
4455 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004456 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004457 }
4458
4459 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004460 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461 }
4462 mActiveTrack.clear();
4463
4464 mStartStopCond.broadcast();
4465
Eric Laurentfeb0db62011-07-22 09:04:31 -07004466 releaseWakeLock();
4467
Steve Block3856b092011-10-20 11:56:00 +01004468 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004469 return false;
4470}
4471
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004472
4473sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4474 const sp<AudioFlinger::Client>& client,
4475 uint32_t sampleRate,
4476 int format,
4477 int channelMask,
4478 int frameCount,
4479 uint32_t flags,
4480 int sessionId,
4481 status_t *status)
4482{
4483 sp<RecordTrack> track;
4484 status_t lStatus;
4485
4486 lStatus = initCheck();
4487 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004488 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004489 goto Exit;
4490 }
4491
4492 { // scope for mLock
4493 Mutex::Autolock _l(mLock);
4494
4495 track = new RecordTrack(this, client, sampleRate,
4496 format, channelMask, frameCount, flags, sessionId);
4497
4498 if (track->getCblk() == NULL) {
4499 lStatus = NO_MEMORY;
4500 goto Exit;
4501 }
4502
4503 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004504 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4505 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004506 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004507 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4508 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004509 }
4510 lStatus = NO_ERROR;
4511
4512Exit:
4513 if (status) {
4514 *status = lStatus;
4515 }
4516 return track;
4517}
4518
Mathias Agopian65ab4712010-07-14 17:59:35 -07004519status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4520{
Steve Block3856b092011-10-20 11:56:00 +01004521 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 sp <ThreadBase> strongMe = this;
4523 status_t status = NO_ERROR;
4524 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004525 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 if (mActiveTrack != 0) {
4527 if (recordTrack != mActiveTrack.get()) {
4528 status = -EBUSY;
4529 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4530 mActiveTrack->mState = TrackBase::ACTIVE;
4531 }
4532 return status;
4533 }
4534
4535 recordTrack->mState = TrackBase::IDLE;
4536 mActiveTrack = recordTrack;
4537 mLock.unlock();
4538 status_t status = AudioSystem::startInput(mId);
4539 mLock.lock();
4540 if (status != NO_ERROR) {
4541 mActiveTrack.clear();
4542 return status;
4543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 mRsmpInIndex = mFrameCount;
4545 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004546 if (mResampler != NULL) {
4547 mResampler->reset();
4548 }
4549 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004551 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004552 mWaitWorkCV.signal();
4553 // do not wait for mStartStopCond if exiting
4554 if (mExiting) {
4555 mActiveTrack.clear();
4556 status = INVALID_OPERATION;
4557 goto startError;
4558 }
4559 mStartStopCond.wait(mLock);
4560 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004561 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004562 status = BAD_VALUE;
4563 goto startError;
4564 }
Steve Block3856b092011-10-20 11:56:00 +01004565 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566 return status;
4567 }
4568startError:
4569 AudioSystem::stopInput(mId);
4570 return status;
4571}
4572
4573void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004574 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575 sp <ThreadBase> strongMe = this;
4576 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004577 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4579 mActiveTrack->mState = TrackBase::PAUSING;
4580 // do not wait for mStartStopCond if exiting
4581 if (mExiting) {
4582 return;
4583 }
4584 mStartStopCond.wait(mLock);
4585 // if we have been restarted, recordTrack == mActiveTrack.get() here
4586 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4587 mLock.unlock();
4588 AudioSystem::stopInput(mId);
4589 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004590 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004591 }
4592 }
4593 }
4594}
4595
4596status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4597{
4598 const size_t SIZE = 256;
4599 char buffer[SIZE];
4600 String8 result;
4601 pid_t pid = 0;
4602
4603 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4604 result.append(buffer);
4605
4606 if (mActiveTrack != 0) {
4607 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004608 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609 mActiveTrack->dump(buffer, SIZE);
4610 result.append(buffer);
4611
4612 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4613 result.append(buffer);
4614 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4615 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004616 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617 result.append(buffer);
4618 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4619 result.append(buffer);
4620 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4621 result.append(buffer);
4622
4623
4624 } else {
4625 result.append("No record client\n");
4626 }
4627 write(fd, result.string(), result.size());
4628
4629 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004630 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631
4632 return NO_ERROR;
4633}
4634
4635status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4636{
4637 size_t framesReq = buffer->frameCount;
4638 size_t framesReady = mFrameCount - mRsmpInIndex;
4639 int channelCount;
4640
4641 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004642 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004643 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004644 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4646 // Force input into standby so that it tries to
4647 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004648 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004649 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004650 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004651 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652 buffer->frameCount = 0;
4653 return NOT_ENOUGH_DATA;
4654 }
4655 mRsmpInIndex = 0;
4656 framesReady = mFrameCount;
4657 }
4658
4659 if (framesReq > framesReady) {
4660 framesReq = framesReady;
4661 }
4662
4663 if (mChannelCount == 1 && mReqChannelCount == 2) {
4664 channelCount = 1;
4665 } else {
4666 channelCount = 2;
4667 }
4668 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4669 buffer->frameCount = framesReq;
4670 return NO_ERROR;
4671}
4672
4673void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4674{
4675 mRsmpInIndex += buffer->frameCount;
4676 buffer->frameCount = 0;
4677}
4678
4679bool AudioFlinger::RecordThread::checkForNewParameters_l()
4680{
4681 bool reconfig = false;
4682
4683 while (!mNewParameters.isEmpty()) {
4684 status_t status = NO_ERROR;
4685 String8 keyValuePair = mNewParameters[0];
4686 AudioParameter param = AudioParameter(keyValuePair);
4687 int value;
4688 int reqFormat = mFormat;
4689 int reqSamplingRate = mReqSampleRate;
4690 int reqChannelCount = mReqChannelCount;
4691
4692 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4693 reqSamplingRate = value;
4694 reconfig = true;
4695 }
4696 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4697 reqFormat = value;
4698 reconfig = true;
4699 }
4700 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004701 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702 reconfig = true;
4703 }
4704 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4705 // do not accept frame count changes if tracks are open as the track buffer
4706 // size depends on frame count and correct behavior would not be garantied
4707 // if frame count is changed after track creation
4708 if (mActiveTrack != 0) {
4709 status = INVALID_OPERATION;
4710 } else {
4711 reconfig = true;
4712 }
4713 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004714 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4715 // forward device change to effects that have requested to be
4716 // aware of attached audio device.
4717 for (size_t i = 0; i < mEffectChains.size(); i++) {
4718 mEffectChains[i]->setDevice_l(value);
4719 }
4720 // store input device and output device but do not forward output device to audio HAL.
4721 // Note that status is ignored by the caller for output device
4722 // (see AudioFlinger::setParameters()
4723 if (value & AUDIO_DEVICE_OUT_ALL) {
4724 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4725 status = BAD_VALUE;
4726 } else {
4727 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004728 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4729 if (mTrack != NULL) {
4730 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004731 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004732 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4733 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4734 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004735 }
4736 mDevice |= (uint32_t)value;
4737 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004738 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004739 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004741 mInput->stream->common.standby(&mInput->stream->common);
4742 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743 }
4744 if (reconfig) {
4745 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004746 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004747 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004748 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4749 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004750 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004751 status = NO_ERROR;
4752 }
4753 if (status == NO_ERROR) {
4754 readInputParameters();
4755 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4756 }
4757 }
4758 }
4759
4760 mNewParameters.removeAt(0);
4761
4762 mParamStatus = status;
4763 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004764 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4765 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004766 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767 }
4768 return reconfig;
4769}
4770
4771String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4772{
Dima Zavinfce7a472011-04-19 22:30:36 -07004773 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004774 String8 out_s8 = String8();
4775
4776 Mutex::Autolock _l(mLock);
4777 if (initCheck() != NO_ERROR) {
4778 return out_s8;
4779 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004780
Dima Zavin799a70e2011-04-18 16:57:27 -07004781 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004782 out_s8 = String8(s);
4783 free(s);
4784 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004785}
4786
4787void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4788 AudioSystem::OutputDescriptor desc;
4789 void *param2 = 0;
4790
4791 switch (event) {
4792 case AudioSystem::INPUT_OPENED:
4793 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004794 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004795 desc.samplingRate = mSampleRate;
4796 desc.format = mFormat;
4797 desc.frameCount = mFrameCount;
4798 desc.latency = 0;
4799 param2 = &desc;
4800 break;
4801
4802 case AudioSystem::INPUT_CLOSED:
4803 default:
4804 break;
4805 }
4806 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4807}
4808
4809void AudioFlinger::RecordThread::readInputParameters()
4810{
4811 if (mRsmpInBuffer) delete mRsmpInBuffer;
4812 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4813 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004814 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815
Dima Zavin799a70e2011-04-18 16:57:27 -07004816 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004817 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4818 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004819 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004820 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004821 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822 mFrameCount = mInputBytes / mFrameSize;
4823 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4824
4825 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4826 {
4827 int channelCount;
4828 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4829 // stereo to mono post process as the resampler always outputs stereo.
4830 if (mChannelCount == 1 && mReqChannelCount == 2) {
4831 channelCount = 1;
4832 } else {
4833 channelCount = 2;
4834 }
4835 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4836 mResampler->setSampleRate(mSampleRate);
4837 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4838 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4839
4840 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4841 if (mChannelCount == 1 && mReqChannelCount == 1) {
4842 mFrameCount >>= 1;
4843 }
4844
4845 }
4846 mRsmpInIndex = mFrameCount;
4847}
4848
4849unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4850{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004851 Mutex::Autolock _l(mLock);
4852 if (initCheck() != NO_ERROR) {
4853 return 0;
4854 }
4855
Dima Zavin799a70e2011-04-18 16:57:27 -07004856 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857}
4858
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004859uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4860{
4861 Mutex::Autolock _l(mLock);
4862 uint32_t result = 0;
4863 if (getEffectChain_l(sessionId) != 0) {
4864 result = EFFECT_SESSION;
4865 }
4866
4867 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4868 result |= TRACK_SESSION;
4869 }
4870
4871 return result;
4872}
4873
Eric Laurent59bd0da2011-08-01 09:52:20 -07004874AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4875{
4876 Mutex::Autolock _l(mLock);
4877 return mTrack;
4878}
4879
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004880AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4881{
4882 Mutex::Autolock _l(mLock);
4883 return mInput;
4884}
4885
4886AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4887{
4888 Mutex::Autolock _l(mLock);
4889 AudioStreamIn *input = mInput;
4890 mInput = NULL;
4891 return input;
4892}
4893
4894// this method must always be called either with ThreadBase mLock held or inside the thread loop
4895audio_stream_t* AudioFlinger::RecordThread::stream()
4896{
4897 if (mInput == NULL) {
4898 return NULL;
4899 }
4900 return &mInput->stream->common;
4901}
4902
4903
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904// ----------------------------------------------------------------------------
4905
4906int AudioFlinger::openOutput(uint32_t *pDevices,
4907 uint32_t *pSamplingRate,
4908 uint32_t *pFormat,
4909 uint32_t *pChannels,
4910 uint32_t *pLatencyMs,
4911 uint32_t flags)
4912{
4913 status_t status;
4914 PlaybackThread *thread = NULL;
4915 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4916 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4917 uint32_t format = pFormat ? *pFormat : 0;
4918 uint32_t channels = pChannels ? *pChannels : 0;
4919 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004920 audio_stream_out_t *outStream;
4921 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922
Steve Block3856b092011-10-20 11:56:00 +01004923 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924 pDevices ? *pDevices : 0,
4925 samplingRate,
4926 format,
4927 channels,
4928 flags);
4929
4930 if (pDevices == NULL || *pDevices == 0) {
4931 return 0;
4932 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004933
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 Mutex::Autolock _l(mLock);
4935
Dima Zavin799a70e2011-04-18 16:57:27 -07004936 outHwDev = findSuitableHwDev_l(*pDevices);
4937 if (outHwDev == NULL)
4938 return 0;
4939
4940 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4941 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004942 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004943 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004944 samplingRate,
4945 format,
4946 channels,
4947 status);
4948
4949 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004950 if (outStream != NULL) {
4951 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004952 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004953
Dima Zavinfce7a472011-04-19 22:30:36 -07004954 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4955 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4956 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004957 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004958 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 } else {
4960 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004961 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004962 }
4963 mPlaybackThreads.add(id, thread);
4964
4965 if (pSamplingRate) *pSamplingRate = samplingRate;
4966 if (pFormat) *pFormat = format;
4967 if (pChannels) *pChannels = channels;
4968 if (pLatencyMs) *pLatencyMs = thread->latency();
4969
4970 // notify client processes of the new output creation
4971 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4972 return id;
4973 }
4974
4975 return 0;
4976}
4977
4978int AudioFlinger::openDuplicateOutput(int output1, int output2)
4979{
4980 Mutex::Autolock _l(mLock);
4981 MixerThread *thread1 = checkMixerThread_l(output1);
4982 MixerThread *thread2 = checkMixerThread_l(output2);
4983
4984 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004985 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 return 0;
4987 }
4988
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004989 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004990 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4991 thread->addOutputTrack(thread2);
4992 mPlaybackThreads.add(id, thread);
4993 // notify client processes of the new output creation
4994 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4995 return id;
4996}
4997
4998status_t AudioFlinger::closeOutput(int output)
4999{
5000 // keep strong reference on the playback thread so that
5001 // it is not destroyed while exit() is executed
5002 sp <PlaybackThread> thread;
5003 {
5004 Mutex::Autolock _l(mLock);
5005 thread = checkPlaybackThread_l(output);
5006 if (thread == NULL) {
5007 return BAD_VALUE;
5008 }
5009
Steve Block3856b092011-10-20 11:56:00 +01005010 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005012 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005014 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5016 dupThread->removeOutputTrack((MixerThread *)thread.get());
5017 }
5018 }
5019 }
5020 void *param2 = 0;
5021 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5022 mPlaybackThreads.removeItem(output);
5023 }
5024 thread->exit();
5025
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005026 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005027 AudioStreamOut *out = thread->clearOutput();
5028 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005029 out->hwDev->close_output_stream(out->hwDev, out->stream);
5030 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 }
5032 return NO_ERROR;
5033}
5034
5035status_t AudioFlinger::suspendOutput(int output)
5036{
5037 Mutex::Autolock _l(mLock);
5038 PlaybackThread *thread = checkPlaybackThread_l(output);
5039
5040 if (thread == NULL) {
5041 return BAD_VALUE;
5042 }
5043
Steve Block3856b092011-10-20 11:56:00 +01005044 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005045 thread->suspend();
5046
5047 return NO_ERROR;
5048}
5049
5050status_t AudioFlinger::restoreOutput(int output)
5051{
5052 Mutex::Autolock _l(mLock);
5053 PlaybackThread *thread = checkPlaybackThread_l(output);
5054
5055 if (thread == NULL) {
5056 return BAD_VALUE;
5057 }
5058
Steve Block3856b092011-10-20 11:56:00 +01005059 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005060
5061 thread->restore();
5062
5063 return NO_ERROR;
5064}
5065
5066int AudioFlinger::openInput(uint32_t *pDevices,
5067 uint32_t *pSamplingRate,
5068 uint32_t *pFormat,
5069 uint32_t *pChannels,
5070 uint32_t acoustics)
5071{
5072 status_t status;
5073 RecordThread *thread = NULL;
5074 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5075 uint32_t format = pFormat ? *pFormat : 0;
5076 uint32_t channels = pChannels ? *pChannels : 0;
5077 uint32_t reqSamplingRate = samplingRate;
5078 uint32_t reqFormat = format;
5079 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005080 audio_stream_in_t *inStream;
5081 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082
5083 if (pDevices == NULL || *pDevices == 0) {
5084 return 0;
5085 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005086
Mathias Agopian65ab4712010-07-14 17:59:35 -07005087 Mutex::Autolock _l(mLock);
5088
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 inHwDev = findSuitableHwDev_l(*pDevices);
5090 if (inHwDev == NULL)
5091 return 0;
5092
5093 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5094 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005095 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005096 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005097 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005098 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005099 samplingRate,
5100 format,
5101 channels,
5102 acoustics,
5103 status);
5104
5105 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5106 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5107 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005108 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005109 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005111 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005112 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005113 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5114 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005115 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005116 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 }
5118
Dima Zavin799a70e2011-04-18 16:57:27 -07005119 if (inStream != NULL) {
5120 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5121
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005122 int id = nextUniqueId();
5123 // Start record thread
5124 // RecorThread require both input and output device indication to forward to audio
5125 // pre processing modules
5126 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5127 thread = new RecordThread(this,
5128 input,
5129 reqSamplingRate,
5130 reqChannels,
5131 id,
5132 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005133 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005134 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005135 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5136 if (pFormat) *pFormat = format;
5137 if (pChannels) *pChannels = reqChannels;
5138
Dima Zavin799a70e2011-04-18 16:57:27 -07005139 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005140
5141 // notify client processes of the new input creation
5142 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5143 return id;
5144 }
5145
5146 return 0;
5147}
5148
5149status_t AudioFlinger::closeInput(int input)
5150{
5151 // keep strong reference on the record thread so that
5152 // it is not destroyed while exit() is executed
5153 sp <RecordThread> thread;
5154 {
5155 Mutex::Autolock _l(mLock);
5156 thread = checkRecordThread_l(input);
5157 if (thread == NULL) {
5158 return BAD_VALUE;
5159 }
5160
Steve Block3856b092011-10-20 11:56:00 +01005161 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 void *param2 = 0;
5163 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5164 mRecordThreads.removeItem(input);
5165 }
5166 thread->exit();
5167
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005168 AudioStreamIn *in = thread->clearInput();
5169 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005170 in->hwDev->close_input_stream(in->hwDev, in->stream);
5171 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172
5173 return NO_ERROR;
5174}
5175
Glenn Kastenfff6d712012-01-12 16:38:12 -08005176status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177{
5178 Mutex::Autolock _l(mLock);
5179 MixerThread *dstThread = checkMixerThread_l(output);
5180 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005181 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 return BAD_VALUE;
5183 }
5184
Steve Block3856b092011-10-20 11:56:00 +01005185 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5187
Eric Laurent9f6530f2011-08-30 10:18:54 -07005188 dstThread->setStreamValid(stream, true);
5189
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5191 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5192 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005193 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005194 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005195 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005197 }
Eric Laurentde070132010-07-13 04:45:46 -07005198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199
5200 return NO_ERROR;
5201}
5202
5203
5204int AudioFlinger::newAudioSessionId()
5205{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005206 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005207}
5208
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005209void AudioFlinger::acquireAudioSessionId(int audioSession)
5210{
5211 Mutex::Autolock _l(mLock);
5212 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005213 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005214 int num = mAudioSessionRefs.size();
5215 for (int i = 0; i< num; i++) {
5216 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5217 if (ref->sessionid == audioSession && ref->pid == caller) {
5218 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005219 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005220 return;
5221 }
5222 }
5223 AudioSessionRef *ref = new AudioSessionRef();
5224 ref->sessionid = audioSession;
5225 ref->pid = caller;
5226 ref->cnt = 1;
5227 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005228 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005229}
5230
5231void AudioFlinger::releaseAudioSessionId(int audioSession)
5232{
5233 Mutex::Autolock _l(mLock);
5234 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005235 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005236 int num = mAudioSessionRefs.size();
5237 for (int i = 0; i< num; i++) {
5238 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5239 if (ref->sessionid == audioSession && ref->pid == caller) {
5240 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005241 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005242 if (ref->cnt == 0) {
5243 mAudioSessionRefs.removeAt(i);
5244 delete ref;
5245 purgeStaleEffects_l();
5246 }
5247 return;
5248 }
5249 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005250 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005251}
5252
5253void AudioFlinger::purgeStaleEffects_l() {
5254
Steve Block3856b092011-10-20 11:56:00 +01005255 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005256
5257 Vector< sp<EffectChain> > chains;
5258
5259 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5260 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5261 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5262 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005263 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5264 chains.push(ec);
5265 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005266 }
5267 }
5268 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5269 sp<RecordThread> t = mRecordThreads.valueAt(i);
5270 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5271 sp<EffectChain> ec = t->mEffectChains[j];
5272 chains.push(ec);
5273 }
5274 }
5275
5276 for (size_t i = 0; i < chains.size(); i++) {
5277 sp<EffectChain> ec = chains[i];
5278 int sessionid = ec->sessionId();
5279 sp<ThreadBase> t = ec->mThread.promote();
5280 if (t == 0) {
5281 continue;
5282 }
5283 size_t numsessionrefs = mAudioSessionRefs.size();
5284 bool found = false;
5285 for (size_t k = 0; k < numsessionrefs; k++) {
5286 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5287 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005288 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005289 sessionid, ref->pid, ref->cnt);
5290 found = true;
5291 break;
5292 }
5293 }
5294 if (!found) {
5295 // remove all effects from the chain
5296 while (ec->mEffects.size()) {
5297 sp<EffectModule> effect = ec->mEffects[0];
5298 effect->unPin();
5299 Mutex::Autolock _l (t->mLock);
5300 t->removeEffect_l(effect);
5301 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5302 sp<EffectHandle> handle = effect->mHandles[j].promote();
5303 if (handle != 0) {
5304 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005305 if (handle->mHasControl && handle->mEnabled) {
5306 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5307 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005308 }
5309 }
5310 AudioSystem::unregisterEffect(effect->id());
5311 }
5312 }
5313 }
5314 return;
5315}
5316
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5318AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5319{
5320 PlaybackThread *thread = NULL;
5321 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5322 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5323 }
5324 return thread;
5325}
5326
5327// checkMixerThread_l() must be called with AudioFlinger::mLock held
5328AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5329{
5330 PlaybackThread *thread = checkPlaybackThread_l(output);
5331 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005332 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 thread = NULL;
5334 }
5335 }
5336 return (MixerThread *)thread;
5337}
5338
5339// checkRecordThread_l() must be called with AudioFlinger::mLock held
5340AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5341{
5342 RecordThread *thread = NULL;
5343 if (mRecordThreads.indexOfKey(input) >= 0) {
5344 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5345 }
5346 return thread;
5347}
5348
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005349uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005350{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005351 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005352}
5353
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005354AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5355{
5356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5357 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005358 AudioStreamOut *output = thread->getOutput();
5359 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005360 return thread;
5361 }
5362 }
5363 return NULL;
5364}
5365
5366uint32_t AudioFlinger::primaryOutputDevice_l()
5367{
5368 PlaybackThread *thread = primaryPlaybackThread_l();
5369
5370 if (thread == NULL) {
5371 return 0;
5372 }
5373
5374 return thread->device();
5375}
5376
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378// ----------------------------------------------------------------------------
5379// Effect management
5380// ----------------------------------------------------------------------------
5381
5382
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5384{
5385 Mutex::Autolock _l(mLock);
5386 return EffectQueryNumberEffects(numEffects);
5387}
5388
5389status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5390{
5391 Mutex::Autolock _l(mLock);
5392 return EffectQueryEffect(index, descriptor);
5393}
5394
5395status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5396{
5397 Mutex::Autolock _l(mLock);
5398 return EffectGetDescriptor(pUuid, descriptor);
5399}
5400
5401
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5403 effect_descriptor_t *pDesc,
5404 const sp<IEffectClient>& effectClient,
5405 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005406 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005407 int sessionId,
5408 status_t *status,
5409 int *id,
5410 int *enabled)
5411{
5412 status_t lStatus = NO_ERROR;
5413 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 effect_descriptor_t desc;
5415 sp<Client> client;
5416 wp<Client> wclient;
5417
Steve Block3856b092011-10-20 11:56:00 +01005418 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005419 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420
5421 if (pDesc == NULL) {
5422 lStatus = BAD_VALUE;
5423 goto Exit;
5424 }
5425
Eric Laurent84e9a102010-09-23 16:10:16 -07005426 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005427 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005428 lStatus = PERMISSION_DENIED;
5429 goto Exit;
5430 }
5431
Dima Zavinfce7a472011-04-19 22:30:36 -07005432 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005433 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005434 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005435 lStatus = PERMISSION_DENIED;
5436 goto Exit;
5437 }
5438
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005439 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005440 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005441 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005442 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005443 lStatus = BAD_VALUE;
5444 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005445 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005446 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005447 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005448 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005449 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005450 }
5451 }
5452
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 {
5454 Mutex::Autolock _l(mLock);
5455
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456
5457 if (!EffectIsNullUuid(&pDesc->uuid)) {
5458 // if uuid is specified, request effect descriptor
5459 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5460 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005461 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462 goto Exit;
5463 }
5464 } else {
5465 // if uuid is not specified, look for an available implementation
5466 // of the required type in effect factory
5467 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005468 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005469 lStatus = BAD_VALUE;
5470 goto Exit;
5471 }
5472 uint32_t numEffects = 0;
5473 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005474 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 bool found = false;
5476
5477 lStatus = EffectQueryNumberEffects(&numEffects);
5478 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005479 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 goto Exit;
5481 }
5482 for (uint32_t i = 0; i < numEffects; i++) {
5483 lStatus = EffectQueryEffect(i, &desc);
5484 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005485 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 continue;
5487 }
5488 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5489 // If matching type found save effect descriptor. If the session is
5490 // 0 and the effect is not auxiliary, continue enumeration in case
5491 // an auxiliary version of this effect type is available
5492 found = true;
5493 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005494 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5496 break;
5497 }
5498 }
5499 }
5500 if (!found) {
5501 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005502 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 goto Exit;
5504 }
5505 // For same effect type, chose auxiliary version over insert version if
5506 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005507 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5509 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5510 }
5511 }
5512
5513 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005514 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5516 lStatus = INVALID_OPERATION;
5517 goto Exit;
5518 }
5519
Eric Laurent59255e42011-07-27 19:49:51 -07005520 // check recording permission for visualizer
5521 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5522 !recordingAllowed()) {
5523 lStatus = PERMISSION_DENIED;
5524 goto Exit;
5525 }
5526
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527 // return effect descriptor
5528 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5529
5530 // If output is not specified try to find a matching audio session ID in one of the
5531 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005532 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5533 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005534 // Note: io is never 0 when creating an effect on an input
5535 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005536 // look for the thread where the specified audio session is present
5537 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5538 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005539 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005540 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005541 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005543 if (io == 0) {
5544 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5545 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5546 io = mRecordThreads.keyAt(i);
5547 break;
5548 }
5549 }
5550 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005551 // If no output thread contains the requested session ID, default to
5552 // first output. The effect chain will be moved to the correct output
5553 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005554 if (io == 0 && mPlaybackThreads.size()) {
5555 io = mPlaybackThreads.keyAt(0);
5556 }
Steve Block3856b092011-10-20 11:56:00 +01005557 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005558 }
5559 ThreadBase *thread = checkRecordThread_l(io);
5560 if (thread == NULL) {
5561 thread = checkPlaybackThread_l(io);
5562 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005563 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005564 lStatus = BAD_VALUE;
5565 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005567 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005568
Mathias Agopian65ab4712010-07-14 17:59:35 -07005569 wclient = mClients.valueFor(pid);
5570
5571 if (wclient != NULL) {
5572 client = wclient.promote();
5573 } else {
5574 client = new Client(this, pid);
5575 mClients.add(pid, client);
5576 }
5577
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005578 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005579 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5580 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581 if (handle != 0 && id != NULL) {
5582 *id = handle->id();
5583 }
5584 }
5585
5586Exit:
5587 if(status) {
5588 *status = lStatus;
5589 }
5590 return handle;
5591}
5592
Eric Laurent59255e42011-07-27 19:49:51 -07005593status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005594{
Steve Block3856b092011-10-20 11:56:00 +01005595 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005596 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005597 Mutex::Autolock _l(mLock);
5598 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005599 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005600 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 }
Eric Laurentde070132010-07-13 04:45:46 -07005602 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5603 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005604 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005605 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 }
Eric Laurentde070132010-07-13 04:45:46 -07005607 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5608 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005609 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005610 return BAD_VALUE;
5611 }
5612
5613 Mutex::Autolock _dl(dstThread->mLock);
5614 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005615 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005616
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 return NO_ERROR;
5618}
5619
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005620// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005621status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005622 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005623 AudioFlinger::PlaybackThread *dstThread,
5624 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005625{
Steve Block3856b092011-10-20 11:56:00 +01005626 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005627 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005628
Eric Laurent59255e42011-07-27 19:49:51 -07005629 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005630 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005631 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005632 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005633 return INVALID_OPERATION;
5634 }
5635
Eric Laurent39e94f82010-07-28 01:32:47 -07005636 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005637 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005638 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005639 // removed.
5640 srcThread->removeEffectChain_l(chain);
5641
5642 // transfer all effects one by one so that new effect chain is created on new thread with
5643 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005644 int dstOutput = dstThread->id();
5645 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005646 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005647 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5648 while (effect != 0) {
5649 srcThread->removeEffect_l(effect);
5650 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005651 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5652 if (effect->state() == EffectModule::ACTIVE ||
5653 effect->state() == EffectModule::STOPPING) {
5654 effect->start();
5655 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005656 // if the move request is not received from audio policy manager, the effect must be
5657 // re-registered with the new strategy and output
5658 if (dstChain == 0) {
5659 dstChain = effect->chain().promote();
5660 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005661 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005662 srcThread->addEffect_l(effect);
5663 return NO_INIT;
5664 }
5665 strategy = dstChain->strategy();
5666 }
5667 if (reRegister) {
5668 AudioSystem::unregisterEffect(effect->id());
5669 AudioSystem::registerEffect(&effect->desc(),
5670 dstOutput,
5671 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005672 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005673 effect->id());
5674 }
Eric Laurentde070132010-07-13 04:45:46 -07005675 effect = chain->getEffectFromId_l(0);
5676 }
5677
5678 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679}
5680
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005681
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005683sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005684 const sp<AudioFlinger::Client>& client,
5685 const sp<IEffectClient>& effectClient,
5686 int32_t priority,
5687 int sessionId,
5688 effect_descriptor_t *desc,
5689 int *enabled,
5690 status_t *status
5691 )
5692{
5693 sp<EffectModule> effect;
5694 sp<EffectHandle> handle;
5695 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005697 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 bool effectCreated = false;
5699 bool effectRegistered = false;
5700
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005701 lStatus = initCheck();
5702 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005703 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 goto Exit;
5705 }
5706
5707 // Do not allow effects with session ID 0 on direct output or duplicating threads
5708 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005709 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005710 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005711 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 lStatus = BAD_VALUE;
5713 goto Exit;
5714 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005715 // Only Pre processor effects are allowed on input threads and only on input threads
5716 if ((mType == RECORD &&
5717 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5718 (mType != RECORD &&
5719 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005720 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005721 desc->name, desc->flags, mType);
5722 lStatus = BAD_VALUE;
5723 goto Exit;
5724 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725
Steve Block3856b092011-10-20 11:56:00 +01005726 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005727
5728 { // scope for mLock
5729 Mutex::Autolock _l(mLock);
5730
5731 // check for existing effect chain with the requested audio session
5732 chain = getEffectChain_l(sessionId);
5733 if (chain == 0) {
5734 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005735 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005736 chain = new EffectChain(this, sessionId);
5737 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005738 chain->setStrategy(getStrategyForSession_l(sessionId));
5739 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005741 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 }
5743
Steve Block3856b092011-10-20 11:56:00 +01005744 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745
5746 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005747 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005749 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 if (lStatus != NO_ERROR) {
5751 goto Exit;
5752 }
5753 effectRegistered = true;
5754 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005755 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 lStatus = effect->status();
5757 if (lStatus != NO_ERROR) {
5758 goto Exit;
5759 }
Eric Laurentcab11242010-07-15 12:50:15 -07005760 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 if (lStatus != NO_ERROR) {
5762 goto Exit;
5763 }
5764 effectCreated = true;
5765
5766 effect->setDevice(mDevice);
5767 effect->setMode(mAudioFlinger->getMode());
5768 }
5769 // create effect handle and connect it to effect module
5770 handle = new EffectHandle(effect, client, effectClient, priority);
5771 lStatus = effect->addHandle(handle);
5772 if (enabled) {
5773 *enabled = (int)effect->isEnabled();
5774 }
5775 }
5776
5777Exit:
5778 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005779 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005781 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005782 }
5783 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005784 AudioSystem::unregisterEffect(effect->id());
5785 }
5786 if (chainCreated) {
5787 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 }
5789 handle.clear();
5790 }
5791
5792 if(status) {
5793 *status = lStatus;
5794 }
5795 return handle;
5796}
5797
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005798sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5799{
5800 sp<EffectModule> effect;
5801
5802 sp<EffectChain> chain = getEffectChain_l(sessionId);
5803 if (chain != 0) {
5804 effect = chain->getEffectFromId_l(effectId);
5805 }
5806 return effect;
5807}
5808
Eric Laurentde070132010-07-13 04:45:46 -07005809// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5810// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005811status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005812{
5813 // check for existing effect chain with the requested audio session
5814 int sessionId = effect->sessionId();
5815 sp<EffectChain> chain = getEffectChain_l(sessionId);
5816 bool chainCreated = false;
5817
5818 if (chain == 0) {
5819 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005820 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005821 chain = new EffectChain(this, sessionId);
5822 addEffectChain_l(chain);
5823 chain->setStrategy(getStrategyForSession_l(sessionId));
5824 chainCreated = true;
5825 }
Steve Block3856b092011-10-20 11:56:00 +01005826 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005827
5828 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005829 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005830 this, effect->desc().name, chain.get());
5831 return BAD_VALUE;
5832 }
5833
5834 status_t status = chain->addEffect_l(effect);
5835 if (status != NO_ERROR) {
5836 if (chainCreated) {
5837 removeEffectChain_l(chain);
5838 }
5839 return status;
5840 }
5841
5842 effect->setDevice(mDevice);
5843 effect->setMode(mAudioFlinger->getMode());
5844 return NO_ERROR;
5845}
5846
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005848
Steve Block3856b092011-10-20 11:56:00 +01005849 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005850 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005851 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5852 detachAuxEffect_l(effect->id());
5853 }
5854
5855 sp<EffectChain> chain = effect->chain().promote();
5856 if (chain != 0) {
5857 // remove effect chain if removing last effect
5858 if (chain->removeEffect_l(effect) == 0) {
5859 removeEffectChain_l(chain);
5860 }
5861 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005862 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005863 }
5864}
5865
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005866void AudioFlinger::ThreadBase::lockEffectChains_l(
5867 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5868{
5869 effectChains = mEffectChains;
5870 for (size_t i = 0; i < mEffectChains.size(); i++) {
5871 mEffectChains[i]->lock();
5872 }
5873}
5874
5875void AudioFlinger::ThreadBase::unlockEffectChains(
5876 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5877{
5878 for (size_t i = 0; i < effectChains.size(); i++) {
5879 effectChains[i]->unlock();
5880 }
5881}
5882
5883sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5884{
5885 Mutex::Autolock _l(mLock);
5886 return getEffectChain_l(sessionId);
5887}
5888
5889sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5890{
5891 sp<EffectChain> chain;
5892
5893 size_t size = mEffectChains.size();
5894 for (size_t i = 0; i < size; i++) {
5895 if (mEffectChains[i]->sessionId() == sessionId) {
5896 chain = mEffectChains[i];
5897 break;
5898 }
5899 }
5900 return chain;
5901}
5902
5903void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5904{
5905 Mutex::Autolock _l(mLock);
5906 size_t size = mEffectChains.size();
5907 for (size_t i = 0; i < size; i++) {
5908 mEffectChains[i]->setMode_l(mode);
5909 }
5910}
5911
5912void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005913 const wp<EffectHandle>& handle,
5914 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005915
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005917 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 // delete the effect module if removing last handle on it
5919 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005920 if (!effect->isPinned() || unpiniflast) {
5921 removeEffect_l(effect);
5922 AudioSystem::unregisterEffect(effect->id());
5923 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 }
5925}
5926
5927status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5928{
5929 int session = chain->sessionId();
5930 int16_t *buffer = mMixBuffer;
5931 bool ownsBuffer = false;
5932
Steve Block3856b092011-10-20 11:56:00 +01005933 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 if (session > 0) {
5935 // Only one effect chain can be present in direct output thread and it uses
5936 // the mix buffer as input
5937 if (mType != DIRECT) {
5938 size_t numSamples = mFrameCount * mChannelCount;
5939 buffer = new int16_t[numSamples];
5940 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005941 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942 ownsBuffer = true;
5943 }
5944
5945 // Attach all tracks with same session ID to this chain.
5946 for (size_t i = 0; i < mTracks.size(); ++i) {
5947 sp<Track> track = mTracks[i];
5948 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005949 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005951 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 }
5953 }
5954
5955 // indicate all active tracks in the chain
5956 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5957 sp<Track> track = mActiveTracks[i].promote();
5958 if (track == 0) continue;
5959 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005960 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005961 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 }
5963 }
5964 }
5965
5966 chain->setInBuffer(buffer, ownsBuffer);
5967 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005968 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005969 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005970 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5971 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005973 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5974 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005975 // Effect chain for other sessions are inserted at beginning of effect
5976 // chains list to be processed before output mix effects. Relative order between other
5977 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 size_t size = mEffectChains.size();
5979 size_t i = 0;
5980 for (i = 0; i < size; i++) {
5981 if (mEffectChains[i]->sessionId() < session) break;
5982 }
5983 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005984 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985
5986 return NO_ERROR;
5987}
5988
5989size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5990{
5991 int session = chain->sessionId();
5992
Steve Block3856b092011-10-20 11:56:00 +01005993 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994
5995 for (size_t i = 0; i < mEffectChains.size(); i++) {
5996 if (chain == mEffectChains[i]) {
5997 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005998 // detach all active tracks from the chain
5999 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6000 sp<Track> track = mActiveTracks[i].promote();
6001 if (track == 0) continue;
6002 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006003 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006004 chain.get(), session);
6005 chain->decActiveTrackCnt();
6006 }
6007 }
6008
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 // detach all tracks with same session ID from this chain
6010 for (size_t i = 0; i < mTracks.size(); ++i) {
6011 sp<Track> track = mTracks[i];
6012 if (session == track->sessionId()) {
6013 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006014 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 }
6016 }
Eric Laurentde070132010-07-13 04:45:46 -07006017 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018 }
6019 }
6020 return mEffectChains.size();
6021}
6022
Eric Laurentde070132010-07-13 04:45:46 -07006023status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6024 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025{
6026 Mutex::Autolock _l(mLock);
6027 return attachAuxEffect_l(track, EffectId);
6028}
6029
Eric Laurentde070132010-07-13 04:45:46 -07006030status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6031 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032{
6033 status_t status = NO_ERROR;
6034
6035 if (EffectId == 0) {
6036 track->setAuxBuffer(0, NULL);
6037 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006038 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6039 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 if (effect != 0) {
6041 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6042 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6043 } else {
6044 status = INVALID_OPERATION;
6045 }
6046 } else {
6047 status = BAD_VALUE;
6048 }
6049 }
6050 return status;
6051}
6052
6053void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6054{
6055 for (size_t i = 0; i < mTracks.size(); ++i) {
6056 sp<Track> track = mTracks[i];
6057 if (track->auxEffectId() == effectId) {
6058 attachAuxEffect_l(track, 0);
6059 }
6060 }
6061}
6062
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006063status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6064{
6065 // only one chain per input thread
6066 if (mEffectChains.size() != 0) {
6067 return INVALID_OPERATION;
6068 }
Steve Block3856b092011-10-20 11:56:00 +01006069 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006070
6071 chain->setInBuffer(NULL);
6072 chain->setOutBuffer(NULL);
6073
Eric Laurent59255e42011-07-27 19:49:51 -07006074 checkSuspendOnAddEffectChain_l(chain);
6075
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006076 mEffectChains.add(chain);
6077
6078 return NO_ERROR;
6079}
6080
6081size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6082{
Steve Block3856b092011-10-20 11:56:00 +01006083 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006084 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006085 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6086 chain.get(), mEffectChains.size(), this);
6087 if (mEffectChains.size() == 1) {
6088 mEffectChains.removeAt(0);
6089 }
6090 return 0;
6091}
6092
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093// ----------------------------------------------------------------------------
6094// EffectModule implementation
6095// ----------------------------------------------------------------------------
6096
6097#undef LOG_TAG
6098#define LOG_TAG "AudioFlinger::EffectModule"
6099
6100AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6101 const wp<AudioFlinger::EffectChain>& chain,
6102 effect_descriptor_t *desc,
6103 int id,
6104 int sessionId)
6105 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006106 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107{
Steve Block3856b092011-10-20 11:56:00 +01006108 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 int lStatus;
6110 sp<ThreadBase> thread = mThread.promote();
6111 if (thread == 0) {
6112 return;
6113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114
6115 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6116
6117 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006118 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119
6120 if (mStatus != NO_ERROR) {
6121 return;
6122 }
6123 lStatus = init();
6124 if (lStatus < 0) {
6125 mStatus = lStatus;
6126 goto Error;
6127 }
6128
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006129 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6130 mPinned = true;
6131 }
Steve Block3856b092011-10-20 11:56:00 +01006132 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 return;
6134Error:
6135 EffectRelease(mEffectInterface);
6136 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006137 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006138}
6139
6140AudioFlinger::EffectModule::~EffectModule()
6141{
Steve Block3856b092011-10-20 11:56:00 +01006142 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006143 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006144 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6145 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6146 sp<ThreadBase> thread = mThread.promote();
6147 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006148 audio_stream_t *stream = thread->stream();
6149 if (stream != NULL) {
6150 stream->remove_audio_effect(stream, mEffectInterface);
6151 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006152 }
6153 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154 // release effect engine
6155 EffectRelease(mEffectInterface);
6156 }
6157}
6158
6159status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6160{
6161 status_t status;
6162
6163 Mutex::Autolock _l(mLock);
6164 // First handle in mHandles has highest priority and controls the effect module
6165 int priority = handle->priority();
6166 size_t size = mHandles.size();
6167 sp<EffectHandle> h;
6168 size_t i;
6169 for (i = 0; i < size; i++) {
6170 h = mHandles[i].promote();
6171 if (h == 0) continue;
6172 if (h->priority() <= priority) break;
6173 }
6174 // if inserted in first place, move effect control from previous owner to this handle
6175 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006176 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006178 enabled = h->enabled();
6179 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180 }
Eric Laurent59255e42011-07-27 19:49:51 -07006181 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 status = NO_ERROR;
6183 } else {
6184 status = ALREADY_EXISTS;
6185 }
Steve Block3856b092011-10-20 11:56:00 +01006186 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006187 mHandles.insertAt(handle, i);
6188 return status;
6189}
6190
6191size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6192{
6193 Mutex::Autolock _l(mLock);
6194 size_t size = mHandles.size();
6195 size_t i;
6196 for (i = 0; i < size; i++) {
6197 if (mHandles[i] == handle) break;
6198 }
6199 if (i == size) {
6200 return size;
6201 }
Steve Block3856b092011-10-20 11:56:00 +01006202 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006203
6204 bool enabled = false;
6205 EffectHandle *hdl = handle.unsafe_get();
6206 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006207 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006208 enabled = hdl->enabled();
6209 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006210 mHandles.removeAt(i);
6211 size = mHandles.size();
6212 // if removed from first place, move effect control from this handle to next in line
6213 if (i == 0 && size != 0) {
6214 sp<EffectHandle> h = mHandles[0].promote();
6215 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006216 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217 }
6218 }
6219
Eric Laurentec437d82011-07-26 20:54:46 -07006220 // Prevent calls to process() and other functions on effect interface from now on.
6221 // The effect engine will be released by the destructor when the last strong reference on
6222 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006223 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006224 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006225 }
6226
Mathias Agopian65ab4712010-07-14 17:59:35 -07006227 return size;
6228}
6229
Eric Laurent59255e42011-07-27 19:49:51 -07006230sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6231{
6232 Mutex::Autolock _l(mLock);
6233 sp<EffectHandle> handle;
6234 if (mHandles.size() != 0) {
6235 handle = mHandles[0].promote();
6236 }
6237 return handle;
6238}
6239
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006240void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241{
Steve Block3856b092011-10-20 11:56:00 +01006242 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006243 // keep a strong reference on this EffectModule to avoid calling the
6244 // destructor before we exit
6245 sp<EffectModule> keep(this);
6246 {
6247 sp<ThreadBase> thread = mThread.promote();
6248 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006249 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 }
6251 }
6252}
6253
6254void AudioFlinger::EffectModule::updateState() {
6255 Mutex::Autolock _l(mLock);
6256
6257 switch (mState) {
6258 case RESTART:
6259 reset_l();
6260 // FALL THROUGH
6261
6262 case STARTING:
6263 // clear auxiliary effect input buffer for next accumulation
6264 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6265 memset(mConfig.inputCfg.buffer.raw,
6266 0,
6267 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6268 }
6269 start_l();
6270 mState = ACTIVE;
6271 break;
6272 case STOPPING:
6273 stop_l();
6274 mDisableWaitCnt = mMaxDisableWaitCnt;
6275 mState = STOPPED;
6276 break;
6277 case STOPPED:
6278 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6279 // turn off sequence.
6280 if (--mDisableWaitCnt == 0) {
6281 reset_l();
6282 mState = IDLE;
6283 }
6284 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006285 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 break;
6287 }
6288}
6289
6290void AudioFlinger::EffectModule::process()
6291{
6292 Mutex::Autolock _l(mLock);
6293
Eric Laurentec437d82011-07-26 20:54:46 -07006294 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 mConfig.inputCfg.buffer.raw == NULL ||
6296 mConfig.outputCfg.buffer.raw == NULL) {
6297 return;
6298 }
6299
Eric Laurent8f45bd72010-08-31 13:50:07 -07006300 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6302 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006303 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006304 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006305 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 }
6307
6308 // do the actual processing in the effect engine
6309 int ret = (*mEffectInterface)->process(mEffectInterface,
6310 &mConfig.inputCfg.buffer,
6311 &mConfig.outputCfg.buffer);
6312
6313 // force transition to IDLE state when engine is ready
6314 if (mState == STOPPED && ret == -ENODATA) {
6315 mDisableWaitCnt = 1;
6316 }
6317
6318 // clear auxiliary effect input buffer for next accumulation
6319 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006320 memset(mConfig.inputCfg.buffer.raw, 0,
6321 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006322 }
6323 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006324 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6325 // If an insert effect is idle and input buffer is different from output buffer,
6326 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006328 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006329 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6330 int16_t *in = mConfig.inputCfg.buffer.s16;
6331 int16_t *out = mConfig.outputCfg.buffer.s16;
6332 for (size_t i = 0; i < frameCnt; i++) {
6333 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006334 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 }
6336 }
6337}
6338
6339void AudioFlinger::EffectModule::reset_l()
6340{
6341 if (mEffectInterface == NULL) {
6342 return;
6343 }
6344 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6345}
6346
6347status_t AudioFlinger::EffectModule::configure()
6348{
6349 uint32_t channels;
6350 if (mEffectInterface == NULL) {
6351 return NO_INIT;
6352 }
6353
6354 sp<ThreadBase> thread = mThread.promote();
6355 if (thread == 0) {
6356 return DEAD_OBJECT;
6357 }
6358
6359 // TODO: handle configuration of effects replacing track process
6360 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006361 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006362 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006363 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 }
6365
6366 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006367 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 } else {
6369 mConfig.inputCfg.channels = channels;
6370 }
6371 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006372 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6373 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 mConfig.inputCfg.samplingRate = thread->sampleRate();
6375 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6376 mConfig.inputCfg.bufferProvider.cookie = NULL;
6377 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6378 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6379 mConfig.outputCfg.bufferProvider.cookie = NULL;
6380 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6381 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6382 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6383 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006384 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006385 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 // - in other sessions:
6387 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6388 // other effect: overwrites output buffer: input buffer == output buffer
6389 // Auxiliary effect:
6390 // accumulates in output buffer: input buffer != output buffer
6391 // Therefore: accumulate <=> input buffer != output buffer
6392 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6393 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6394 } else {
6395 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6396 }
6397 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6398 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6399 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6400 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6401
Steve Block3856b092011-10-20 11:56:00 +01006402 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006403 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6404
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006406 uint32_t size = sizeof(int);
6407 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006408 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006409 sizeof(effect_config_t),
6410 &mConfig,
6411 &size,
6412 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 if (status == 0) {
6414 status = cmdStatus;
6415 }
6416
6417 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6418 (1000 * mConfig.outputCfg.buffer.frameCount);
6419
6420 return status;
6421}
6422
6423status_t AudioFlinger::EffectModule::init()
6424{
6425 Mutex::Autolock _l(mLock);
6426 if (mEffectInterface == NULL) {
6427 return NO_INIT;
6428 }
6429 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006430 uint32_t size = sizeof(status_t);
6431 status_t status = (*mEffectInterface)->command(mEffectInterface,
6432 EFFECT_CMD_INIT,
6433 0,
6434 NULL,
6435 &size,
6436 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 if (status == 0) {
6438 status = cmdStatus;
6439 }
6440 return status;
6441}
6442
Eric Laurentec35a142011-10-05 17:42:25 -07006443status_t AudioFlinger::EffectModule::start()
6444{
6445 Mutex::Autolock _l(mLock);
6446 return start_l();
6447}
6448
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449status_t AudioFlinger::EffectModule::start_l()
6450{
6451 if (mEffectInterface == NULL) {
6452 return NO_INIT;
6453 }
6454 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006455 uint32_t size = sizeof(status_t);
6456 status_t status = (*mEffectInterface)->command(mEffectInterface,
6457 EFFECT_CMD_ENABLE,
6458 0,
6459 NULL,
6460 &size,
6461 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462 if (status == 0) {
6463 status = cmdStatus;
6464 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006465 if (status == 0 &&
6466 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6467 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6468 sp<ThreadBase> thread = mThread.promote();
6469 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006470 audio_stream_t *stream = thread->stream();
6471 if (stream != NULL) {
6472 stream->add_audio_effect(stream, mEffectInterface);
6473 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006474 }
6475 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 return status;
6477}
6478
Eric Laurentec437d82011-07-26 20:54:46 -07006479status_t AudioFlinger::EffectModule::stop()
6480{
6481 Mutex::Autolock _l(mLock);
6482 return stop_l();
6483}
6484
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485status_t AudioFlinger::EffectModule::stop_l()
6486{
6487 if (mEffectInterface == NULL) {
6488 return NO_INIT;
6489 }
6490 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006491 uint32_t size = sizeof(status_t);
6492 status_t status = (*mEffectInterface)->command(mEffectInterface,
6493 EFFECT_CMD_DISABLE,
6494 0,
6495 NULL,
6496 &size,
6497 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498 if (status == 0) {
6499 status = cmdStatus;
6500 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006501 if (status == 0 &&
6502 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6503 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6504 sp<ThreadBase> thread = mThread.promote();
6505 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006506 audio_stream_t *stream = thread->stream();
6507 if (stream != NULL) {
6508 stream->remove_audio_effect(stream, mEffectInterface);
6509 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006510 }
6511 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512 return status;
6513}
6514
Eric Laurent25f43952010-07-28 05:40:18 -07006515status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6516 uint32_t cmdSize,
6517 void *pCmdData,
6518 uint32_t *replySize,
6519 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006520{
6521 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006522// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523
Eric Laurentec437d82011-07-26 20:54:46 -07006524 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 return NO_INIT;
6526 }
Eric Laurent25f43952010-07-28 05:40:18 -07006527 status_t status = (*mEffectInterface)->command(mEffectInterface,
6528 cmdCode,
6529 cmdSize,
6530 pCmdData,
6531 replySize,
6532 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006534 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 for (size_t i = 1; i < mHandles.size(); i++) {
6536 sp<EffectHandle> h = mHandles[i].promote();
6537 if (h != 0) {
6538 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6539 }
6540 }
6541 }
6542 return status;
6543}
6544
6545status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6546{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006547
Mathias Agopian65ab4712010-07-14 17:59:35 -07006548 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006549 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006550
6551 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006552 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6553 if (enabled && status != NO_ERROR) {
6554 return status;
6555 }
6556
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 switch (mState) {
6558 // going from disabled to enabled
6559 case IDLE:
6560 mState = STARTING;
6561 break;
6562 case STOPPED:
6563 mState = RESTART;
6564 break;
6565 case STOPPING:
6566 mState = ACTIVE;
6567 break;
6568
6569 // going from enabled to disabled
6570 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006571 mState = STOPPED;
6572 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 case STARTING:
6574 mState = IDLE;
6575 break;
6576 case ACTIVE:
6577 mState = STOPPING;
6578 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006579 case DESTROYED:
6580 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 }
6582 for (size_t i = 1; i < mHandles.size(); i++) {
6583 sp<EffectHandle> h = mHandles[i].promote();
6584 if (h != 0) {
6585 h->setEnabled(enabled);
6586 }
6587 }
6588 }
6589 return NO_ERROR;
6590}
6591
6592bool AudioFlinger::EffectModule::isEnabled()
6593{
6594 switch (mState) {
6595 case RESTART:
6596 case STARTING:
6597 case ACTIVE:
6598 return true;
6599 case IDLE:
6600 case STOPPING:
6601 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006602 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 default:
6604 return false;
6605 }
6606}
6607
Eric Laurent8f45bd72010-08-31 13:50:07 -07006608bool AudioFlinger::EffectModule::isProcessEnabled()
6609{
6610 switch (mState) {
6611 case RESTART:
6612 case ACTIVE:
6613 case STOPPING:
6614 case STOPPED:
6615 return true;
6616 case IDLE:
6617 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006618 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006619 default:
6620 return false;
6621 }
6622}
6623
Mathias Agopian65ab4712010-07-14 17:59:35 -07006624status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6625{
6626 Mutex::Autolock _l(mLock);
6627 status_t status = NO_ERROR;
6628
6629 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6630 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006631 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006632 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6633 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 status_t cmdStatus;
6635 uint32_t volume[2];
6636 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006637 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006638 volume[0] = *left;
6639 volume[1] = *right;
6640 if (controller) {
6641 pVolume = volume;
6642 }
Eric Laurent25f43952010-07-28 05:40:18 -07006643 status = (*mEffectInterface)->command(mEffectInterface,
6644 EFFECT_CMD_SET_VOLUME,
6645 size,
6646 volume,
6647 &size,
6648 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006649 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6650 *left = volume[0];
6651 *right = volume[1];
6652 }
6653 }
6654 return status;
6655}
6656
6657status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6658{
6659 Mutex::Autolock _l(mLock);
6660 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006661 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6662 // audio pre processing modules on RecordThread can receive both output and
6663 // input device indication in the same call
6664 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6665 if (dev) {
6666 status_t cmdStatus;
6667 uint32_t size = sizeof(status_t);
6668
6669 status = (*mEffectInterface)->command(mEffectInterface,
6670 EFFECT_CMD_SET_DEVICE,
6671 sizeof(uint32_t),
6672 &dev,
6673 &size,
6674 &cmdStatus);
6675 if (status == NO_ERROR) {
6676 status = cmdStatus;
6677 }
6678 }
6679 dev = device & AUDIO_DEVICE_IN_ALL;
6680 if (dev) {
6681 status_t cmdStatus;
6682 uint32_t size = sizeof(status_t);
6683
6684 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6685 EFFECT_CMD_SET_INPUT_DEVICE,
6686 sizeof(uint32_t),
6687 &dev,
6688 &size,
6689 &cmdStatus);
6690 if (status2 == NO_ERROR) {
6691 status2 = cmdStatus;
6692 }
6693 if (status == NO_ERROR) {
6694 status = status2;
6695 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006696 }
6697 }
6698 return status;
6699}
6700
6701status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6702{
6703 Mutex::Autolock _l(mLock);
6704 status_t status = NO_ERROR;
6705 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006707 uint32_t size = sizeof(status_t);
6708 status = (*mEffectInterface)->command(mEffectInterface,
6709 EFFECT_CMD_SET_AUDIO_MODE,
6710 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006711 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006712 &size,
6713 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006714 if (status == NO_ERROR) {
6715 status = cmdStatus;
6716 }
6717 }
6718 return status;
6719}
6720
Eric Laurent59255e42011-07-27 19:49:51 -07006721void AudioFlinger::EffectModule::setSuspended(bool suspended)
6722{
6723 Mutex::Autolock _l(mLock);
6724 mSuspended = suspended;
6725}
Glenn Kastena3a85482012-01-04 11:01:11 -08006726
6727bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006728{
6729 Mutex::Autolock _l(mLock);
6730 return mSuspended;
6731}
6732
Mathias Agopian65ab4712010-07-14 17:59:35 -07006733status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6734{
6735 const size_t SIZE = 256;
6736 char buffer[SIZE];
6737 String8 result;
6738
6739 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6740 result.append(buffer);
6741
6742 bool locked = tryLock(mLock);
6743 // failed to lock - AudioFlinger is probably deadlocked
6744 if (!locked) {
6745 result.append("\t\tCould not lock Fx mutex:\n");
6746 }
6747
6748 result.append("\t\tSession Status State Engine:\n");
6749 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6750 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6751 result.append(buffer);
6752
6753 result.append("\t\tDescriptor:\n");
6754 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6755 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6756 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6757 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6758 result.append(buffer);
6759 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6760 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6761 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6762 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6763 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006764 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 mDescriptor.apiVersion,
6766 mDescriptor.flags);
6767 result.append(buffer);
6768 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6769 mDescriptor.name);
6770 result.append(buffer);
6771 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6772 mDescriptor.implementor);
6773 result.append(buffer);
6774
6775 result.append("\t\t- Input configuration:\n");
6776 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6777 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6778 (uint32_t)mConfig.inputCfg.buffer.raw,
6779 mConfig.inputCfg.buffer.frameCount,
6780 mConfig.inputCfg.samplingRate,
6781 mConfig.inputCfg.channels,
6782 mConfig.inputCfg.format);
6783 result.append(buffer);
6784
6785 result.append("\t\t- Output configuration:\n");
6786 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6787 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6788 (uint32_t)mConfig.outputCfg.buffer.raw,
6789 mConfig.outputCfg.buffer.frameCount,
6790 mConfig.outputCfg.samplingRate,
6791 mConfig.outputCfg.channels,
6792 mConfig.outputCfg.format);
6793 result.append(buffer);
6794
6795 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6796 result.append(buffer);
6797 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6798 for (size_t i = 0; i < mHandles.size(); ++i) {
6799 sp<EffectHandle> handle = mHandles[i].promote();
6800 if (handle != 0) {
6801 handle->dump(buffer, SIZE);
6802 result.append(buffer);
6803 }
6804 }
6805
6806 result.append("\n");
6807
6808 write(fd, result.string(), result.length());
6809
6810 if (locked) {
6811 mLock.unlock();
6812 }
6813
6814 return NO_ERROR;
6815}
6816
6817// ----------------------------------------------------------------------------
6818// EffectHandle implementation
6819// ----------------------------------------------------------------------------
6820
6821#undef LOG_TAG
6822#define LOG_TAG "AudioFlinger::EffectHandle"
6823
6824AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6825 const sp<AudioFlinger::Client>& client,
6826 const sp<IEffectClient>& effectClient,
6827 int32_t priority)
6828 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006829 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006830 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006831{
Steve Block3856b092011-10-20 11:56:00 +01006832 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006833
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006834 if (client == 0) {
6835 return;
6836 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6838 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6839 if (mCblkMemory != 0) {
6840 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6841
6842 if (mCblk) {
6843 new(mCblk) effect_param_cblk_t();
6844 mBuffer = (uint8_t *)mCblk + bufOffset;
6845 }
6846 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006847 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 return;
6849 }
6850}
6851
6852AudioFlinger::EffectHandle::~EffectHandle()
6853{
Steve Block3856b092011-10-20 11:56:00 +01006854 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006855 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006856 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857}
6858
6859status_t AudioFlinger::EffectHandle::enable()
6860{
Steve Block3856b092011-10-20 11:56:00 +01006861 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862 if (!mHasControl) return INVALID_OPERATION;
6863 if (mEffect == 0) return DEAD_OBJECT;
6864
Eric Laurentdb7c0792011-08-10 10:37:50 -07006865 if (mEnabled) {
6866 return NO_ERROR;
6867 }
6868
Eric Laurent59255e42011-07-27 19:49:51 -07006869 mEnabled = true;
6870
6871 sp<ThreadBase> thread = mEffect->thread().promote();
6872 if (thread != 0) {
6873 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6874 }
6875
6876 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6877 if (mEffect->suspended()) {
6878 return NO_ERROR;
6879 }
6880
Eric Laurentdb7c0792011-08-10 10:37:50 -07006881 status_t status = mEffect->setEnabled(true);
6882 if (status != NO_ERROR) {
6883 if (thread != 0) {
6884 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6885 }
6886 mEnabled = false;
6887 }
6888 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889}
6890
6891status_t AudioFlinger::EffectHandle::disable()
6892{
Steve Block3856b092011-10-20 11:56:00 +01006893 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006895 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896
Eric Laurentdb7c0792011-08-10 10:37:50 -07006897 if (!mEnabled) {
6898 return NO_ERROR;
6899 }
Eric Laurent59255e42011-07-27 19:49:51 -07006900 mEnabled = false;
6901
6902 if (mEffect->suspended()) {
6903 return NO_ERROR;
6904 }
6905
6906 status_t status = mEffect->setEnabled(false);
6907
6908 sp<ThreadBase> thread = mEffect->thread().promote();
6909 if (thread != 0) {
6910 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6911 }
6912
6913 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914}
6915
6916void AudioFlinger::EffectHandle::disconnect()
6917{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006918 disconnect(true);
6919}
6920
6921void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6922{
Steve Block3856b092011-10-20 11:56:00 +01006923 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006924 if (mEffect == 0) {
6925 return;
6926 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006927 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006928
Eric Laurenta85a74a2011-10-19 11:44:54 -07006929 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006930 sp<ThreadBase> thread = mEffect->thread().promote();
6931 if (thread != 0) {
6932 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6933 }
Eric Laurent59255e42011-07-27 19:49:51 -07006934 }
6935
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936 // release sp on module => module destructor can be called now
6937 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006939 if (mCblk) {
6940 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6941 }
6942 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6944 mClient.clear();
6945 }
6946}
6947
Eric Laurent25f43952010-07-28 05:40:18 -07006948status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6949 uint32_t cmdSize,
6950 void *pCmdData,
6951 uint32_t *replySize,
6952 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953{
Steve Block3856b092011-10-20 11:56:00 +01006954// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006955// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956
6957 // only get parameter command is permitted for applications not controlling the effect
6958 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6959 return INVALID_OPERATION;
6960 }
6961 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006962 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963
6964 // handle commands that are not forwarded transparently to effect engine
6965 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6966 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6967 // no risk to block the whole media server process or mixer threads is we are stuck here
6968 Mutex::Autolock _l(mCblk->lock);
6969 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6970 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6971 mCblk->serverIndex = 0;
6972 mCblk->clientIndex = 0;
6973 return BAD_VALUE;
6974 }
6975 status_t status = NO_ERROR;
6976 while (mCblk->serverIndex < mCblk->clientIndex) {
6977 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006978 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 int *p = (int *)(mBuffer + mCblk->serverIndex);
6980 int size = *p++;
6981 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006982 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 break;
6984 }
6985 effect_param_t *param = (effect_param_t *)p;
6986 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006987 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988 mCblk->serverIndex += size;
6989 continue;
6990 }
Eric Laurent25f43952010-07-28 05:40:18 -07006991 uint32_t psize = sizeof(effect_param_t) +
6992 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6993 param->vsize;
6994 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6995 psize,
6996 p,
6997 &rsize,
6998 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006999 // stop at first error encountered
7000 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007002 *(int *)pReplyData = reply;
7003 break;
7004 } else if (reply != NO_ERROR) {
7005 *(int *)pReplyData = reply;
7006 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 }
7008 mCblk->serverIndex += size;
7009 }
7010 mCblk->serverIndex = 0;
7011 mCblk->clientIndex = 0;
7012 return status;
7013 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007014 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007015 return enable();
7016 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007017 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007018 return disable();
7019 }
7020
7021 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7022}
7023
7024sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7025 return mCblkMemory;
7026}
7027
Eric Laurent59255e42011-07-27 19:49:51 -07007028void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007029{
Steve Block3856b092011-10-20 11:56:00 +01007030 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031
7032 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007033 mEnabled = enabled;
7034
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035 if (signal && mEffectClient != 0) {
7036 mEffectClient->controlStatusChanged(hasControl);
7037 }
7038}
7039
Eric Laurent25f43952010-07-28 05:40:18 -07007040void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7041 uint32_t cmdSize,
7042 void *pCmdData,
7043 uint32_t replySize,
7044 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045{
7046 if (mEffectClient != 0) {
7047 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7048 }
7049}
7050
7051
7052
7053void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7054{
7055 if (mEffectClient != 0) {
7056 mEffectClient->enableStatusChanged(enabled);
7057 }
7058}
7059
7060status_t AudioFlinger::EffectHandle::onTransact(
7061 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7062{
7063 return BnEffect::onTransact(code, data, reply, flags);
7064}
7065
7066
7067void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7068{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007069 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070
7071 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7072 (mClient == NULL) ? getpid() : mClient->pid(),
7073 mPriority,
7074 mHasControl,
7075 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007076 mCblk ? mCblk->clientIndex : 0,
7077 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 );
7079
7080 if (locked) {
7081 mCblk->lock.unlock();
7082 }
7083}
7084
7085#undef LOG_TAG
7086#define LOG_TAG "AudioFlinger::EffectChain"
7087
7088AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7089 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007090 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007091 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7092 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093{
Dima Zavinfce7a472011-04-19 22:30:36 -07007094 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007095 sp<ThreadBase> thread = mThread.promote();
7096 if (thread == 0) {
7097 return;
7098 }
7099 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7100 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007101}
7102
7103AudioFlinger::EffectChain::~EffectChain()
7104{
7105 if (mOwnInBuffer) {
7106 delete mInBuffer;
7107 }
7108
7109}
7110
Eric Laurent59255e42011-07-27 19:49:51 -07007111// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007112sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007113{
7114 sp<EffectModule> effect;
7115 size_t size = mEffects.size();
7116
7117 for (size_t i = 0; i < size; i++) {
7118 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7119 effect = mEffects[i];
7120 break;
7121 }
7122 }
7123 return effect;
7124}
7125
Eric Laurent59255e42011-07-27 19:49:51 -07007126// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007127sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007128{
7129 sp<EffectModule> effect;
7130 size_t size = mEffects.size();
7131
7132 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007133 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7134 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135 effect = mEffects[i];
7136 break;
7137 }
7138 }
7139 return effect;
7140}
7141
Eric Laurent59255e42011-07-27 19:49:51 -07007142// getEffectFromType_l() must be called with ThreadBase::mLock held
7143sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7144 const effect_uuid_t *type)
7145{
7146 sp<EffectModule> effect;
7147 size_t size = mEffects.size();
7148
7149 for (size_t i = 0; i < size; i++) {
7150 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7151 effect = mEffects[i];
7152 break;
7153 }
7154 }
7155 return effect;
7156}
7157
Mathias Agopian65ab4712010-07-14 17:59:35 -07007158// Must be called with EffectChain::mLock locked
7159void AudioFlinger::EffectChain::process_l()
7160{
Eric Laurentdac69112010-09-28 14:09:57 -07007161 sp<ThreadBase> thread = mThread.promote();
7162 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007163 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007164 return;
7165 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007166 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7167 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007168 // always process effects unless no more tracks are on the session and the effect tail
7169 // has been rendered
7170 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007171 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007172 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007173
Eric Laurent544fe9b2011-11-11 15:42:52 -08007174 if (!tracksOnSession && mTailBufferCount == 0) {
7175 doProcess = false;
7176 }
7177
7178 if (activeTrackCnt() == 0) {
7179 // if no track is active and the effect tail has not been rendered,
7180 // the input buffer must be cleared here as the mixer process will not do it
7181 if (tracksOnSession || mTailBufferCount > 0) {
7182 size_t numSamples = thread->frameCount() * thread->channelCount();
7183 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7184 if (mTailBufferCount > 0) {
7185 mTailBufferCount--;
7186 }
7187 }
7188 }
Eric Laurentdac69112010-09-28 14:09:57 -07007189 }
7190
Mathias Agopian65ab4712010-07-14 17:59:35 -07007191 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007192 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007193 for (size_t i = 0; i < size; i++) {
7194 mEffects[i]->process();
7195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196 }
7197 for (size_t i = 0; i < size; i++) {
7198 mEffects[i]->updateState();
7199 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007200}
7201
Eric Laurentcab11242010-07-15 12:50:15 -07007202// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007203status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204{
7205 effect_descriptor_t desc = effect->desc();
7206 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7207
7208 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007209 effect->setChain(this);
7210 sp<ThreadBase> thread = mThread.promote();
7211 if (thread == 0) {
7212 return NO_INIT;
7213 }
7214 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007215
7216 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7217 // Auxiliary effects are inserted at the beginning of mEffects vector as
7218 // they are processed first and accumulated in chain input buffer
7219 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007220
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221 // the input buffer for auxiliary effect contains mono samples in
7222 // 32 bit format. This is to avoid saturation in AudoMixer
7223 // accumulation stage. Saturation is done in EffectModule::process() before
7224 // calling the process in effect engine
7225 size_t numSamples = thread->frameCount();
7226 int32_t *buffer = new int32_t[numSamples];
7227 memset(buffer, 0, numSamples * sizeof(int32_t));
7228 effect->setInBuffer((int16_t *)buffer);
7229 // auxiliary effects output samples to chain input buffer for further processing
7230 // by insert effects
7231 effect->setOutBuffer(mInBuffer);
7232 } else {
7233 // Insert effects are inserted at the end of mEffects vector as they are processed
7234 // after track and auxiliary effects.
7235 // Insert effect order as a function of indicated preference:
7236 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7237 // another effect is present
7238 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7239 // last effect claiming first position
7240 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7241 // first effect claiming last position
7242 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7243 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7244 // already present
7245
7246 int size = (int)mEffects.size();
7247 int idx_insert = size;
7248 int idx_insert_first = -1;
7249 int idx_insert_last = -1;
7250
7251 for (int i = 0; i < size; i++) {
7252 effect_descriptor_t d = mEffects[i]->desc();
7253 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7254 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7255 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7256 // check invalid effect chaining combinations
7257 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7258 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007259 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007260 return INVALID_OPERATION;
7261 }
7262 // remember position of first insert effect and by default
7263 // select this as insert position for new effect
7264 if (idx_insert == size) {
7265 idx_insert = i;
7266 }
7267 // remember position of last insert effect claiming
7268 // first position
7269 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7270 idx_insert_first = i;
7271 }
7272 // remember position of first insert effect claiming
7273 // last position
7274 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7275 idx_insert_last == -1) {
7276 idx_insert_last = i;
7277 }
7278 }
7279 }
7280
7281 // modify idx_insert from first position if needed
7282 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7283 if (idx_insert_last != -1) {
7284 idx_insert = idx_insert_last;
7285 } else {
7286 idx_insert = size;
7287 }
7288 } else {
7289 if (idx_insert_first != -1) {
7290 idx_insert = idx_insert_first + 1;
7291 }
7292 }
7293
7294 // always read samples from chain input buffer
7295 effect->setInBuffer(mInBuffer);
7296
7297 // if last effect in the chain, output samples to chain
7298 // output buffer, otherwise to chain input buffer
7299 if (idx_insert == size) {
7300 if (idx_insert != 0) {
7301 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7302 mEffects[idx_insert-1]->configure();
7303 }
7304 effect->setOutBuffer(mOutBuffer);
7305 } else {
7306 effect->setOutBuffer(mInBuffer);
7307 }
7308 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309
Steve Block3856b092011-10-20 11:56:00 +01007310 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311 }
7312 effect->configure();
7313 return NO_ERROR;
7314}
7315
Eric Laurentcab11242010-07-15 12:50:15 -07007316// removeEffect_l() must be called with PlaybackThread::mLock held
7317size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318{
7319 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 int size = (int)mEffects.size();
7321 int i;
7322 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7323
7324 for (i = 0; i < size; i++) {
7325 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007326 // calling stop here will remove pre-processing effect from the audio HAL.
7327 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7328 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007329 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7330 mEffects[i]->state() == EffectModule::STOPPING) {
7331 mEffects[i]->stop();
7332 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7334 delete[] effect->inBuffer();
7335 } else {
7336 if (i == size - 1 && i != 0) {
7337 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7338 mEffects[i - 1]->configure();
7339 }
7340 }
7341 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007342 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343 break;
7344 }
7345 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346
7347 return mEffects.size();
7348}
7349
Eric Laurentcab11242010-07-15 12:50:15 -07007350// setDevice_l() must be called with PlaybackThread::mLock held
7351void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352{
7353 size_t size = mEffects.size();
7354 for (size_t i = 0; i < size; i++) {
7355 mEffects[i]->setDevice(device);
7356 }
7357}
7358
Eric Laurentcab11242010-07-15 12:50:15 -07007359// setMode_l() must be called with PlaybackThread::mLock held
7360void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361{
7362 size_t size = mEffects.size();
7363 for (size_t i = 0; i < size; i++) {
7364 mEffects[i]->setMode(mode);
7365 }
7366}
7367
Eric Laurentcab11242010-07-15 12:50:15 -07007368// setVolume_l() must be called with PlaybackThread::mLock held
7369bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370{
7371 uint32_t newLeft = *left;
7372 uint32_t newRight = *right;
7373 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007374 int ctrlIdx = -1;
7375 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376
Eric Laurentcab11242010-07-15 12:50:15 -07007377 // first update volume controller
7378 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007379 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007380 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7381 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007382 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007383 break;
7384 }
7385 }
7386
7387 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007388 if (hasControl) {
7389 *left = mNewLeftVolume;
7390 *right = mNewRightVolume;
7391 }
7392 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007393 }
7394
7395 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007396 mLeftVolume = newLeft;
7397 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007398
7399 // second get volume update from volume controller
7400 if (ctrlIdx >= 0) {
7401 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007402 mNewLeftVolume = newLeft;
7403 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007404 }
7405 // then indicate volume to all other effects in chain.
7406 // Pass altered volume to effects before volume controller
7407 // and requested volume to effects after controller
7408 uint32_t lVol = newLeft;
7409 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007410
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007412 if ((int)i == ctrlIdx) continue;
7413 // this also works for ctrlIdx == -1 when there is no volume controller
7414 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 lVol = *left;
7416 rVol = *right;
7417 }
7418 mEffects[i]->setVolume(&lVol, &rVol, false);
7419 }
7420 *left = newLeft;
7421 *right = newRight;
7422
7423 return hasControl;
7424}
7425
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7427{
7428 const size_t SIZE = 256;
7429 char buffer[SIZE];
7430 String8 result;
7431
7432 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7433 result.append(buffer);
7434
7435 bool locked = tryLock(mLock);
7436 // failed to lock - AudioFlinger is probably deadlocked
7437 if (!locked) {
7438 result.append("\tCould not lock mutex:\n");
7439 }
7440
Eric Laurentcab11242010-07-15 12:50:15 -07007441 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7442 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007443 mEffects.size(),
7444 (uint32_t)mInBuffer,
7445 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446 mActiveTrackCnt);
7447 result.append(buffer);
7448 write(fd, result.string(), result.size());
7449
7450 for (size_t i = 0; i < mEffects.size(); ++i) {
7451 sp<EffectModule> effect = mEffects[i];
7452 if (effect != 0) {
7453 effect->dump(fd, args);
7454 }
7455 }
7456
7457 if (locked) {
7458 mLock.unlock();
7459 }
7460
7461 return NO_ERROR;
7462}
7463
Eric Laurent59255e42011-07-27 19:49:51 -07007464// must be called with ThreadBase::mLock held
7465void AudioFlinger::EffectChain::setEffectSuspended_l(
7466 const effect_uuid_t *type, bool suspend)
7467{
7468 sp<SuspendedEffectDesc> desc;
7469 // use effect type UUID timelow as key as there is no real risk of identical
7470 // timeLow fields among effect type UUIDs.
7471 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7472 if (suspend) {
7473 if (index >= 0) {
7474 desc = mSuspendedEffects.valueAt(index);
7475 } else {
7476 desc = new SuspendedEffectDesc();
7477 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7478 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007479 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007480 }
7481 if (desc->mRefCount++ == 0) {
7482 sp<EffectModule> effect = getEffectIfEnabled(type);
7483 if (effect != 0) {
7484 desc->mEffect = effect;
7485 effect->setSuspended(true);
7486 effect->setEnabled(false);
7487 }
7488 }
7489 } else {
7490 if (index < 0) {
7491 return;
7492 }
7493 desc = mSuspendedEffects.valueAt(index);
7494 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007495 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007496 desc->mRefCount = 1;
7497 }
7498 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007499 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007500 if (desc->mEffect != 0) {
7501 sp<EffectModule> effect = desc->mEffect.promote();
7502 if (effect != 0) {
7503 effect->setSuspended(false);
7504 sp<EffectHandle> handle = effect->controlHandle();
7505 if (handle != 0) {
7506 effect->setEnabled(handle->enabled());
7507 }
7508 }
7509 desc->mEffect.clear();
7510 }
7511 mSuspendedEffects.removeItemsAt(index);
7512 }
7513 }
7514}
7515
7516// must be called with ThreadBase::mLock held
7517void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7518{
7519 sp<SuspendedEffectDesc> desc;
7520
7521 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7522 if (suspend) {
7523 if (index >= 0) {
7524 desc = mSuspendedEffects.valueAt(index);
7525 } else {
7526 desc = new SuspendedEffectDesc();
7527 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007528 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007529 }
7530 if (desc->mRefCount++ == 0) {
7531 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7532 for (size_t i = 0; i < effects.size(); i++) {
7533 setEffectSuspended_l(&effects[i]->desc().type, true);
7534 }
7535 }
7536 } else {
7537 if (index < 0) {
7538 return;
7539 }
7540 desc = mSuspendedEffects.valueAt(index);
7541 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007542 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007543 desc->mRefCount = 1;
7544 }
7545 if (--desc->mRefCount == 0) {
7546 Vector<const effect_uuid_t *> types;
7547 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7548 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7549 continue;
7550 }
7551 types.add(&mSuspendedEffects.valueAt(i)->mType);
7552 }
7553 for (size_t i = 0; i < types.size(); i++) {
7554 setEffectSuspended_l(types[i], false);
7555 }
Steve Block3856b092011-10-20 11:56:00 +01007556 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007557 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7558 }
7559 }
7560}
7561
Eric Laurent6bffdb82011-09-23 08:40:41 -07007562
7563// The volume effect is used for automated tests only
7564#ifndef OPENSL_ES_H_
7565static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7566 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7567const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7568#endif //OPENSL_ES_H_
7569
Eric Laurentdb7c0792011-08-10 10:37:50 -07007570bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7571{
7572 // auxiliary effects and visualizer are never suspended on output mix
7573 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7574 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007575 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7576 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007577 return false;
7578 }
7579 return true;
7580}
7581
Eric Laurent59255e42011-07-27 19:49:51 -07007582Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7583{
7584 Vector< sp<EffectModule> > effects;
7585 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007586 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007587 continue;
7588 }
7589 effects.add(mEffects[i]);
7590 }
7591 return effects;
7592}
7593
7594sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7595 const effect_uuid_t *type)
7596{
7597 sp<EffectModule> effect;
7598 effect = getEffectFromType_l(type);
7599 if (effect != 0 && !effect->isEnabled()) {
7600 effect.clear();
7601 }
7602 return effect;
7603}
7604
7605void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7606 bool enabled)
7607{
7608 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7609 if (enabled) {
7610 if (index < 0) {
7611 // if the effect is not suspend check if all effects are suspended
7612 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7613 if (index < 0) {
7614 return;
7615 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007616 if (!isEffectEligibleForSuspend(effect->desc())) {
7617 return;
7618 }
Eric Laurent59255e42011-07-27 19:49:51 -07007619 setEffectSuspended_l(&effect->desc().type, enabled);
7620 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007621 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007622 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007623 return;
7624 }
Eric Laurent59255e42011-07-27 19:49:51 -07007625 }
Steve Block3856b092011-10-20 11:56:00 +01007626 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007627 effect->desc().type.timeLow);
7628 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7629 // if effect is requested to suspended but was not yet enabled, supend it now.
7630 if (desc->mEffect == 0) {
7631 desc->mEffect = effect;
7632 effect->setEnabled(false);
7633 effect->setSuspended(true);
7634 }
7635 } else {
7636 if (index < 0) {
7637 return;
7638 }
Steve Block3856b092011-10-20 11:56:00 +01007639 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007640 effect->desc().type.timeLow);
7641 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7642 desc->mEffect.clear();
7643 effect->setSuspended(false);
7644 }
7645}
7646
Mathias Agopian65ab4712010-07-14 17:59:35 -07007647#undef LOG_TAG
7648#define LOG_TAG "AudioFlinger"
7649
7650// ----------------------------------------------------------------------------
7651
7652status_t AudioFlinger::onTransact(
7653 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7654{
7655 return BnAudioFlinger::onTransact(code, data, reply, flags);
7656}
7657
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658}; // namespace android