blob: a03f2eaf6626ac7dd13690427867615402d6e312 [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;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -080075static const uint32_t MAX_GAIN_INT = 0x1000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070076
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{
Glenn Kastenf1d45922012-01-13 15:54:24 -0800334 if (!checkCallingPermission(String16("android.permission.DUMP"))) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335 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
Glenn Kastenf78aee72012-01-04 11:00:47 -0800568status_t AudioFlinger::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569{
Eric Laurenta1884f92011-08-23 08:25:03 -0700570 status_t ret = initCheck();
571 if (ret != NO_ERROR) {
572 return ret;
573 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574
575 // check calling permissions
576 if (!settingsAllowed()) {
577 return PERMISSION_DENIED;
578 }
Glenn Kasten930f4ca2012-01-06 16:47:31 -0800579 if (uint32_t(mode) >= AUDIO_MODE_CNT) {
Steve Block5ff1dd52012-01-05 23:22:43 +0000580 ALOGW("Illegal value: setMode(%d)", mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 return BAD_VALUE;
582 }
583
584 { // scope for the lock
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700587 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 mHardwareStatus = AUDIO_HW_IDLE;
589 }
590
591 if (NO_ERROR == ret) {
592 Mutex::Autolock _l(mLock);
593 mMode = mode;
594 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
595 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 }
597
598 return ret;
599}
600
601status_t AudioFlinger::setMicMute(bool state)
602{
Eric Laurenta1884f92011-08-23 08:25:03 -0700603 status_t ret = initCheck();
604 if (ret != NO_ERROR) {
605 return ret;
606 }
607
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 // check calling permissions
609 if (!settingsAllowed()) {
610 return PERMISSION_DENIED;
611 }
612
613 AutoMutex lock(mHardwareLock);
614 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700615 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700616 mHardwareStatus = AUDIO_HW_IDLE;
617 return ret;
618}
619
620bool AudioFlinger::getMicMute() const
621{
Eric Laurenta1884f92011-08-23 08:25:03 -0700622 status_t ret = initCheck();
623 if (ret != NO_ERROR) {
624 return false;
625 }
626
Dima Zavinfce7a472011-04-19 22:30:36 -0700627 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700629 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700630 mHardwareStatus = AUDIO_HW_IDLE;
631 return state;
632}
633
634status_t AudioFlinger::setMasterMute(bool muted)
635{
636 // check calling permissions
637 if (!settingsAllowed()) {
638 return PERMISSION_DENIED;
639 }
640
Eric Laurent93575202011-01-18 18:39:02 -0800641 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700642 mMasterMute = muted;
643 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
644 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
645
646 return NO_ERROR;
647}
648
649float AudioFlinger::masterVolume() const
650{
Glenn Kasten98067102011-12-13 11:47:54 -0800651 Mutex::Autolock _l(mLock);
652 return masterVolume_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653}
654
655bool AudioFlinger::masterMute() const
656{
Glenn Kasten98067102011-12-13 11:47:54 -0800657 Mutex::Autolock _l(mLock);
658 return masterMute_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700659}
660
Glenn 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
Glenn Kastenf1d45922012-01-13 15:54:24 -08001965 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001966 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;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002193 uint32_t vlr = cblk->volumeLR;
2194 vl = vlr & 0xFFFF;
2195 vr = vlr >> 16;
2196 // track volumes come from shared memory, so can't be trusted and must be clamped
2197 if (vl > MAX_GAIN_INT) {
2198 ALOGV("Track left volume out of range: %04X", vl);
2199 vl = MAX_GAIN_INT;
2200 }
2201 if (vr > MAX_GAIN_INT) {
2202 ALOGV("Track right volume out of range: %04X", vr);
2203 vr = MAX_GAIN_INT;
2204 }
2205 // now apply the master volume and stream type volume
2206 vl = (uint32_t)(v * vl) << 12;
2207 vr = (uint32_t)(v * vr) << 12;
2208 // assuming master volume and stream type volume each go up to 1.0,
2209 // vl and vr are now in 8.24 format
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210
Glenn Kasten05632a52012-01-03 14:22:33 -08002211 uint16_t sendLevel = cblk->getSendLevel_U4_12();
2212 // send level comes from shared memory and so may be corrupt
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002213 if (sendLevel >= MAX_GAIN_INT) {
Glenn Kasten05632a52012-01-03 14:22:33 -08002214 ALOGV("Track send level out of range: %04X", sendLevel);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002215 sendLevel = MAX_GAIN_INT;
Glenn Kasten05632a52012-01-03 14:22:33 -08002216 }
2217 va = (uint32_t)(v * sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002219 // Delegate volume control to effect in track effect chain if needed
2220 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2221 // Do not ramp volume if volume is controlled by effect
2222 param = AudioMixer::VOLUME;
2223 track->mHasVolumeController = true;
2224 } else {
2225 // force no volume ramp when volume controller was just disabled or removed
2226 // from effect chain to avoid volume spike
2227 if (track->mHasVolumeController) {
2228 param = AudioMixer::VOLUME;
2229 }
2230 track->mHasVolumeController = false;
2231 }
2232
2233 // Convert volumes from 8.24 to 4.12 format
2234 int16_t left, right, aux;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002235 // This additional clamping is needed in case chain->setVolume_l() overshot
Eric Laurente0aed6d2010-09-10 17:44:44 -07002236 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2237 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2238 left = int16_t(v_clamped);
2239 v_clamped = (vr + (1 << 11)) >> 12;
2240 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2241 right = int16_t(v_clamped);
2242
2243 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2244 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245
Mathias Agopian65ab4712010-07-14 17:59:35 -07002246 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002247 mAudioMixer->setBufferProvider(name, track);
2248 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002250 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2251 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2252 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002253 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002254 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 AudioMixer::TRACK,
2256 AudioMixer::FORMAT, (void *)track->format());
2257 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002258 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002259 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002260 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002262 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 AudioMixer::RESAMPLE,
2264 AudioMixer::SAMPLE_RATE,
2265 (void *)(cblk->sampleRate));
2266 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002267 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002268 AudioMixer::TRACK,
2269 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2270 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002271 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002272 AudioMixer::TRACK,
2273 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2274
2275 // reset retry count
2276 track->mRetryCount = kMaxTrackRetries;
2277 mixerStatus = MIXER_TRACKS_READY;
2278 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002279 //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 -07002280 if (track->isStopped()) {
2281 track->reset();
2282 }
2283 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2284 // We have consumed all the buffers of this track.
2285 // Remove it from the list of active tracks.
2286 tracksToRemove->add(track);
2287 } else {
2288 // No buffers for this track. Give it a few chances to
2289 // fill a buffer, then remove it from active list.
2290 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002291 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002293 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002294 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 } else if (mixerStatus != MIXER_TRACKS_READY) {
2296 mixerStatus = MIXER_TRACKS_ENABLED;
2297 }
2298 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002299 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002300 }
2301 }
2302
2303 // remove all the tracks that need to be...
2304 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002305 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 for (size_t i=0 ; i<count ; i++) {
2307 const sp<Track>& track = tracksToRemove->itemAt(i);
2308 mActiveTracks.remove(track);
2309 if (track->mainBuffer() != mMixBuffer) {
2310 chain = getEffectChain_l(track->sessionId());
2311 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002312 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002313 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002314 }
2315 }
2316 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002317 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002318 }
2319 }
2320 }
2321
2322 // mix buffer must be cleared if all tracks are connected to an
2323 // effect chain as in this case the mixer will not write to
2324 // mix buffer and track effects will accumulate into it
2325 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2326 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2327 }
2328
2329 return mixerStatus;
2330}
2331
Glenn Kastenfff6d712012-01-12 16:38:12 -08002332void AudioFlinger::MixerThread::invalidateTracks(audio_stream_type_t streamType)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002333{
Steve Block3856b092011-10-20 11:56:00 +01002334 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002335 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002337
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 size_t size = mTracks.size();
2339 for (size_t i = 0; i < size; i++) {
2340 sp<Track> t = mTracks[i];
2341 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002342 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002343 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002344 }
2345 }
2346}
2347
Glenn Kastenfff6d712012-01-12 16:38:12 -08002348void AudioFlinger::PlaybackThread::setStreamValid(audio_stream_type_t streamType, bool valid)
Eric Laurent9f6530f2011-08-30 10:18:54 -07002349{
Steve Block3856b092011-10-20 11:56:00 +01002350 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002351 this, streamType, valid);
2352 Mutex::Autolock _l(mLock);
2353
2354 mStreamTypes[streamType].valid = valid;
2355}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356
2357// getTrackName_l() must be called with ThreadBase::mLock held
2358int AudioFlinger::MixerThread::getTrackName_l()
2359{
2360 return mAudioMixer->getTrackName();
2361}
2362
2363// deleteTrackName_l() must be called with ThreadBase::mLock held
2364void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2365{
Steve Block3856b092011-10-20 11:56:00 +01002366 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002367 mAudioMixer->deleteTrackName(name);
2368}
2369
2370// checkForNewParameters_l() must be called with ThreadBase::mLock held
2371bool AudioFlinger::MixerThread::checkForNewParameters_l()
2372{
2373 bool reconfig = false;
2374
2375 while (!mNewParameters.isEmpty()) {
2376 status_t status = NO_ERROR;
2377 String8 keyValuePair = mNewParameters[0];
2378 AudioParameter param = AudioParameter(keyValuePair);
2379 int value;
2380
2381 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2382 reconfig = true;
2383 }
2384 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002385 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 status = BAD_VALUE;
2387 } else {
2388 reconfig = true;
2389 }
2390 }
2391 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002392 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 status = BAD_VALUE;
2394 } else {
2395 reconfig = true;
2396 }
2397 }
2398 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2399 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002400 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 // if frame count is changed after track creation
2402 if (!mTracks.isEmpty()) {
2403 status = INVALID_OPERATION;
2404 } else {
2405 reconfig = true;
2406 }
2407 }
2408 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002409 // when changing the audio output device, call addBatteryData to notify
2410 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002411 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002412 uint32_t params = 0;
2413 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002414 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002415 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2416 }
2417
2418 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002419 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002420 // check if any other device (except speaker) is on
2421 if (value & deviceWithoutSpeaker ) {
2422 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2423 }
2424
2425 if (params != 0) {
2426 addBatteryData(params);
2427 }
2428 }
2429
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430 // forward device change to effects that have requested to be
2431 // aware of attached audio device.
2432 mDevice = (uint32_t)value;
2433 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002434 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
2436 }
2437
2438 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002439 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002440 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002442 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002443 mStandby = true;
2444 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002445 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002446 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002447 }
2448 if (status == NO_ERROR && reconfig) {
2449 delete mAudioMixer;
2450 readOutputParameters();
2451 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2452 for (size_t i = 0; i < mTracks.size() ; i++) {
2453 int name = getTrackName_l();
2454 if (name < 0) break;
2455 mTracks[i]->mName = name;
2456 // limit track sample rate to 2 x new output sample rate
2457 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2458 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2459 }
2460 }
2461 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2462 }
2463 }
2464
2465 mNewParameters.removeAt(0);
2466
2467 mParamStatus = status;
2468 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002469 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2470 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002471 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 }
2473 return reconfig;
2474}
2475
2476status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2477{
2478 const size_t SIZE = 256;
2479 char buffer[SIZE];
2480 String8 result;
2481
2482 PlaybackThread::dumpInternals(fd, args);
2483
2484 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2485 result.append(buffer);
2486 write(fd, result.string(), result.size());
2487 return NO_ERROR;
2488}
2489
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2491{
Eric Laurent60e18242010-07-29 06:50:24 -07002492 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493}
2494
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002495uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2496{
2497 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2498}
2499
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002501AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 : PlaybackThread(audioFlinger, output, id, device)
2503{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002504 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505}
2506
2507AudioFlinger::DirectOutputThread::~DirectOutputThread()
2508{
2509}
2510
Mathias Agopian65ab4712010-07-14 17:59:35 -07002511static inline
2512int32_t mul(int16_t in, int16_t v)
2513{
2514#if defined(__arm__) && !defined(__thumb__)
2515 int32_t out;
2516 asm( "smulbb %[out], %[in], %[v] \n"
2517 : [out]"=r"(out)
2518 : [in]"%r"(in), [v]"r"(v)
2519 : );
2520 return out;
2521#else
2522 return in * int32_t(v);
2523#endif
2524}
2525
2526void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2527{
2528 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002529 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002530 return;
2531 }
2532
2533 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002534 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002535 size_t count = mFrameCount * mChannelCount;
2536 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2537 int16_t *dst = mMixBuffer + count-1;
2538 while(count--) {
2539 *dst-- = (int16_t)(*src--^0x80) << 8;
2540 }
2541 }
2542
2543 size_t frameCount = mFrameCount;
2544 int16_t *out = mMixBuffer;
2545 if (ramp) {
2546 if (mChannelCount == 1) {
2547 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2548 int32_t vlInc = d / (int32_t)frameCount;
2549 int32_t vl = ((int32_t)mLeftVolShort << 16);
2550 do {
2551 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2552 out++;
2553 vl += vlInc;
2554 } while (--frameCount);
2555
2556 } else {
2557 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2558 int32_t vlInc = d / (int32_t)frameCount;
2559 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2560 int32_t vrInc = d / (int32_t)frameCount;
2561 int32_t vl = ((int32_t)mLeftVolShort << 16);
2562 int32_t vr = ((int32_t)mRightVolShort << 16);
2563 do {
2564 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2565 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2566 out += 2;
2567 vl += vlInc;
2568 vr += vrInc;
2569 } while (--frameCount);
2570 }
2571 } else {
2572 if (mChannelCount == 1) {
2573 do {
2574 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2575 out++;
2576 } while (--frameCount);
2577 } else {
2578 do {
2579 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2580 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2581 out += 2;
2582 } while (--frameCount);
2583 }
2584 }
2585
2586 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002587 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 size_t count = mFrameCount * mChannelCount;
2589 int16_t *src = mMixBuffer;
2590 uint8_t *dst = (uint8_t *)mMixBuffer;
2591 while(count--) {
2592 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2593 }
2594 }
2595
2596 mLeftVolShort = leftVol;
2597 mRightVolShort = rightVol;
2598}
2599
2600bool AudioFlinger::DirectOutputThread::threadLoop()
2601{
2602 uint32_t mixerStatus = MIXER_IDLE;
2603 sp<Track> trackToRemove;
2604 sp<Track> activeTrack;
2605 nsecs_t standbyTime = systemTime();
2606 int8_t *curBuf;
2607 size_t mixBufferSize = mFrameCount*mFrameSize;
2608 uint32_t activeSleepTime = activeSleepTimeUs();
2609 uint32_t idleSleepTime = idleSleepTimeUs();
2610 uint32_t sleepTime = idleSleepTime;
2611 // use shorter standby delay as on normal output to release
2612 // hardware resources as soon as possible
2613 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2614
Eric Laurentfeb0db62011-07-22 09:04:31 -07002615 acquireWakeLock();
2616
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 while (!exitPending())
2618 {
2619 bool rampVolume;
2620 uint16_t leftVol;
2621 uint16_t rightVol;
2622 Vector< sp<EffectChain> > effectChains;
2623
2624 processConfigEvents();
2625
2626 mixerStatus = MIXER_IDLE;
2627
2628 { // scope for the mLock
2629
2630 Mutex::Autolock _l(mLock);
2631
2632 if (checkForNewParameters_l()) {
2633 mixBufferSize = mFrameCount*mFrameSize;
2634 activeSleepTime = activeSleepTimeUs();
2635 idleSleepTime = idleSleepTimeUs();
2636 standbyDelay = microseconds(activeSleepTime*2);
2637 }
2638
2639 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002640 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2641 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642 // wait until we have something to do...
2643 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002644 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002645 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 mStandby = true;
2647 mBytesWritten = 0;
2648 }
2649
2650 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2651 // we're about to wait, flush the binder command buffer
2652 IPCThreadState::self()->flushCommands();
2653
2654 if (exitPending()) break;
2655
Eric Laurentfeb0db62011-07-22 09:04:31 -07002656 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002657 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002658 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002659 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002660 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661
Glenn Kastenf1d45922012-01-13 15:54:24 -08002662 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 char value[PROPERTY_VALUE_MAX];
2664 property_get("ro.audio.silent", value, "0");
2665 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002666 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 setMasterMute(true);
2668 }
2669 }
2670
2671 standbyTime = systemTime() + standbyDelay;
2672 sleepTime = idleSleepTime;
2673 continue;
2674 }
2675 }
2676
2677 effectChains = mEffectChains;
2678
2679 // find out which tracks need to be processed
2680 if (mActiveTracks.size() != 0) {
2681 sp<Track> t = mActiveTracks[0].promote();
2682 if (t == 0) continue;
2683
2684 Track* const track = t.get();
2685 audio_track_cblk_t* cblk = track->cblk();
2686
2687 // The first time a track is added we wait
2688 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002689 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 !track->isPaused() && !track->isTerminated())
2691 {
Steve Block3856b092011-10-20 11:56:00 +01002692 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693
2694 if (track->mFillingUpStatus == Track::FS_FILLED) {
2695 track->mFillingUpStatus = Track::FS_ACTIVE;
2696 mLeftVolFloat = mRightVolFloat = 0;
2697 mLeftVolShort = mRightVolShort = 0;
2698 if (track->mState == TrackBase::RESUMING) {
2699 track->mState = TrackBase::ACTIVE;
2700 rampVolume = true;
2701 }
2702 } else if (cblk->server != 0) {
2703 // If the track is stopped before the first frame was mixed,
2704 // do not apply ramp
2705 rampVolume = true;
2706 }
2707 // compute volume for this track
2708 float left, right;
2709 if (track->isMuted() || mMasterMute || track->isPausing() ||
2710 mStreamTypes[track->type()].mute) {
2711 left = right = 0;
2712 if (track->isPausing()) {
2713 track->setPaused();
2714 }
2715 } else {
2716 float typeVolume = mStreamTypes[track->type()].volume;
2717 float v = mMasterVolume * typeVolume;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002718 uint32_t vlr = cblk->volumeLR;
2719 float v_clamped = v * (vlr & 0xFFFF);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002720 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2721 left = v_clamped/MAX_GAIN;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08002722 v_clamped = v * (vlr >> 16);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002723 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2724 right = v_clamped/MAX_GAIN;
2725 }
2726
2727 if (left != mLeftVolFloat || right != mRightVolFloat) {
2728 mLeftVolFloat = left;
2729 mRightVolFloat = right;
2730
2731 // If audio HAL implements volume control,
2732 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002733 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002734 left = 1.0f;
2735 right = 1.0f;
2736 }
2737
2738 // Convert volumes from float to 8.24
2739 uint32_t vl = (uint32_t)(left * (1 << 24));
2740 uint32_t vr = (uint32_t)(right * (1 << 24));
2741
2742 // Delegate volume control to effect in track effect chain if needed
2743 // only one effect chain can be present on DirectOutputThread, so if
2744 // there is one, the track is connected to it
2745 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002746 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002747 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748 rampVolume = false;
2749 }
2750 }
2751
2752 // Convert volumes from 8.24 to 4.12 format
2753 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2754 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2755 leftVol = (uint16_t)v_clamped;
2756 v_clamped = (vr + (1 << 11)) >> 12;
2757 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2758 rightVol = (uint16_t)v_clamped;
2759 } else {
2760 leftVol = mLeftVolShort;
2761 rightVol = mRightVolShort;
2762 rampVolume = false;
2763 }
2764
2765 // reset retry count
2766 track->mRetryCount = kMaxTrackRetriesDirect;
2767 activeTrack = t;
2768 mixerStatus = MIXER_TRACKS_READY;
2769 } else {
Steve Block3856b092011-10-20 11:56:00 +01002770 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 if (track->isStopped()) {
2772 track->reset();
2773 }
2774 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2775 // We have consumed all the buffers of this track.
2776 // Remove it from the list of active tracks.
2777 trackToRemove = track;
2778 } else {
2779 // No buffers for this track. Give it a few chances to
2780 // fill a buffer, then remove it from active list.
2781 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002782 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783 trackToRemove = track;
2784 } else {
2785 mixerStatus = MIXER_TRACKS_ENABLED;
2786 }
2787 }
2788 }
2789 }
2790
2791 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002792 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 mActiveTracks.remove(trackToRemove);
2794 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002795 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002796 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002797 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002798 }
2799 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002800 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002801 }
2802 }
2803
Eric Laurentde070132010-07-13 04:45:46 -07002804 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 }
2806
Glenn Kastenf6b16782011-12-15 09:51:17 -08002807 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 AudioBufferProvider::Buffer buffer;
2809 size_t frameCount = mFrameCount;
2810 curBuf = (int8_t *)mMixBuffer;
2811 // output audio to hardware
2812 while (frameCount) {
2813 buffer.frameCount = frameCount;
2814 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002815 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002816 memset(curBuf, 0, frameCount * mFrameSize);
2817 break;
2818 }
2819 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2820 frameCount -= buffer.frameCount;
2821 curBuf += buffer.frameCount * mFrameSize;
2822 activeTrack->releaseBuffer(&buffer);
2823 }
2824 sleepTime = 0;
2825 standbyTime = systemTime() + standbyDelay;
2826 } else {
2827 if (sleepTime == 0) {
2828 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2829 sleepTime = activeSleepTime;
2830 } else {
2831 sleepTime = idleSleepTime;
2832 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002833 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2835 sleepTime = 0;
2836 }
2837 }
2838
2839 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002840 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002841 }
2842 // sleepTime == 0 means we must write to audio hardware
2843 if (sleepTime == 0) {
2844 if (mixerStatus == MIXER_TRACKS_READY) {
2845 applyVolume(leftVol, rightVol, rampVolume);
2846 }
2847 for (size_t i = 0; i < effectChains.size(); i ++) {
2848 effectChains[i]->process_l();
2849 }
Eric Laurentde070132010-07-13 04:45:46 -07002850 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851
2852 mLastWriteTime = systemTime();
2853 mInWrite = true;
2854 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002855 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2857 mNumWrites++;
2858 mInWrite = false;
2859 mStandby = false;
2860 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002861 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862 usleep(sleepTime);
2863 }
2864
2865 // finally let go of removed track, without the lock held
2866 // since we can't guarantee the destructors won't acquire that
2867 // same lock.
2868 trackToRemove.clear();
2869 activeTrack.clear();
2870
2871 // Effect chains will be actually deleted here if they were removed from
2872 // mEffectChains list during mixing or effects processing
2873 effectChains.clear();
2874 }
2875
2876 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002877 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002878 }
2879
Eric Laurentfeb0db62011-07-22 09:04:31 -07002880 releaseWakeLock();
2881
Steve Block3856b092011-10-20 11:56:00 +01002882 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 return false;
2884}
2885
2886// getTrackName_l() must be called with ThreadBase::mLock held
2887int AudioFlinger::DirectOutputThread::getTrackName_l()
2888{
2889 return 0;
2890}
2891
2892// deleteTrackName_l() must be called with ThreadBase::mLock held
2893void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2894{
2895}
2896
2897// checkForNewParameters_l() must be called with ThreadBase::mLock held
2898bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2899{
2900 bool reconfig = false;
2901
2902 while (!mNewParameters.isEmpty()) {
2903 status_t status = NO_ERROR;
2904 String8 keyValuePair = mNewParameters[0];
2905 AudioParameter param = AudioParameter(keyValuePair);
2906 int value;
2907
2908 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2909 // do not accept frame count changes if tracks are open as the track buffer
2910 // size depends on frame count and correct behavior would not be garantied
2911 // if frame count is changed after track creation
2912 if (!mTracks.isEmpty()) {
2913 status = INVALID_OPERATION;
2914 } else {
2915 reconfig = true;
2916 }
2917 }
2918 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002919 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002920 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002921 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002922 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 mStandby = true;
2924 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002925 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002926 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 }
2928 if (status == NO_ERROR && reconfig) {
2929 readOutputParameters();
2930 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2931 }
2932 }
2933
2934 mNewParameters.removeAt(0);
2935
2936 mParamStatus = status;
2937 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002938 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2939 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002940 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 }
2942 return reconfig;
2943}
2944
2945uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2946{
2947 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002948 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002949 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002950 } else {
2951 time = 10000;
2952 }
2953 return time;
2954}
2955
2956uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2957{
2958 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002959 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002960 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002961 } else {
2962 time = 10000;
2963 }
2964 return time;
2965}
2966
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002967uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2968{
2969 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002970 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002971 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2972 } else {
2973 time = 10000;
2974 }
2975 return time;
2976}
2977
2978
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979// ----------------------------------------------------------------------------
2980
2981AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2982 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2983{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002984 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985 addOutputTrack(mainThread);
2986}
2987
2988AudioFlinger::DuplicatingThread::~DuplicatingThread()
2989{
2990 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2991 mOutputTracks[i]->destroy();
2992 }
2993 mOutputTracks.clear();
2994}
2995
2996bool AudioFlinger::DuplicatingThread::threadLoop()
2997{
2998 Vector< sp<Track> > tracksToRemove;
2999 uint32_t mixerStatus = MIXER_IDLE;
3000 nsecs_t standbyTime = systemTime();
3001 size_t mixBufferSize = mFrameCount*mFrameSize;
3002 SortedVector< sp<OutputTrack> > outputTracks;
3003 uint32_t writeFrames = 0;
3004 uint32_t activeSleepTime = activeSleepTimeUs();
3005 uint32_t idleSleepTime = idleSleepTimeUs();
3006 uint32_t sleepTime = idleSleepTime;
3007 Vector< sp<EffectChain> > effectChains;
3008
Eric Laurentfeb0db62011-07-22 09:04:31 -07003009 acquireWakeLock();
3010
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 while (!exitPending())
3012 {
3013 processConfigEvents();
3014
3015 mixerStatus = MIXER_IDLE;
3016 { // scope for the mLock
3017
3018 Mutex::Autolock _l(mLock);
3019
3020 if (checkForNewParameters_l()) {
3021 mixBufferSize = mFrameCount*mFrameSize;
3022 updateWaitTime();
3023 activeSleepTime = activeSleepTimeUs();
3024 idleSleepTime = idleSleepTimeUs();
3025 }
3026
3027 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3028
3029 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3030 outputTracks.add(mOutputTracks[i]);
3031 }
3032
3033 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08003034 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3035 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003036 if (!mStandby) {
3037 for (size_t i = 0; i < outputTracks.size(); i++) {
3038 outputTracks[i]->stop();
3039 }
3040 mStandby = true;
3041 mBytesWritten = 0;
3042 }
3043
3044 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3045 // we're about to wait, flush the binder command buffer
3046 IPCThreadState::self()->flushCommands();
3047 outputTracks.clear();
3048
3049 if (exitPending()) break;
3050
Eric Laurentfeb0db62011-07-22 09:04:31 -07003051 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003052 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003054 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003055 acquireWakeLock_l();
3056
Glenn Kastenf1d45922012-01-13 15:54:24 -08003057 if (!mMasterMute) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 char value[PROPERTY_VALUE_MAX];
3059 property_get("ro.audio.silent", value, "0");
3060 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003061 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 setMasterMute(true);
3063 }
3064 }
3065
3066 standbyTime = systemTime() + kStandbyTimeInNsecs;
3067 sleepTime = idleSleepTime;
3068 continue;
3069 }
3070 }
3071
3072 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3073
3074 // prevent any changes in effect chain list and in each effect chain
3075 // during mixing and effect process as the audio buffers could be deleted
3076 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003077 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 }
3079
Glenn Kastenf6b16782011-12-15 09:51:17 -08003080 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 // mix buffers...
3082 if (outputsReady(outputTracks)) {
3083 mAudioMixer->process();
3084 } else {
3085 memset(mMixBuffer, 0, mixBufferSize);
3086 }
3087 sleepTime = 0;
3088 writeFrames = mFrameCount;
3089 } else {
3090 if (sleepTime == 0) {
3091 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3092 sleepTime = activeSleepTime;
3093 } else {
3094 sleepTime = idleSleepTime;
3095 }
3096 } else if (mBytesWritten != 0) {
3097 // flush remaining overflow buffers in output tracks
3098 for (size_t i = 0; i < outputTracks.size(); i++) {
3099 if (outputTracks[i]->isActive()) {
3100 sleepTime = 0;
3101 writeFrames = 0;
3102 memset(mMixBuffer, 0, mixBufferSize);
3103 break;
3104 }
3105 }
3106 }
3107 }
3108
3109 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003110 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111 }
3112 // sleepTime == 0 means we must write to audio hardware
3113 if (sleepTime == 0) {
3114 for (size_t i = 0; i < effectChains.size(); i ++) {
3115 effectChains[i]->process_l();
3116 }
3117 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003118 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003119
3120 standbyTime = systemTime() + kStandbyTimeInNsecs;
3121 for (size_t i = 0; i < outputTracks.size(); i++) {
3122 outputTracks[i]->write(mMixBuffer, writeFrames);
3123 }
3124 mStandby = false;
3125 mBytesWritten += mixBufferSize;
3126 } else {
3127 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003128 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003129 usleep(sleepTime);
3130 }
3131
3132 // finally let go of all our tracks, without the lock held
3133 // since we can't guarantee the destructors won't acquire that
3134 // same lock.
3135 tracksToRemove.clear();
3136 outputTracks.clear();
3137
3138 // Effect chains will be actually deleted here if they were removed from
3139 // mEffectChains list during mixing or effects processing
3140 effectChains.clear();
3141 }
3142
Eric Laurentfeb0db62011-07-22 09:04:31 -07003143 releaseWakeLock();
3144
Mathias Agopian65ab4712010-07-14 17:59:35 -07003145 return false;
3146}
3147
3148void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3149{
3150 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3151 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3152 this,
3153 mSampleRate,
3154 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003155 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003156 frameCount);
3157 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003158 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003160 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 updateWaitTime();
3162 }
3163}
3164
3165void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3166{
3167 Mutex::Autolock _l(mLock);
3168 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3169 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3170 mOutputTracks[i]->destroy();
3171 mOutputTracks.removeAt(i);
3172 updateWaitTime();
3173 return;
3174 }
3175 }
Steve Block3856b092011-10-20 11:56:00 +01003176 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177}
3178
3179void AudioFlinger::DuplicatingThread::updateWaitTime()
3180{
3181 mWaitTimeMs = UINT_MAX;
3182 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3183 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3184 if (strong != NULL) {
3185 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3186 if (waitTimeMs < mWaitTimeMs) {
3187 mWaitTimeMs = waitTimeMs;
3188 }
3189 }
3190 }
3191}
3192
3193
3194bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3195{
3196 for (size_t i = 0; i < outputTracks.size(); i++) {
3197 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3198 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00003199 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 return false;
3201 }
3202 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3203 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003204 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 return false;
3206 }
3207 }
3208 return true;
3209}
3210
3211uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3212{
3213 return (mWaitTimeMs * 1000) / 2;
3214}
3215
3216// ----------------------------------------------------------------------------
3217
3218// TrackBase constructor must be called with AudioFlinger::mLock held
3219AudioFlinger::ThreadBase::TrackBase::TrackBase(
3220 const wp<ThreadBase>& thread,
3221 const sp<Client>& client,
3222 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003223 uint32_t format,
3224 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 int frameCount,
3226 uint32_t flags,
3227 const sp<IMemory>& sharedBuffer,
3228 int sessionId)
3229 : RefBase(),
3230 mThread(thread),
3231 mClient(client),
3232 mCblk(0),
3233 mFrameCount(0),
3234 mState(IDLE),
3235 mClientTid(-1),
3236 mFormat(format),
3237 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3238 mSessionId(sessionId)
3239{
Steve Block3856b092011-10-20 11:56:00 +01003240 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241
Steve Blockb8a80522011-12-20 16:23:08 +00003242 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003243 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003244 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3246 if (sharedBuffer == 0) {
3247 size += bufferSize;
3248 }
3249
3250 if (client != NULL) {
3251 mCblkMemory = client->heap()->allocate(size);
3252 if (mCblkMemory != 0) {
3253 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3254 if (mCblk) { // construct the shared structure in-place.
3255 new(mCblk) audio_track_cblk_t();
3256 // clear all buffers
3257 mCblk->frameCount = frameCount;
3258 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003259 mChannelCount = channelCount;
3260 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 if (sharedBuffer == 0) {
3262 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3263 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3264 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003265 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 mCblk->flags = CBLK_UNDERRUN_ON;
3267 } else {
3268 mBuffer = sharedBuffer->pointer();
3269 }
3270 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3271 }
3272 } else {
Steve Block29357bc2012-01-06 19:20:56 +00003273 ALOGE("not enough memory for AudioTrack size=%u", size);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 client->heap()->dump("AudioTrack");
3275 return;
3276 }
3277 } else {
3278 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003279 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003280 new(mCblk) audio_track_cblk_t();
3281 // clear all buffers
3282 mCblk->frameCount = frameCount;
3283 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003284 mChannelCount = channelCount;
3285 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003286 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3287 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3288 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003289 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 mCblk->flags = CBLK_UNDERRUN_ON;
3291 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 }
3293}
3294
3295AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3296{
3297 if (mCblk) {
3298 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3299 if (mClient == NULL) {
3300 delete mCblk;
3301 }
3302 }
3303 mCblkMemory.clear(); // and free the shared memory
3304 if (mClient != NULL) {
3305 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3306 mClient.clear();
3307 }
3308}
3309
3310void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3311{
Glenn Kastene0feee32011-12-13 11:53:26 -08003312 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 mFrameCount = buffer->frameCount;
3314 step();
3315 buffer->frameCount = 0;
3316}
3317
3318bool AudioFlinger::ThreadBase::TrackBase::step() {
3319 bool result;
3320 audio_track_cblk_t* cblk = this->cblk();
3321
3322 result = cblk->stepServer(mFrameCount);
3323 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003324 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 mFlags |= STEPSERVER_FAILED;
3326 }
3327 return result;
3328}
3329
3330void AudioFlinger::ThreadBase::TrackBase::reset() {
3331 audio_track_cblk_t* cblk = this->cblk();
3332
3333 cblk->user = 0;
3334 cblk->server = 0;
3335 cblk->userBase = 0;
3336 cblk->serverBase = 0;
3337 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003338 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003339}
3340
3341sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3342{
3343 return mCblkMemory;
3344}
3345
3346int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3347 return (int)mCblk->sampleRate;
3348}
3349
3350int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003351 return (const int)mChannelCount;
3352}
3353
3354uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3355 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356}
3357
3358void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3359 audio_track_cblk_t* cblk = this->cblk();
Glenn Kastenb9980652012-01-11 09:48:27 -08003360 size_t frameSize = cblk->frameSize;
3361 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*frameSize;
3362 int8_t *bufferEnd = bufferStart + frames * frameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363
3364 // Check validity of returned pointer in case the track control block would have been corrupted.
3365 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
Glenn Kastenb9980652012-01-11 09:48:27 -08003366 ((unsigned long)bufferStart & (unsigned long)(frameSize - 1))) {
Steve Block29357bc2012-01-06 19:20:56 +00003367 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 -07003368 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003370 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003371 return 0;
3372 }
3373
3374 return bufferStart;
3375}
3376
3377// ----------------------------------------------------------------------------
3378
3379// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3380AudioFlinger::PlaybackThread::Track::Track(
3381 const wp<ThreadBase>& thread,
3382 const sp<Client>& client,
Glenn Kastenfff6d712012-01-12 16:38:12 -08003383 audio_stream_type_t streamType,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003384 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003385 uint32_t format,
3386 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 int frameCount,
3388 const sp<IMemory>& sharedBuffer,
3389 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003390 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003391 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3392 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393{
3394 if (mCblk != NULL) {
3395 sp<ThreadBase> baseThread = thread.promote();
3396 if (baseThread != 0) {
3397 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3398 mName = playbackThread->getTrackName_l();
3399 mMainBuffer = playbackThread->mixBuffer();
3400 }
Steve Block3856b092011-10-20 11:56:00 +01003401 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 if (mName < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00003403 ALOGE("no more track names available");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003404 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 mStreamType = streamType;
3406 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3407 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003408 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003409 }
3410}
3411
3412AudioFlinger::PlaybackThread::Track::~Track()
3413{
Steve Block3856b092011-10-20 11:56:00 +01003414 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 sp<ThreadBase> thread = mThread.promote();
3416 if (thread != 0) {
3417 Mutex::Autolock _l(thread->mLock);
3418 mState = TERMINATED;
3419 }
3420}
3421
3422void AudioFlinger::PlaybackThread::Track::destroy()
3423{
3424 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3425 // by removing it from mTracks vector, so there is a risk that this Tracks's
3426 // desctructor is called. As the destructor needs to lock mLock,
3427 // we must acquire a strong reference on this Track before locking mLock
3428 // here so that the destructor is called only when exiting this function.
3429 // On the other hand, as long as Track::destroy() is only called by
3430 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3431 // this Track with its member mTrack.
3432 sp<Track> keep(this);
3433 { // scope for mLock
3434 sp<ThreadBase> thread = mThread.promote();
3435 if (thread != 0) {
3436 if (!isOutputTrack()) {
3437 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003438 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003439 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003440 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003441
3442 // to track the speaker usage
3443 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 }
3445 AudioSystem::releaseOutput(thread->id());
3446 }
3447 Mutex::Autolock _l(thread->mLock);
3448 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3449 playbackThread->destroyTrack_l(this);
3450 }
3451 }
3452}
3453
3454void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3455{
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003456 uint32_t vlr = mCblk->volumeLR;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003457 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 -07003458 mName - AudioMixer::TRACK0,
3459 (mClient == NULL) ? getpid() : mClient->pid(),
3460 mStreamType,
3461 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003462 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003463 mSessionId,
3464 mFrameCount,
3465 mState,
3466 mMute,
3467 mFillingUpStatus,
3468 mCblk->sampleRate,
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003469 vlr & 0xFFFF,
3470 vlr >> 16,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 mCblk->server,
3472 mCblk->user,
3473 (int)mMainBuffer,
3474 (int)mAuxBuffer);
3475}
3476
3477status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3478{
3479 audio_track_cblk_t* cblk = this->cblk();
3480 uint32_t framesReady;
3481 uint32_t framesReq = buffer->frameCount;
3482
3483 // Check if last stepServer failed, try to step now
3484 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3485 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003486 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3488 }
3489
3490 framesReady = cblk->framesReady();
3491
Glenn Kastenf6b16782011-12-15 09:51:17 -08003492 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 uint32_t s = cblk->server;
3494 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3495
3496 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3497 if (framesReq > framesReady) {
3498 framesReq = framesReady;
3499 }
3500 if (s + framesReq > bufferEnd) {
3501 framesReq = bufferEnd - s;
3502 }
3503
3504 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003505 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506
3507 buffer->frameCount = framesReq;
3508 return NO_ERROR;
3509 }
3510
3511getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003512 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003514 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 return NOT_ENOUGH_DATA;
3516}
3517
3518bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003519 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520
3521 if (mCblk->framesReady() >= mCblk->frameCount ||
3522 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3523 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003524 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 return true;
3526 }
3527 return false;
3528}
3529
3530status_t AudioFlinger::PlaybackThread::Track::start()
3531{
3532 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003533 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003534 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 sp<ThreadBase> thread = mThread.promote();
3536 if (thread != 0) {
3537 Mutex::Autolock _l(thread->mLock);
3538 int state = mState;
3539 // here the track could be either new, or restarted
3540 // in both cases "unstop" the track
3541 if (mState == PAUSED) {
3542 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003543 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544 } else {
3545 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003546 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 }
3548
3549 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3550 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003551 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003552 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003553 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003555
3556 // to track the speaker usage
3557 if (status == NO_ERROR) {
3558 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3559 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 }
3561 if (status == NO_ERROR) {
3562 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3563 playbackThread->addTrack_l(this);
3564 } else {
3565 mState = state;
3566 }
3567 } else {
3568 status = BAD_VALUE;
3569 }
3570 return status;
3571}
3572
3573void AudioFlinger::PlaybackThread::Track::stop()
3574{
Steve Block3856b092011-10-20 11:56:00 +01003575 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 sp<ThreadBase> thread = mThread.promote();
3577 if (thread != 0) {
3578 Mutex::Autolock _l(thread->mLock);
3579 int state = mState;
3580 if (mState > STOPPED) {
3581 mState = STOPPED;
3582 // If the track is not active (PAUSED and buffers full), flush buffers
3583 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3584 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3585 reset();
3586 }
Steve Block3856b092011-10-20 11:56:00 +01003587 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 }
3589 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3590 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003591 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003592 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003593 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003594 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003595
3596 // to track the speaker usage
3597 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003598 }
3599 }
3600}
3601
3602void AudioFlinger::PlaybackThread::Track::pause()
3603{
Steve Block3856b092011-10-20 11:56:00 +01003604 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605 sp<ThreadBase> thread = mThread.promote();
3606 if (thread != 0) {
3607 Mutex::Autolock _l(thread->mLock);
3608 if (mState == ACTIVE || mState == RESUMING) {
3609 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003610 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 if (!isOutputTrack()) {
3612 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003613 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003614 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003615 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003617
3618 // to track the speaker usage
3619 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 }
3621 }
3622 }
3623}
3624
3625void AudioFlinger::PlaybackThread::Track::flush()
3626{
Steve Block3856b092011-10-20 11:56:00 +01003627 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 sp<ThreadBase> thread = mThread.promote();
3629 if (thread != 0) {
3630 Mutex::Autolock _l(thread->mLock);
3631 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3632 return;
3633 }
3634 // No point remaining in PAUSED state after a flush => go to
3635 // STOPPED state
3636 mState = STOPPED;
3637
Eric Laurent38ccae22011-03-28 18:37:07 -07003638 // do not reset the track if it is still in the process of being stopped or paused.
3639 // this will be done by prepareTracks_l() when the track is stopped.
3640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3641 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3642 reset();
3643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003644 }
3645}
3646
3647void AudioFlinger::PlaybackThread::Track::reset()
3648{
3649 // Do not reset twice to avoid discarding data written just after a flush and before
3650 // the audioflinger thread detects the track is stopped.
3651 if (!mResetDone) {
3652 TrackBase::reset();
3653 // Force underrun condition to avoid false underrun callback until first data is
3654 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003655 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3656 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003657 mFillingUpStatus = FS_FILLING;
3658 mResetDone = true;
3659 }
3660}
3661
3662void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3663{
3664 mMute = muted;
3665}
3666
Mathias Agopian65ab4712010-07-14 17:59:35 -07003667status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3668{
3669 status_t status = DEAD_OBJECT;
3670 sp<ThreadBase> thread = mThread.promote();
3671 if (thread != 0) {
3672 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3673 status = playbackThread->attachAuxEffect(this, EffectId);
3674 }
3675 return status;
3676}
3677
3678void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3679{
3680 mAuxEffectId = EffectId;
3681 mAuxBuffer = buffer;
3682}
3683
3684// ----------------------------------------------------------------------------
3685
3686// RecordTrack constructor must be called with AudioFlinger::mLock held
3687AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3688 const wp<ThreadBase>& thread,
3689 const sp<Client>& client,
3690 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003691 uint32_t format,
3692 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 int frameCount,
3694 uint32_t flags,
3695 int sessionId)
3696 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003697 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 mOverflow(false)
3699{
3700 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003701 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003702 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003703 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003704 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003705 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003706 } else {
3707 mCblk->frameSize = sizeof(int8_t);
3708 }
3709 }
3710}
3711
3712AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3713{
3714 sp<ThreadBase> thread = mThread.promote();
3715 if (thread != 0) {
3716 AudioSystem::releaseInput(thread->id());
3717 }
3718}
3719
3720status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3721{
3722 audio_track_cblk_t* cblk = this->cblk();
3723 uint32_t framesAvail;
3724 uint32_t framesReq = buffer->frameCount;
3725
3726 // Check if last stepServer failed, try to step now
3727 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3728 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003729 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3731 }
3732
3733 framesAvail = cblk->framesAvailable_l();
3734
Glenn Kastenf6b16782011-12-15 09:51:17 -08003735 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003736 uint32_t s = cblk->server;
3737 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3738
3739 if (framesReq > framesAvail) {
3740 framesReq = framesAvail;
3741 }
3742 if (s + framesReq > bufferEnd) {
3743 framesReq = bufferEnd - s;
3744 }
3745
3746 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003747 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748
3749 buffer->frameCount = framesReq;
3750 return NO_ERROR;
3751 }
3752
3753getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003754 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 buffer->frameCount = 0;
3756 return NOT_ENOUGH_DATA;
3757}
3758
3759status_t AudioFlinger::RecordThread::RecordTrack::start()
3760{
3761 sp<ThreadBase> thread = mThread.promote();
3762 if (thread != 0) {
3763 RecordThread *recordThread = (RecordThread *)thread.get();
3764 return recordThread->start(this);
3765 } else {
3766 return BAD_VALUE;
3767 }
3768}
3769
3770void AudioFlinger::RecordThread::RecordTrack::stop()
3771{
3772 sp<ThreadBase> thread = mThread.promote();
3773 if (thread != 0) {
3774 RecordThread *recordThread = (RecordThread *)thread.get();
3775 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003776 TrackBase::reset();
3777 // Force overerrun condition to avoid false overrun callback until first data is
3778 // read from buffer
3779 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780 }
3781}
3782
3783void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3784{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003785 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003786 (mClient == NULL) ? getpid() : mClient->pid(),
3787 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003788 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003789 mSessionId,
3790 mFrameCount,
3791 mState,
3792 mCblk->sampleRate,
3793 mCblk->server,
3794 mCblk->user);
3795}
3796
3797
3798// ----------------------------------------------------------------------------
3799
3800AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3801 const wp<ThreadBase>& thread,
3802 DuplicatingThread *sourceThread,
3803 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003804 uint32_t format,
3805 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003806 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003807 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808 mActive(false), mSourceThread(sourceThread)
3809{
3810
3811 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3812 if (mCblk != NULL) {
3813 mCblk->flags |= CBLK_DIRECTION_OUT;
3814 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
Glenn Kastenb1cf75c2012-01-17 12:20:54 -08003815 mCblk->volumeLR = (MAX_GAIN_INT << 16) | MAX_GAIN_INT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816 mOutBuffer.frameCount = 0;
3817 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003818 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003819 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3820 mCblk, mBuffer, mCblk->buffers,
3821 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003822 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003823 ALOGW("Error creating output track on thread %p", playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824 }
3825}
3826
3827AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3828{
3829 clearBufferQueue();
3830}
3831
3832status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3833{
3834 status_t status = Track::start();
3835 if (status != NO_ERROR) {
3836 return status;
3837 }
3838
3839 mActive = true;
3840 mRetryCount = 127;
3841 return status;
3842}
3843
3844void AudioFlinger::PlaybackThread::OutputTrack::stop()
3845{
3846 Track::stop();
3847 clearBufferQueue();
3848 mOutBuffer.frameCount = 0;
3849 mActive = false;
3850}
3851
3852bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3853{
3854 Buffer *pInBuffer;
3855 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003856 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003857 bool outputBufferFull = false;
3858 inBuffer.frameCount = frames;
3859 inBuffer.i16 = data;
3860
3861 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3862
3863 if (!mActive && frames != 0) {
3864 start();
3865 sp<ThreadBase> thread = mThread.promote();
3866 if (thread != 0) {
3867 MixerThread *mixerThread = (MixerThread *)thread.get();
3868 if (mCblk->frameCount > frames){
3869 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3870 uint32_t startFrames = (mCblk->frameCount - frames);
3871 pInBuffer = new Buffer;
3872 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3873 pInBuffer->frameCount = startFrames;
3874 pInBuffer->i16 = pInBuffer->mBuffer;
3875 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3876 mBufferQueue.add(pInBuffer);
3877 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003878 ALOGW ("OutputTrack::write() %p no more buffers in queue", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 }
3880 }
3881 }
3882 }
3883
3884 while (waitTimeLeftMs) {
3885 // First write pending buffers, then new data
3886 if (mBufferQueue.size()) {
3887 pInBuffer = mBufferQueue.itemAt(0);
3888 } else {
3889 pInBuffer = &inBuffer;
3890 }
3891
3892 if (pInBuffer->frameCount == 0) {
3893 break;
3894 }
3895
3896 if (mOutBuffer.frameCount == 0) {
3897 mOutBuffer.frameCount = pInBuffer->frameCount;
3898 nsecs_t startTime = systemTime();
3899 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003900 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003901 outputBufferFull = true;
3902 break;
3903 }
3904 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3905 if (waitTimeLeftMs >= waitTimeMs) {
3906 waitTimeLeftMs -= waitTimeMs;
3907 } else {
3908 waitTimeLeftMs = 0;
3909 }
3910 }
3911
3912 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3913 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3914 mCblk->stepUser(outFrames);
3915 pInBuffer->frameCount -= outFrames;
3916 pInBuffer->i16 += outFrames * channelCount;
3917 mOutBuffer.frameCount -= outFrames;
3918 mOutBuffer.i16 += outFrames * channelCount;
3919
3920 if (pInBuffer->frameCount == 0) {
3921 if (mBufferQueue.size()) {
3922 mBufferQueue.removeAt(0);
3923 delete [] pInBuffer->mBuffer;
3924 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003925 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926 } else {
3927 break;
3928 }
3929 }
3930 }
3931
3932 // If we could not write all frames, allocate a buffer and queue it for next time.
3933 if (inBuffer.frameCount) {
3934 sp<ThreadBase> thread = mThread.promote();
3935 if (thread != 0 && !thread->standby()) {
3936 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3937 pInBuffer = new Buffer;
3938 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3939 pInBuffer->frameCount = inBuffer.frameCount;
3940 pInBuffer->i16 = pInBuffer->mBuffer;
3941 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3942 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003943 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00003945 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946 }
3947 }
3948 }
3949
3950 // Calling write() with a 0 length buffer, means that no more data will be written:
3951 // If no more buffers are pending, fill output track buffer to make sure it is started
3952 // by output mixer.
3953 if (frames == 0 && mBufferQueue.size() == 0) {
3954 if (mCblk->user < mCblk->frameCount) {
3955 frames = mCblk->frameCount - mCblk->user;
3956 pInBuffer = new Buffer;
3957 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3958 pInBuffer->frameCount = frames;
3959 pInBuffer->i16 = pInBuffer->mBuffer;
3960 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3961 mBufferQueue.add(pInBuffer);
3962 } else if (mActive) {
3963 stop();
3964 }
3965 }
3966
3967 return outputBufferFull;
3968}
3969
3970status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3971{
3972 int active;
3973 status_t result;
3974 audio_track_cblk_t* cblk = mCblk;
3975 uint32_t framesReq = buffer->frameCount;
3976
Steve Block3856b092011-10-20 11:56:00 +01003977// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003978 buffer->frameCount = 0;
3979
3980 uint32_t framesAvail = cblk->framesAvailable();
3981
3982
3983 if (framesAvail == 0) {
3984 Mutex::Autolock _l(cblk->lock);
3985 goto start_loop_here;
3986 while (framesAvail == 0) {
3987 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003988 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003989 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990 return AudioTrack::NO_MORE_BUFFERS;
3991 }
3992 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3993 if (result != NO_ERROR) {
3994 return AudioTrack::NO_MORE_BUFFERS;
3995 }
3996 // read the server count again
3997 start_loop_here:
3998 framesAvail = cblk->framesAvailable_l();
3999 }
4000 }
4001
4002// if (framesAvail < framesReq) {
4003// return AudioTrack::NO_MORE_BUFFERS;
4004// }
4005
4006 if (framesReq > framesAvail) {
4007 framesReq = framesAvail;
4008 }
4009
4010 uint32_t u = cblk->user;
4011 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4012
4013 if (u + framesReq > bufferEnd) {
4014 framesReq = bufferEnd - u;
4015 }
4016
4017 buffer->frameCount = framesReq;
4018 buffer->raw = (void *)cblk->buffer(u);
4019 return NO_ERROR;
4020}
4021
4022
4023void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4024{
4025 size_t size = mBufferQueue.size();
4026 Buffer *pBuffer;
4027
4028 for (size_t i = 0; i < size; i++) {
4029 pBuffer = mBufferQueue.itemAt(i);
4030 delete [] pBuffer->mBuffer;
4031 delete pBuffer;
4032 }
4033 mBufferQueue.clear();
4034}
4035
4036// ----------------------------------------------------------------------------
4037
4038AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4039 : RefBase(),
4040 mAudioFlinger(audioFlinger),
4041 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4042 mPid(pid)
4043{
4044 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4045}
4046
4047// Client destructor must be called with AudioFlinger::mLock held
4048AudioFlinger::Client::~Client()
4049{
4050 mAudioFlinger->removeClient_l(mPid);
4051}
4052
4053const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4054{
4055 return mMemoryDealer;
4056}
4057
4058// ----------------------------------------------------------------------------
4059
4060AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4061 const sp<IAudioFlingerClient>& client,
4062 pid_t pid)
4063 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4064{
4065}
4066
4067AudioFlinger::NotificationClient::~NotificationClient()
4068{
4069 mClient.clear();
4070}
4071
4072void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4073{
4074 sp<NotificationClient> keep(this);
4075 {
4076 mAudioFlinger->removeNotificationClient(mPid);
4077 }
4078}
4079
4080// ----------------------------------------------------------------------------
4081
4082AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4083 : BnAudioTrack(),
4084 mTrack(track)
4085{
4086}
4087
4088AudioFlinger::TrackHandle::~TrackHandle() {
4089 // just stop the track on deletion, associated resources
4090 // will be freed from the main thread once all pending buffers have
4091 // been played. Unless it's not in the active track list, in which
4092 // case we free everything now...
4093 mTrack->destroy();
4094}
4095
4096status_t AudioFlinger::TrackHandle::start() {
4097 return mTrack->start();
4098}
4099
4100void AudioFlinger::TrackHandle::stop() {
4101 mTrack->stop();
4102}
4103
4104void AudioFlinger::TrackHandle::flush() {
4105 mTrack->flush();
4106}
4107
4108void AudioFlinger::TrackHandle::mute(bool e) {
4109 mTrack->mute(e);
4110}
4111
4112void AudioFlinger::TrackHandle::pause() {
4113 mTrack->pause();
4114}
4115
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4117 return mTrack->getCblk();
4118}
4119
4120status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4121{
4122 return mTrack->attachAuxEffect(EffectId);
4123}
4124
4125status_t AudioFlinger::TrackHandle::onTransact(
4126 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4127{
4128 return BnAudioTrack::onTransact(code, data, reply, flags);
4129}
4130
4131// ----------------------------------------------------------------------------
4132
4133sp<IAudioRecord> AudioFlinger::openRecord(
4134 pid_t pid,
4135 int input,
4136 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004137 uint32_t format,
4138 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 int frameCount,
4140 uint32_t flags,
4141 int *sessionId,
4142 status_t *status)
4143{
4144 sp<RecordThread::RecordTrack> recordTrack;
4145 sp<RecordHandle> recordHandle;
4146 sp<Client> client;
4147 wp<Client> wclient;
4148 status_t lStatus;
4149 RecordThread *thread;
4150 size_t inFrameCount;
4151 int lSessionId;
4152
4153 // check calling permissions
4154 if (!recordingAllowed()) {
4155 lStatus = PERMISSION_DENIED;
4156 goto Exit;
4157 }
4158
4159 // add client to list
4160 { // scope for mLock
4161 Mutex::Autolock _l(mLock);
4162 thread = checkRecordThread_l(input);
4163 if (thread == NULL) {
4164 lStatus = BAD_VALUE;
4165 goto Exit;
4166 }
4167
4168 wclient = mClients.valueFor(pid);
4169 if (wclient != NULL) {
4170 client = wclient.promote();
4171 } else {
4172 client = new Client(this, pid);
4173 mClients.add(pid, client);
4174 }
4175
4176 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004177 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 lSessionId = *sessionId;
4179 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004180 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181 if (sessionId != NULL) {
4182 *sessionId = lSessionId;
4183 }
4184 }
4185 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004186 recordTrack = thread->createRecordTrack_l(client,
4187 sampleRate,
4188 format,
4189 channelMask,
4190 frameCount,
4191 flags,
4192 lSessionId,
4193 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004195 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4197 // destructor is called by the TrackBase destructor with mLock held
4198 client.clear();
4199 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 goto Exit;
4201 }
4202
4203 // return to handle to client
4204 recordHandle = new RecordHandle(recordTrack);
4205 lStatus = NO_ERROR;
4206
4207Exit:
4208 if (status) {
4209 *status = lStatus;
4210 }
4211 return recordHandle;
4212}
4213
4214// ----------------------------------------------------------------------------
4215
4216AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4217 : BnAudioRecord(),
4218 mRecordTrack(recordTrack)
4219{
4220}
4221
4222AudioFlinger::RecordHandle::~RecordHandle() {
4223 stop();
4224}
4225
4226status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004227 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 return mRecordTrack->start();
4229}
4230
4231void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004232 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233 mRecordTrack->stop();
4234}
4235
4236sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4237 return mRecordTrack->getCblk();
4238}
4239
4240status_t AudioFlinger::RecordHandle::onTransact(
4241 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4242{
4243 return BnAudioRecord::onTransact(code, data, reply, flags);
4244}
4245
4246// ----------------------------------------------------------------------------
4247
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004248AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4249 AudioStreamIn *input,
4250 uint32_t sampleRate,
4251 uint32_t channels,
4252 int id,
4253 uint32_t device) :
4254 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004255 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004257 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004258
4259 snprintf(mName, kNameLength, "AudioIn_%d", id);
4260
Dima Zavinfce7a472011-04-19 22:30:36 -07004261 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 mReqSampleRate = sampleRate;
4263 readInputParameters();
4264}
4265
4266
4267AudioFlinger::RecordThread::~RecordThread()
4268{
4269 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004270 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 delete mResampler;
4272 delete[] mRsmpOutBuffer;
4273 }
4274}
4275
4276void AudioFlinger::RecordThread::onFirstRef()
4277{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004278 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279}
4280
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004281status_t AudioFlinger::RecordThread::readyToRun()
4282{
4283 status_t status = initCheck();
Steve Block5ff1dd52012-01-05 23:22:43 +00004284 ALOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004285 return status;
4286}
4287
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288bool AudioFlinger::RecordThread::threadLoop()
4289{
4290 AudioBufferProvider::Buffer buffer;
4291 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004292 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293
Eric Laurent44d98482010-09-30 16:12:31 -07004294 nsecs_t lastWarning = 0;
4295
Eric Laurentfeb0db62011-07-22 09:04:31 -07004296 acquireWakeLock();
4297
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 // start recording
4299 while (!exitPending()) {
4300
4301 processConfigEvents();
4302
4303 { // scope for mLock
4304 Mutex::Autolock _l(mLock);
4305 checkForNewParameters_l();
4306 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4307 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004308 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 mStandby = true;
4310 }
4311
4312 if (exitPending()) break;
4313
Eric Laurentfeb0db62011-07-22 09:04:31 -07004314 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004315 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 // go to sleep
4317 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004318 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004319 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 continue;
4321 }
4322 if (mActiveTrack != 0) {
4323 if (mActiveTrack->mState == TrackBase::PAUSING) {
4324 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004325 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 mStandby = true;
4327 }
4328 mActiveTrack.clear();
4329 mStartStopCond.broadcast();
4330 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4331 if (mReqChannelCount != mActiveTrack->channelCount()) {
4332 mActiveTrack.clear();
4333 mStartStopCond.broadcast();
4334 } else if (mBytesRead != 0) {
4335 // record start succeeds only if first read from audio input
4336 // succeeds
4337 if (mBytesRead > 0) {
4338 mActiveTrack->mState = TrackBase::ACTIVE;
4339 } else {
4340 mActiveTrack.clear();
4341 }
4342 mStartStopCond.broadcast();
4343 }
4344 mStandby = false;
4345 }
4346 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004347 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004348 }
4349
4350 if (mActiveTrack != 0) {
4351 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4352 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004353 unlockEffectChains(effectChains);
4354 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004355 continue;
4356 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004357 for (size_t i = 0; i < effectChains.size(); i ++) {
4358 effectChains[i]->process_l();
4359 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004360
Mathias Agopian65ab4712010-07-14 17:59:35 -07004361 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004362 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004364 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 // no resampling
4366 while (framesOut) {
4367 size_t framesIn = mFrameCount - mRsmpInIndex;
4368 if (framesIn) {
4369 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4370 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4371 if (framesIn > framesOut)
4372 framesIn = framesOut;
4373 mRsmpInIndex += framesIn;
4374 framesOut -= framesIn;
4375 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004376 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 memcpy(dst, src, framesIn * mFrameSize);
4378 } else {
4379 int16_t *src16 = (int16_t *)src;
4380 int16_t *dst16 = (int16_t *)dst;
4381 if (mChannelCount == 1) {
4382 while (framesIn--) {
4383 *dst16++ = *src16;
4384 *dst16++ = *src16++;
4385 }
4386 } else {
4387 while (framesIn--) {
4388 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4389 src16 += 2;
4390 }
4391 }
4392 }
4393 }
4394 if (framesOut && mFrameCount == mRsmpInIndex) {
4395 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004396 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004397 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 framesOut = 0;
4399 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004400 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004401 mRsmpInIndex = 0;
4402 }
4403 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004404 ALOGE("Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4406 // Force input into standby so that it tries to
4407 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004408 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004409 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 }
4411 mRsmpInIndex = mFrameCount;
4412 framesOut = 0;
4413 buffer.frameCount = 0;
4414 }
4415 }
4416 }
4417 } else {
4418 // resampling
4419
4420 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4421 // alter output frame count as if we were expecting stereo samples
4422 if (mChannelCount == 1 && mReqChannelCount == 1) {
4423 framesOut >>= 1;
4424 }
4425 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4426 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4427 // are 32 bit aligned which should be always true.
4428 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004429 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 // the resampler always outputs stereo samples: do post stereo to mono conversion
4431 int16_t *src = (int16_t *)mRsmpOutBuffer;
4432 int16_t *dst = buffer.i16;
4433 while (framesOut--) {
4434 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4435 src += 2;
4436 }
4437 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004438 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 }
4440
4441 }
4442 mActiveTrack->releaseBuffer(&buffer);
4443 mActiveTrack->overflow();
4444 }
4445 // client isn't retrieving buffers fast enough
4446 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004447 if (!mActiveTrack->setOverflow()) {
4448 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004449 if ((now - lastWarning) > kWarningThrottleNs) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004450 ALOGW("RecordThread: buffer overflow");
Eric Laurent44d98482010-09-30 16:12:31 -07004451 lastWarning = now;
4452 }
4453 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004454 // Release the processor for a while before asking for a new buffer.
4455 // This will give the application more chance to read from the buffer and
4456 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004457 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 }
4459 }
Eric Laurentec437d82011-07-26 20:54:46 -07004460 // enable changes in effect chain
4461 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004462 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 }
4464
4465 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004466 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004467 }
4468 mActiveTrack.clear();
4469
4470 mStartStopCond.broadcast();
4471
Eric Laurentfeb0db62011-07-22 09:04:31 -07004472 releaseWakeLock();
4473
Steve Block3856b092011-10-20 11:56:00 +01004474 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475 return false;
4476}
4477
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004478
4479sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4480 const sp<AudioFlinger::Client>& client,
4481 uint32_t sampleRate,
4482 int format,
4483 int channelMask,
4484 int frameCount,
4485 uint32_t flags,
4486 int sessionId,
4487 status_t *status)
4488{
4489 sp<RecordTrack> track;
4490 status_t lStatus;
4491
4492 lStatus = initCheck();
4493 if (lStatus != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004494 ALOGE("Audio driver not initialized.");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004495 goto Exit;
4496 }
4497
4498 { // scope for mLock
4499 Mutex::Autolock _l(mLock);
4500
4501 track = new RecordTrack(this, client, sampleRate,
4502 format, channelMask, frameCount, flags, sessionId);
4503
4504 if (track->getCblk() == NULL) {
4505 lStatus = NO_MEMORY;
4506 goto Exit;
4507 }
4508
4509 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004510 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4511 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004512 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004513 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4514 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004515 }
4516 lStatus = NO_ERROR;
4517
4518Exit:
4519 if (status) {
4520 *status = lStatus;
4521 }
4522 return track;
4523}
4524
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4526{
Steve Block3856b092011-10-20 11:56:00 +01004527 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 sp <ThreadBase> strongMe = this;
4529 status_t status = NO_ERROR;
4530 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004531 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004532 if (mActiveTrack != 0) {
4533 if (recordTrack != mActiveTrack.get()) {
4534 status = -EBUSY;
4535 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4536 mActiveTrack->mState = TrackBase::ACTIVE;
4537 }
4538 return status;
4539 }
4540
4541 recordTrack->mState = TrackBase::IDLE;
4542 mActiveTrack = recordTrack;
4543 mLock.unlock();
4544 status_t status = AudioSystem::startInput(mId);
4545 mLock.lock();
4546 if (status != NO_ERROR) {
4547 mActiveTrack.clear();
4548 return status;
4549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004550 mRsmpInIndex = mFrameCount;
4551 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004552 if (mResampler != NULL) {
4553 mResampler->reset();
4554 }
4555 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004557 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558 mWaitWorkCV.signal();
4559 // do not wait for mStartStopCond if exiting
4560 if (mExiting) {
4561 mActiveTrack.clear();
4562 status = INVALID_OPERATION;
4563 goto startError;
4564 }
4565 mStartStopCond.wait(mLock);
4566 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004567 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 status = BAD_VALUE;
4569 goto startError;
4570 }
Steve Block3856b092011-10-20 11:56:00 +01004571 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572 return status;
4573 }
4574startError:
4575 AudioSystem::stopInput(mId);
4576 return status;
4577}
4578
4579void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004580 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581 sp <ThreadBase> strongMe = this;
4582 {
Glenn Kastena7d8d6f2012-01-05 15:41:56 -08004583 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4585 mActiveTrack->mState = TrackBase::PAUSING;
4586 // do not wait for mStartStopCond if exiting
4587 if (mExiting) {
4588 return;
4589 }
4590 mStartStopCond.wait(mLock);
4591 // if we have been restarted, recordTrack == mActiveTrack.get() here
4592 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4593 mLock.unlock();
4594 AudioSystem::stopInput(mId);
4595 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004596 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 }
4598 }
4599 }
4600}
4601
4602status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4603{
4604 const size_t SIZE = 256;
4605 char buffer[SIZE];
4606 String8 result;
4607 pid_t pid = 0;
4608
4609 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4610 result.append(buffer);
4611
4612 if (mActiveTrack != 0) {
4613 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004614 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 mActiveTrack->dump(buffer, SIZE);
4616 result.append(buffer);
4617
4618 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4619 result.append(buffer);
4620 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4621 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004622 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004623 result.append(buffer);
4624 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4625 result.append(buffer);
4626 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4627 result.append(buffer);
4628
4629
4630 } else {
4631 result.append("No record client\n");
4632 }
4633 write(fd, result.string(), result.size());
4634
4635 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004636 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004637
4638 return NO_ERROR;
4639}
4640
4641status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4642{
4643 size_t framesReq = buffer->frameCount;
4644 size_t framesReady = mFrameCount - mRsmpInIndex;
4645 int channelCount;
4646
4647 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004648 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 if (mBytesRead < 0) {
Steve Block29357bc2012-01-06 19:20:56 +00004650 ALOGE("RecordThread::getNextBuffer() Error reading audio input");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004651 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4652 // Force input into standby so that it tries to
4653 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004654 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004655 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004657 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 buffer->frameCount = 0;
4659 return NOT_ENOUGH_DATA;
4660 }
4661 mRsmpInIndex = 0;
4662 framesReady = mFrameCount;
4663 }
4664
4665 if (framesReq > framesReady) {
4666 framesReq = framesReady;
4667 }
4668
4669 if (mChannelCount == 1 && mReqChannelCount == 2) {
4670 channelCount = 1;
4671 } else {
4672 channelCount = 2;
4673 }
4674 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4675 buffer->frameCount = framesReq;
4676 return NO_ERROR;
4677}
4678
4679void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4680{
4681 mRsmpInIndex += buffer->frameCount;
4682 buffer->frameCount = 0;
4683}
4684
4685bool AudioFlinger::RecordThread::checkForNewParameters_l()
4686{
4687 bool reconfig = false;
4688
4689 while (!mNewParameters.isEmpty()) {
4690 status_t status = NO_ERROR;
4691 String8 keyValuePair = mNewParameters[0];
4692 AudioParameter param = AudioParameter(keyValuePair);
4693 int value;
4694 int reqFormat = mFormat;
4695 int reqSamplingRate = mReqSampleRate;
4696 int reqChannelCount = mReqChannelCount;
4697
4698 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4699 reqSamplingRate = value;
4700 reconfig = true;
4701 }
4702 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4703 reqFormat = value;
4704 reconfig = true;
4705 }
4706 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004707 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004708 reconfig = true;
4709 }
4710 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4711 // do not accept frame count changes if tracks are open as the track buffer
4712 // size depends on frame count and correct behavior would not be garantied
4713 // if frame count is changed after track creation
4714 if (mActiveTrack != 0) {
4715 status = INVALID_OPERATION;
4716 } else {
4717 reconfig = true;
4718 }
4719 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004720 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4721 // forward device change to effects that have requested to be
4722 // aware of attached audio device.
4723 for (size_t i = 0; i < mEffectChains.size(); i++) {
4724 mEffectChains[i]->setDevice_l(value);
4725 }
4726 // store input device and output device but do not forward output device to audio HAL.
4727 // Note that status is ignored by the caller for output device
4728 // (see AudioFlinger::setParameters()
4729 if (value & AUDIO_DEVICE_OUT_ALL) {
4730 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4731 status = BAD_VALUE;
4732 } else {
4733 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004734 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4735 if (mTrack != NULL) {
4736 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004737 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004738 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4739 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4740 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004741 }
4742 mDevice |= (uint32_t)value;
4743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004745 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004747 mInput->stream->common.standby(&mInput->stream->common);
4748 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004749 }
4750 if (reconfig) {
4751 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004752 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004753 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004754 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4755 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004756 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004757 status = NO_ERROR;
4758 }
4759 if (status == NO_ERROR) {
4760 readInputParameters();
4761 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4762 }
4763 }
4764 }
4765
4766 mNewParameters.removeAt(0);
4767
4768 mParamStatus = status;
4769 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004770 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4771 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004772 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773 }
4774 return reconfig;
4775}
4776
4777String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4778{
Dima Zavinfce7a472011-04-19 22:30:36 -07004779 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004780 String8 out_s8 = String8();
4781
4782 Mutex::Autolock _l(mLock);
4783 if (initCheck() != NO_ERROR) {
4784 return out_s8;
4785 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004786
Dima Zavin799a70e2011-04-18 16:57:27 -07004787 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004788 out_s8 = String8(s);
4789 free(s);
4790 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791}
4792
4793void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4794 AudioSystem::OutputDescriptor desc;
4795 void *param2 = 0;
4796
4797 switch (event) {
4798 case AudioSystem::INPUT_OPENED:
4799 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004800 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004801 desc.samplingRate = mSampleRate;
4802 desc.format = mFormat;
4803 desc.frameCount = mFrameCount;
4804 desc.latency = 0;
4805 param2 = &desc;
4806 break;
4807
4808 case AudioSystem::INPUT_CLOSED:
4809 default:
4810 break;
4811 }
4812 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4813}
4814
4815void AudioFlinger::RecordThread::readInputParameters()
4816{
4817 if (mRsmpInBuffer) delete mRsmpInBuffer;
4818 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4819 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004820 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821
Dima Zavin799a70e2011-04-18 16:57:27 -07004822 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004823 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4824 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004825 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
Glenn Kastenb9980652012-01-11 09:48:27 -08004826 mFrameSize = audio_stream_frame_size(&mInput->stream->common);
Dima Zavin799a70e2011-04-18 16:57:27 -07004827 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828 mFrameCount = mInputBytes / mFrameSize;
4829 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4830
4831 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4832 {
4833 int channelCount;
4834 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4835 // stereo to mono post process as the resampler always outputs stereo.
4836 if (mChannelCount == 1 && mReqChannelCount == 2) {
4837 channelCount = 1;
4838 } else {
4839 channelCount = 2;
4840 }
4841 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4842 mResampler->setSampleRate(mSampleRate);
4843 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4844 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4845
4846 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4847 if (mChannelCount == 1 && mReqChannelCount == 1) {
4848 mFrameCount >>= 1;
4849 }
4850
4851 }
4852 mRsmpInIndex = mFrameCount;
4853}
4854
4855unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4856{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004857 Mutex::Autolock _l(mLock);
4858 if (initCheck() != NO_ERROR) {
4859 return 0;
4860 }
4861
Dima Zavin799a70e2011-04-18 16:57:27 -07004862 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004863}
4864
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004865uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4866{
4867 Mutex::Autolock _l(mLock);
4868 uint32_t result = 0;
4869 if (getEffectChain_l(sessionId) != 0) {
4870 result = EFFECT_SESSION;
4871 }
4872
4873 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4874 result |= TRACK_SESSION;
4875 }
4876
4877 return result;
4878}
4879
Eric Laurent59bd0da2011-08-01 09:52:20 -07004880AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4881{
4882 Mutex::Autolock _l(mLock);
4883 return mTrack;
4884}
4885
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004886AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4887{
4888 Mutex::Autolock _l(mLock);
4889 return mInput;
4890}
4891
4892AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4893{
4894 Mutex::Autolock _l(mLock);
4895 AudioStreamIn *input = mInput;
4896 mInput = NULL;
4897 return input;
4898}
4899
4900// this method must always be called either with ThreadBase mLock held or inside the thread loop
4901audio_stream_t* AudioFlinger::RecordThread::stream()
4902{
4903 if (mInput == NULL) {
4904 return NULL;
4905 }
4906 return &mInput->stream->common;
4907}
4908
4909
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910// ----------------------------------------------------------------------------
4911
4912int AudioFlinger::openOutput(uint32_t *pDevices,
4913 uint32_t *pSamplingRate,
4914 uint32_t *pFormat,
4915 uint32_t *pChannels,
4916 uint32_t *pLatencyMs,
4917 uint32_t flags)
4918{
4919 status_t status;
4920 PlaybackThread *thread = NULL;
4921 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4922 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4923 uint32_t format = pFormat ? *pFormat : 0;
4924 uint32_t channels = pChannels ? *pChannels : 0;
4925 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004926 audio_stream_out_t *outStream;
4927 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928
Steve Block3856b092011-10-20 11:56:00 +01004929 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930 pDevices ? *pDevices : 0,
4931 samplingRate,
4932 format,
4933 channels,
4934 flags);
4935
4936 if (pDevices == NULL || *pDevices == 0) {
4937 return 0;
4938 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004939
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 Mutex::Autolock _l(mLock);
4941
Dima Zavin799a70e2011-04-18 16:57:27 -07004942 outHwDev = findSuitableHwDev_l(*pDevices);
4943 if (outHwDev == NULL)
4944 return 0;
4945
4946 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4947 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004948 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004949 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 samplingRate,
4951 format,
4952 channels,
4953 status);
4954
4955 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004956 if (outStream != NULL) {
4957 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004958 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004959
Dima Zavinfce7a472011-04-19 22:30:36 -07004960 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4961 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4962 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004964 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004965 } else {
4966 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004967 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968 }
4969 mPlaybackThreads.add(id, thread);
4970
4971 if (pSamplingRate) *pSamplingRate = samplingRate;
4972 if (pFormat) *pFormat = format;
4973 if (pChannels) *pChannels = channels;
4974 if (pLatencyMs) *pLatencyMs = thread->latency();
4975
4976 // notify client processes of the new output creation
4977 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4978 return id;
4979 }
4980
4981 return 0;
4982}
4983
4984int AudioFlinger::openDuplicateOutput(int output1, int output2)
4985{
4986 Mutex::Autolock _l(mLock);
4987 MixerThread *thread1 = checkMixerThread_l(output1);
4988 MixerThread *thread2 = checkMixerThread_l(output2);
4989
4990 if (thread1 == NULL || thread2 == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00004991 ALOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004992 return 0;
4993 }
4994
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004995 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4997 thread->addOutputTrack(thread2);
4998 mPlaybackThreads.add(id, thread);
4999 // notify client processes of the new output creation
5000 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5001 return id;
5002}
5003
5004status_t AudioFlinger::closeOutput(int output)
5005{
5006 // keep strong reference on the playback thread so that
5007 // it is not destroyed while exit() is executed
5008 sp <PlaybackThread> thread;
5009 {
5010 Mutex::Autolock _l(mLock);
5011 thread = checkPlaybackThread_l(output);
5012 if (thread == NULL) {
5013 return BAD_VALUE;
5014 }
5015
Steve Block3856b092011-10-20 11:56:00 +01005016 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005019 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005020 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5022 dupThread->removeOutputTrack((MixerThread *)thread.get());
5023 }
5024 }
5025 }
5026 void *param2 = 0;
5027 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5028 mPlaybackThreads.removeItem(output);
5029 }
5030 thread->exit();
5031
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005032 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005033 AudioStreamOut *out = thread->clearOutput();
5034 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005035 out->hwDev->close_output_stream(out->hwDev, out->stream);
5036 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005037 }
5038 return NO_ERROR;
5039}
5040
5041status_t AudioFlinger::suspendOutput(int output)
5042{
5043 Mutex::Autolock _l(mLock);
5044 PlaybackThread *thread = checkPlaybackThread_l(output);
5045
5046 if (thread == NULL) {
5047 return BAD_VALUE;
5048 }
5049
Steve Block3856b092011-10-20 11:56:00 +01005050 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 thread->suspend();
5052
5053 return NO_ERROR;
5054}
5055
5056status_t AudioFlinger::restoreOutput(int output)
5057{
5058 Mutex::Autolock _l(mLock);
5059 PlaybackThread *thread = checkPlaybackThread_l(output);
5060
5061 if (thread == NULL) {
5062 return BAD_VALUE;
5063 }
5064
Steve Block3856b092011-10-20 11:56:00 +01005065 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005066
5067 thread->restore();
5068
5069 return NO_ERROR;
5070}
5071
5072int AudioFlinger::openInput(uint32_t *pDevices,
5073 uint32_t *pSamplingRate,
5074 uint32_t *pFormat,
5075 uint32_t *pChannels,
5076 uint32_t acoustics)
5077{
5078 status_t status;
5079 RecordThread *thread = NULL;
5080 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5081 uint32_t format = pFormat ? *pFormat : 0;
5082 uint32_t channels = pChannels ? *pChannels : 0;
5083 uint32_t reqSamplingRate = samplingRate;
5084 uint32_t reqFormat = format;
5085 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005086 audio_stream_in_t *inStream;
5087 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088
5089 if (pDevices == NULL || *pDevices == 0) {
5090 return 0;
5091 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005092
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 Mutex::Autolock _l(mLock);
5094
Dima Zavin799a70e2011-04-18 16:57:27 -07005095 inHwDev = findSuitableHwDev_l(*pDevices);
5096 if (inHwDev == NULL)
5097 return 0;
5098
5099 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5100 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005101 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005102 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005103 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005104 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105 samplingRate,
5106 format,
5107 channels,
5108 acoustics,
5109 status);
5110
5111 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5112 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5113 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005114 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005115 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005117 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005118 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005119 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5120 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005121 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005122 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 }
5124
Dima Zavin799a70e2011-04-18 16:57:27 -07005125 if (inStream != NULL) {
5126 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5127
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005128 int id = nextUniqueId();
5129 // Start record thread
5130 // RecorThread require both input and output device indication to forward to audio
5131 // pre processing modules
5132 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5133 thread = new RecordThread(this,
5134 input,
5135 reqSamplingRate,
5136 reqChannels,
5137 id,
5138 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005139 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005140 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005141 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5142 if (pFormat) *pFormat = format;
5143 if (pChannels) *pChannels = reqChannels;
5144
Dima Zavin799a70e2011-04-18 16:57:27 -07005145 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146
5147 // notify client processes of the new input creation
5148 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5149 return id;
5150 }
5151
5152 return 0;
5153}
5154
5155status_t AudioFlinger::closeInput(int input)
5156{
5157 // keep strong reference on the record thread so that
5158 // it is not destroyed while exit() is executed
5159 sp <RecordThread> thread;
5160 {
5161 Mutex::Autolock _l(mLock);
5162 thread = checkRecordThread_l(input);
5163 if (thread == NULL) {
5164 return BAD_VALUE;
5165 }
5166
Steve Block3856b092011-10-20 11:56:00 +01005167 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 void *param2 = 0;
5169 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5170 mRecordThreads.removeItem(input);
5171 }
5172 thread->exit();
5173
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005174 AudioStreamIn *in = thread->clearInput();
5175 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005176 in->hwDev->close_input_stream(in->hwDev, in->stream);
5177 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005178
5179 return NO_ERROR;
5180}
5181
Glenn Kastenfff6d712012-01-12 16:38:12 -08005182status_t AudioFlinger::setStreamOutput(audio_stream_type_t stream, int output)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183{
5184 Mutex::Autolock _l(mLock);
5185 MixerThread *dstThread = checkMixerThread_l(output);
5186 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005187 ALOGW("setStreamOutput() bad output id %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 return BAD_VALUE;
5189 }
5190
Steve Block3856b092011-10-20 11:56:00 +01005191 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005192 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5193
Eric Laurent9f6530f2011-08-30 10:18:54 -07005194 dstThread->setStreamValid(stream, true);
5195
Mathias Agopian65ab4712010-07-14 17:59:35 -07005196 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5197 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5198 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005199 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005201 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 }
Eric Laurentde070132010-07-13 04:45:46 -07005204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005205
5206 return NO_ERROR;
5207}
5208
5209
5210int AudioFlinger::newAudioSessionId()
5211{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005212 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005213}
5214
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005215void AudioFlinger::acquireAudioSessionId(int audioSession)
5216{
5217 Mutex::Autolock _l(mLock);
5218 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005219 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005220 int num = mAudioSessionRefs.size();
5221 for (int i = 0; i< num; i++) {
5222 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5223 if (ref->sessionid == audioSession && ref->pid == caller) {
5224 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005225 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005226 return;
5227 }
5228 }
5229 AudioSessionRef *ref = new AudioSessionRef();
5230 ref->sessionid = audioSession;
5231 ref->pid = caller;
5232 ref->cnt = 1;
5233 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005234 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005235}
5236
5237void AudioFlinger::releaseAudioSessionId(int audioSession)
5238{
5239 Mutex::Autolock _l(mLock);
5240 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005241 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005242 int num = mAudioSessionRefs.size();
5243 for (int i = 0; i< num; i++) {
5244 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5245 if (ref->sessionid == audioSession && ref->pid == caller) {
5246 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005247 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005248 if (ref->cnt == 0) {
5249 mAudioSessionRefs.removeAt(i);
5250 delete ref;
5251 purgeStaleEffects_l();
5252 }
5253 return;
5254 }
5255 }
Steve Block5ff1dd52012-01-05 23:22:43 +00005256 ALOGW("session id %d not found for pid %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005257}
5258
5259void AudioFlinger::purgeStaleEffects_l() {
5260
Steve Block3856b092011-10-20 11:56:00 +01005261 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005262
5263 Vector< sp<EffectChain> > chains;
5264
5265 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5266 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5267 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5268 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005269 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5270 chains.push(ec);
5271 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005272 }
5273 }
5274 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5275 sp<RecordThread> t = mRecordThreads.valueAt(i);
5276 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5277 sp<EffectChain> ec = t->mEffectChains[j];
5278 chains.push(ec);
5279 }
5280 }
5281
5282 for (size_t i = 0; i < chains.size(); i++) {
5283 sp<EffectChain> ec = chains[i];
5284 int sessionid = ec->sessionId();
5285 sp<ThreadBase> t = ec->mThread.promote();
5286 if (t == 0) {
5287 continue;
5288 }
5289 size_t numsessionrefs = mAudioSessionRefs.size();
5290 bool found = false;
5291 for (size_t k = 0; k < numsessionrefs; k++) {
5292 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5293 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005294 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005295 sessionid, ref->pid, ref->cnt);
5296 found = true;
5297 break;
5298 }
5299 }
5300 if (!found) {
5301 // remove all effects from the chain
5302 while (ec->mEffects.size()) {
5303 sp<EffectModule> effect = ec->mEffects[0];
5304 effect->unPin();
5305 Mutex::Autolock _l (t->mLock);
5306 t->removeEffect_l(effect);
5307 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5308 sp<EffectHandle> handle = effect->mHandles[j].promote();
5309 if (handle != 0) {
5310 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005311 if (handle->mHasControl && handle->mEnabled) {
5312 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5313 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005314 }
5315 }
5316 AudioSystem::unregisterEffect(effect->id());
5317 }
5318 }
5319 }
5320 return;
5321}
5322
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5324AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5325{
5326 PlaybackThread *thread = NULL;
5327 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5328 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5329 }
5330 return thread;
5331}
5332
5333// checkMixerThread_l() must be called with AudioFlinger::mLock held
5334AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5335{
5336 PlaybackThread *thread = checkPlaybackThread_l(output);
5337 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005338 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339 thread = NULL;
5340 }
5341 }
5342 return (MixerThread *)thread;
5343}
5344
5345// checkRecordThread_l() must be called with AudioFlinger::mLock held
5346AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5347{
5348 RecordThread *thread = NULL;
5349 if (mRecordThreads.indexOfKey(input) >= 0) {
5350 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5351 }
5352 return thread;
5353}
5354
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005355uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005357 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358}
5359
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005360AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5361{
5362 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5363 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005364 AudioStreamOut *output = thread->getOutput();
5365 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005366 return thread;
5367 }
5368 }
5369 return NULL;
5370}
5371
5372uint32_t AudioFlinger::primaryOutputDevice_l()
5373{
5374 PlaybackThread *thread = primaryPlaybackThread_l();
5375
5376 if (thread == NULL) {
5377 return 0;
5378 }
5379
5380 return thread->device();
5381}
5382
5383
Mathias Agopian65ab4712010-07-14 17:59:35 -07005384// ----------------------------------------------------------------------------
5385// Effect management
5386// ----------------------------------------------------------------------------
5387
5388
Mathias Agopian65ab4712010-07-14 17:59:35 -07005389status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5390{
5391 Mutex::Autolock _l(mLock);
5392 return EffectQueryNumberEffects(numEffects);
5393}
5394
5395status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5396{
5397 Mutex::Autolock _l(mLock);
5398 return EffectQueryEffect(index, descriptor);
5399}
5400
5401status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5402{
5403 Mutex::Autolock _l(mLock);
5404 return EffectGetDescriptor(pUuid, descriptor);
5405}
5406
5407
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5409 effect_descriptor_t *pDesc,
5410 const sp<IEffectClient>& effectClient,
5411 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413 int sessionId,
5414 status_t *status,
5415 int *id,
5416 int *enabled)
5417{
5418 status_t lStatus = NO_ERROR;
5419 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005420 effect_descriptor_t desc;
5421 sp<Client> client;
5422 wp<Client> wclient;
5423
Steve Block3856b092011-10-20 11:56:00 +01005424 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005425 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426
5427 if (pDesc == NULL) {
5428 lStatus = BAD_VALUE;
5429 goto Exit;
5430 }
5431
Eric Laurent84e9a102010-09-23 16:10:16 -07005432 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005433 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005434 lStatus = PERMISSION_DENIED;
5435 goto Exit;
5436 }
5437
Dima Zavinfce7a472011-04-19 22:30:36 -07005438 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005439 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005440 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005441 lStatus = PERMISSION_DENIED;
5442 goto Exit;
5443 }
5444
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005445 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005446 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005447 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005448 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005449 lStatus = BAD_VALUE;
5450 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005451 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005452 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005453 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005454 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005455 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005456 }
5457 }
5458
Mathias Agopian65ab4712010-07-14 17:59:35 -07005459 {
5460 Mutex::Autolock _l(mLock);
5461
Mathias Agopian65ab4712010-07-14 17:59:35 -07005462
5463 if (!EffectIsNullUuid(&pDesc->uuid)) {
5464 // if uuid is specified, request effect descriptor
5465 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5466 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005467 ALOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 goto Exit;
5469 }
5470 } else {
5471 // if uuid is not specified, look for an available implementation
5472 // of the required type in effect factory
5473 if (EffectIsNullUuid(&pDesc->type)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005474 ALOGW("createEffect() no effect type");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 lStatus = BAD_VALUE;
5476 goto Exit;
5477 }
5478 uint32_t numEffects = 0;
5479 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005480 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 bool found = false;
5482
5483 lStatus = EffectQueryNumberEffects(&numEffects);
5484 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005485 ALOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 goto Exit;
5487 }
5488 for (uint32_t i = 0; i < numEffects; i++) {
5489 lStatus = EffectQueryEffect(i, &desc);
5490 if (lStatus < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005491 ALOGW("createEffect() error %d from EffectQueryEffect", lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 continue;
5493 }
5494 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5495 // If matching type found save effect descriptor. If the session is
5496 // 0 and the effect is not auxiliary, continue enumeration in case
5497 // an auxiliary version of this effect type is available
5498 found = true;
5499 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005500 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005501 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5502 break;
5503 }
5504 }
5505 }
5506 if (!found) {
5507 lStatus = BAD_VALUE;
Steve Block5ff1dd52012-01-05 23:22:43 +00005508 ALOGW("createEffect() effect not found");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005509 goto Exit;
5510 }
5511 // For same effect type, chose auxiliary version over insert version if
5512 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005513 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005514 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5515 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5516 }
5517 }
5518
5519 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005520 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5522 lStatus = INVALID_OPERATION;
5523 goto Exit;
5524 }
5525
Eric Laurent59255e42011-07-27 19:49:51 -07005526 // check recording permission for visualizer
5527 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5528 !recordingAllowed()) {
5529 lStatus = PERMISSION_DENIED;
5530 goto Exit;
5531 }
5532
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533 // return effect descriptor
5534 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5535
5536 // If output is not specified try to find a matching audio session ID in one of the
5537 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005538 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5539 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005540 // Note: io is never 0 when creating an effect on an input
5541 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005542 // look for the thread where the specified audio session is present
5543 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5544 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005545 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005546 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005549 if (io == 0) {
5550 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5551 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5552 io = mRecordThreads.keyAt(i);
5553 break;
5554 }
5555 }
5556 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005557 // If no output thread contains the requested session ID, default to
5558 // first output. The effect chain will be moved to the correct output
5559 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005560 if (io == 0 && mPlaybackThreads.size()) {
5561 io = mPlaybackThreads.keyAt(0);
5562 }
Steve Block3856b092011-10-20 11:56:00 +01005563 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005564 }
5565 ThreadBase *thread = checkRecordThread_l(io);
5566 if (thread == NULL) {
5567 thread = checkPlaybackThread_l(io);
5568 if (thread == NULL) {
Steve Block29357bc2012-01-06 19:20:56 +00005569 ALOGE("createEffect() unknown output thread");
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005570 lStatus = BAD_VALUE;
5571 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005574
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575 wclient = mClients.valueFor(pid);
5576
5577 if (wclient != NULL) {
5578 client = wclient.promote();
5579 } else {
5580 client = new Client(this, pid);
5581 mClients.add(pid, client);
5582 }
5583
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005584 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005585 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5586 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005587 if (handle != 0 && id != NULL) {
5588 *id = handle->id();
5589 }
5590 }
5591
5592Exit:
5593 if(status) {
5594 *status = lStatus;
5595 }
5596 return handle;
5597}
5598
Eric Laurent59255e42011-07-27 19:49:51 -07005599status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005600{
Steve Block3856b092011-10-20 11:56:00 +01005601 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005602 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005603 Mutex::Autolock _l(mLock);
5604 if (srcOutput == dstOutput) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005605 ALOGW("moveEffects() same dst and src outputs %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005606 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607 }
Eric Laurentde070132010-07-13 04:45:46 -07005608 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5609 if (srcThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005610 ALOGW("moveEffects() bad srcOutput %d", srcOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005611 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005612 }
Eric Laurentde070132010-07-13 04:45:46 -07005613 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5614 if (dstThread == NULL) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005615 ALOGW("moveEffects() bad dstOutput %d", dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005616 return BAD_VALUE;
5617 }
5618
5619 Mutex::Autolock _dl(dstThread->mLock);
5620 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005621 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005622
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 return NO_ERROR;
5624}
5625
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005626// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005627status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005628 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005629 AudioFlinger::PlaybackThread *dstThread,
5630 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005631{
Steve Block3856b092011-10-20 11:56:00 +01005632 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005633 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005634
Eric Laurent59255e42011-07-27 19:49:51 -07005635 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005636 if (chain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005637 ALOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005638 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005639 return INVALID_OPERATION;
5640 }
5641
Eric Laurent39e94f82010-07-28 01:32:47 -07005642 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005643 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005644 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005645 // removed.
5646 srcThread->removeEffectChain_l(chain);
5647
5648 // transfer all effects one by one so that new effect chain is created on new thread with
5649 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005650 int dstOutput = dstThread->id();
5651 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005652 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005653 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5654 while (effect != 0) {
5655 srcThread->removeEffect_l(effect);
5656 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005657 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5658 if (effect->state() == EffectModule::ACTIVE ||
5659 effect->state() == EffectModule::STOPPING) {
5660 effect->start();
5661 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005662 // if the move request is not received from audio policy manager, the effect must be
5663 // re-registered with the new strategy and output
5664 if (dstChain == 0) {
5665 dstChain = effect->chain().promote();
5666 if (dstChain == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005667 ALOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
Eric Laurent39e94f82010-07-28 01:32:47 -07005668 srcThread->addEffect_l(effect);
5669 return NO_INIT;
5670 }
5671 strategy = dstChain->strategy();
5672 }
5673 if (reRegister) {
5674 AudioSystem::unregisterEffect(effect->id());
5675 AudioSystem::registerEffect(&effect->desc(),
5676 dstOutput,
5677 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005678 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005679 effect->id());
5680 }
Eric Laurentde070132010-07-13 04:45:46 -07005681 effect = chain->getEffectFromId_l(0);
5682 }
5683
5684 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685}
5686
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005687
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005689sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 const sp<AudioFlinger::Client>& client,
5691 const sp<IEffectClient>& effectClient,
5692 int32_t priority,
5693 int sessionId,
5694 effect_descriptor_t *desc,
5695 int *enabled,
5696 status_t *status
5697 )
5698{
5699 sp<EffectModule> effect;
5700 sp<EffectHandle> handle;
5701 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005702 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005703 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 bool effectCreated = false;
5705 bool effectRegistered = false;
5706
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005707 lStatus = initCheck();
5708 if (lStatus != NO_ERROR) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005709 ALOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710 goto Exit;
5711 }
5712
5713 // Do not allow effects with session ID 0 on direct output or duplicating threads
5714 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005715 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005716 ALOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
Eric Laurentde070132010-07-13 04:45:46 -07005717 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 lStatus = BAD_VALUE;
5719 goto Exit;
5720 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005721 // Only Pre processor effects are allowed on input threads and only on input threads
5722 if ((mType == RECORD &&
5723 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5724 (mType != RECORD &&
5725 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005726 ALOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005727 desc->name, desc->flags, mType);
5728 lStatus = BAD_VALUE;
5729 goto Exit;
5730 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005731
Steve Block3856b092011-10-20 11:56:00 +01005732 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733
5734 { // scope for mLock
5735 Mutex::Autolock _l(mLock);
5736
5737 // check for existing effect chain with the requested audio session
5738 chain = getEffectChain_l(sessionId);
5739 if (chain == 0) {
5740 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005741 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 chain = new EffectChain(this, sessionId);
5743 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005744 chain->setStrategy(getStrategyForSession_l(sessionId));
5745 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005747 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748 }
5749
Steve Block3856b092011-10-20 11:56:00 +01005750 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005751
5752 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005753 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005754 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005755 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 if (lStatus != NO_ERROR) {
5757 goto Exit;
5758 }
5759 effectRegistered = true;
5760 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005761 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 lStatus = effect->status();
5763 if (lStatus != NO_ERROR) {
5764 goto Exit;
5765 }
Eric Laurentcab11242010-07-15 12:50:15 -07005766 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767 if (lStatus != NO_ERROR) {
5768 goto Exit;
5769 }
5770 effectCreated = true;
5771
5772 effect->setDevice(mDevice);
5773 effect->setMode(mAudioFlinger->getMode());
5774 }
5775 // create effect handle and connect it to effect module
5776 handle = new EffectHandle(effect, client, effectClient, priority);
5777 lStatus = effect->addHandle(handle);
5778 if (enabled) {
5779 *enabled = (int)effect->isEnabled();
5780 }
5781 }
5782
5783Exit:
5784 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005785 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005786 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005787 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 }
5789 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005790 AudioSystem::unregisterEffect(effect->id());
5791 }
5792 if (chainCreated) {
5793 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005794 }
5795 handle.clear();
5796 }
5797
5798 if(status) {
5799 *status = lStatus;
5800 }
5801 return handle;
5802}
5803
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005804sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5805{
5806 sp<EffectModule> effect;
5807
5808 sp<EffectChain> chain = getEffectChain_l(sessionId);
5809 if (chain != 0) {
5810 effect = chain->getEffectFromId_l(effectId);
5811 }
5812 return effect;
5813}
5814
Eric Laurentde070132010-07-13 04:45:46 -07005815// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5816// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005817status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005818{
5819 // check for existing effect chain with the requested audio session
5820 int sessionId = effect->sessionId();
5821 sp<EffectChain> chain = getEffectChain_l(sessionId);
5822 bool chainCreated = false;
5823
5824 if (chain == 0) {
5825 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005826 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005827 chain = new EffectChain(this, sessionId);
5828 addEffectChain_l(chain);
5829 chain->setStrategy(getStrategyForSession_l(sessionId));
5830 chainCreated = true;
5831 }
Steve Block3856b092011-10-20 11:56:00 +01005832 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005833
5834 if (chain->getEffectFromId_l(effect->id()) != 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00005835 ALOGW("addEffect_l() %p effect %s already present in chain %p",
Eric Laurentde070132010-07-13 04:45:46 -07005836 this, effect->desc().name, chain.get());
5837 return BAD_VALUE;
5838 }
5839
5840 status_t status = chain->addEffect_l(effect);
5841 if (status != NO_ERROR) {
5842 if (chainCreated) {
5843 removeEffectChain_l(chain);
5844 }
5845 return status;
5846 }
5847
5848 effect->setDevice(mDevice);
5849 effect->setMode(mAudioFlinger->getMode());
5850 return NO_ERROR;
5851}
5852
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005853void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005854
Steve Block3856b092011-10-20 11:56:00 +01005855 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005857 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5858 detachAuxEffect_l(effect->id());
5859 }
5860
5861 sp<EffectChain> chain = effect->chain().promote();
5862 if (chain != 0) {
5863 // remove effect chain if removing last effect
5864 if (chain->removeEffect_l(effect) == 0) {
5865 removeEffectChain_l(chain);
5866 }
5867 } else {
Steve Block5ff1dd52012-01-05 23:22:43 +00005868 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005869 }
5870}
5871
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005872void AudioFlinger::ThreadBase::lockEffectChains_l(
5873 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5874{
5875 effectChains = mEffectChains;
5876 for (size_t i = 0; i < mEffectChains.size(); i++) {
5877 mEffectChains[i]->lock();
5878 }
5879}
5880
5881void AudioFlinger::ThreadBase::unlockEffectChains(
5882 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5883{
5884 for (size_t i = 0; i < effectChains.size(); i++) {
5885 effectChains[i]->unlock();
5886 }
5887}
5888
5889sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5890{
5891 Mutex::Autolock _l(mLock);
5892 return getEffectChain_l(sessionId);
5893}
5894
5895sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5896{
5897 sp<EffectChain> chain;
5898
5899 size_t size = mEffectChains.size();
5900 for (size_t i = 0; i < size; i++) {
5901 if (mEffectChains[i]->sessionId() == sessionId) {
5902 chain = mEffectChains[i];
5903 break;
5904 }
5905 }
5906 return chain;
5907}
5908
Glenn Kastenf78aee72012-01-04 11:00:47 -08005909void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005910{
5911 Mutex::Autolock _l(mLock);
5912 size_t size = mEffectChains.size();
5913 for (size_t i = 0; i < size; i++) {
5914 mEffectChains[i]->setMode_l(mode);
5915 }
5916}
5917
5918void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005919 const wp<EffectHandle>& handle,
5920 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005921
Mathias Agopian65ab4712010-07-14 17:59:35 -07005922 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005923 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 // delete the effect module if removing last handle on it
5925 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005926 if (!effect->isPinned() || unpiniflast) {
5927 removeEffect_l(effect);
5928 AudioSystem::unregisterEffect(effect->id());
5929 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 }
5931}
5932
5933status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5934{
5935 int session = chain->sessionId();
5936 int16_t *buffer = mMixBuffer;
5937 bool ownsBuffer = false;
5938
Steve Block3856b092011-10-20 11:56:00 +01005939 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 if (session > 0) {
5941 // Only one effect chain can be present in direct output thread and it uses
5942 // the mix buffer as input
5943 if (mType != DIRECT) {
5944 size_t numSamples = mFrameCount * mChannelCount;
5945 buffer = new int16_t[numSamples];
5946 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005947 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 ownsBuffer = true;
5949 }
5950
5951 // Attach all tracks with same session ID to this chain.
5952 for (size_t i = 0; i < mTracks.size(); ++i) {
5953 sp<Track> track = mTracks[i];
5954 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005955 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005957 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 }
5959 }
5960
5961 // indicate all active tracks in the chain
5962 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5963 sp<Track> track = mActiveTracks[i].promote();
5964 if (track == 0) continue;
5965 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005966 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005967 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005968 }
5969 }
5970 }
5971
5972 chain->setInBuffer(buffer, ownsBuffer);
5973 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005974 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005975 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005976 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5977 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005978 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005979 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5980 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005981 // Effect chain for other sessions are inserted at beginning of effect
5982 // chains list to be processed before output mix effects. Relative order between other
5983 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 size_t size = mEffectChains.size();
5985 size_t i = 0;
5986 for (i = 0; i < size; i++) {
5987 if (mEffectChains[i]->sessionId() < session) break;
5988 }
5989 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005990 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991
5992 return NO_ERROR;
5993}
5994
5995size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5996{
5997 int session = chain->sessionId();
5998
Steve Block3856b092011-10-20 11:56:00 +01005999 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006000
6001 for (size_t i = 0; i < mEffectChains.size(); i++) {
6002 if (chain == mEffectChains[i]) {
6003 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006004 // detach all active tracks from the chain
6005 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6006 sp<Track> track = mActiveTracks[i].promote();
6007 if (track == 0) continue;
6008 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01006009 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07006010 chain.get(), session);
6011 chain->decActiveTrackCnt();
6012 }
6013 }
6014
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015 // detach all tracks with same session ID from this chain
6016 for (size_t i = 0; i < mTracks.size(); ++i) {
6017 sp<Track> track = mTracks[i];
6018 if (session == track->sessionId()) {
6019 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006020 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006021 }
6022 }
Eric Laurentde070132010-07-13 04:45:46 -07006023 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 }
6025 }
6026 return mEffectChains.size();
6027}
6028
Eric Laurentde070132010-07-13 04:45:46 -07006029status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6030 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006031{
6032 Mutex::Autolock _l(mLock);
6033 return attachAuxEffect_l(track, EffectId);
6034}
6035
Eric Laurentde070132010-07-13 04:45:46 -07006036status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6037 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038{
6039 status_t status = NO_ERROR;
6040
6041 if (EffectId == 0) {
6042 track->setAuxBuffer(0, NULL);
6043 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006044 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6045 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 if (effect != 0) {
6047 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6048 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6049 } else {
6050 status = INVALID_OPERATION;
6051 }
6052 } else {
6053 status = BAD_VALUE;
6054 }
6055 }
6056 return status;
6057}
6058
6059void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6060{
6061 for (size_t i = 0; i < mTracks.size(); ++i) {
6062 sp<Track> track = mTracks[i];
6063 if (track->auxEffectId() == effectId) {
6064 attachAuxEffect_l(track, 0);
6065 }
6066 }
6067}
6068
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006069status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6070{
6071 // only one chain per input thread
6072 if (mEffectChains.size() != 0) {
6073 return INVALID_OPERATION;
6074 }
Steve Block3856b092011-10-20 11:56:00 +01006075 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006076
6077 chain->setInBuffer(NULL);
6078 chain->setOutBuffer(NULL);
6079
Eric Laurent59255e42011-07-27 19:49:51 -07006080 checkSuspendOnAddEffectChain_l(chain);
6081
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006082 mEffectChains.add(chain);
6083
6084 return NO_ERROR;
6085}
6086
6087size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6088{
Steve Block3856b092011-10-20 11:56:00 +01006089 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Steve Block5ff1dd52012-01-05 23:22:43 +00006090 ALOGW_IF(mEffectChains.size() != 1,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006091 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6092 chain.get(), mEffectChains.size(), this);
6093 if (mEffectChains.size() == 1) {
6094 mEffectChains.removeAt(0);
6095 }
6096 return 0;
6097}
6098
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099// ----------------------------------------------------------------------------
6100// EffectModule implementation
6101// ----------------------------------------------------------------------------
6102
6103#undef LOG_TAG
6104#define LOG_TAG "AudioFlinger::EffectModule"
6105
6106AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6107 const wp<AudioFlinger::EffectChain>& chain,
6108 effect_descriptor_t *desc,
6109 int id,
6110 int sessionId)
6111 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006112 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006113{
Steve Block3856b092011-10-20 11:56:00 +01006114 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006115 int lStatus;
6116 sp<ThreadBase> thread = mThread.promote();
6117 if (thread == 0) {
6118 return;
6119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120
6121 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6122
6123 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006124 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006125
6126 if (mStatus != NO_ERROR) {
6127 return;
6128 }
6129 lStatus = init();
6130 if (lStatus < 0) {
6131 mStatus = lStatus;
6132 goto Error;
6133 }
6134
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006135 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6136 mPinned = true;
6137 }
Steve Block3856b092011-10-20 11:56:00 +01006138 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006139 return;
6140Error:
6141 EffectRelease(mEffectInterface);
6142 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006143 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006144}
6145
6146AudioFlinger::EffectModule::~EffectModule()
6147{
Steve Block3856b092011-10-20 11:56:00 +01006148 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006150 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6151 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6152 sp<ThreadBase> thread = mThread.promote();
6153 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006154 audio_stream_t *stream = thread->stream();
6155 if (stream != NULL) {
6156 stream->remove_audio_effect(stream, mEffectInterface);
6157 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006158 }
6159 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 // release effect engine
6161 EffectRelease(mEffectInterface);
6162 }
6163}
6164
6165status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6166{
6167 status_t status;
6168
6169 Mutex::Autolock _l(mLock);
6170 // First handle in mHandles has highest priority and controls the effect module
6171 int priority = handle->priority();
6172 size_t size = mHandles.size();
6173 sp<EffectHandle> h;
6174 size_t i;
6175 for (i = 0; i < size; i++) {
6176 h = mHandles[i].promote();
6177 if (h == 0) continue;
6178 if (h->priority() <= priority) break;
6179 }
6180 // if inserted in first place, move effect control from previous owner to this handle
6181 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006182 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006184 enabled = h->enabled();
6185 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 }
Eric Laurent59255e42011-07-27 19:49:51 -07006187 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 status = NO_ERROR;
6189 } else {
6190 status = ALREADY_EXISTS;
6191 }
Steve Block3856b092011-10-20 11:56:00 +01006192 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 mHandles.insertAt(handle, i);
6194 return status;
6195}
6196
6197size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6198{
6199 Mutex::Autolock _l(mLock);
6200 size_t size = mHandles.size();
6201 size_t i;
6202 for (i = 0; i < size; i++) {
6203 if (mHandles[i] == handle) break;
6204 }
6205 if (i == size) {
6206 return size;
6207 }
Steve Block3856b092011-10-20 11:56:00 +01006208 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006209
6210 bool enabled = false;
6211 EffectHandle *hdl = handle.unsafe_get();
6212 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006213 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006214 enabled = hdl->enabled();
6215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 mHandles.removeAt(i);
6217 size = mHandles.size();
6218 // if removed from first place, move effect control from this handle to next in line
6219 if (i == 0 && size != 0) {
6220 sp<EffectHandle> h = mHandles[0].promote();
6221 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006222 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 }
6224 }
6225
Eric Laurentec437d82011-07-26 20:54:46 -07006226 // Prevent calls to process() and other functions on effect interface from now on.
6227 // The effect engine will be released by the destructor when the last strong reference on
6228 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006229 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006230 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006231 }
6232
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 return size;
6234}
6235
Eric Laurent59255e42011-07-27 19:49:51 -07006236sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6237{
6238 Mutex::Autolock _l(mLock);
6239 sp<EffectHandle> handle;
6240 if (mHandles.size() != 0) {
6241 handle = mHandles[0].promote();
6242 }
6243 return handle;
6244}
6245
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006246void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006247{
Steve Block3856b092011-10-20 11:56:00 +01006248 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006249 // keep a strong reference on this EffectModule to avoid calling the
6250 // destructor before we exit
6251 sp<EffectModule> keep(this);
6252 {
6253 sp<ThreadBase> thread = mThread.promote();
6254 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006255 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 }
6257 }
6258}
6259
6260void AudioFlinger::EffectModule::updateState() {
6261 Mutex::Autolock _l(mLock);
6262
6263 switch (mState) {
6264 case RESTART:
6265 reset_l();
6266 // FALL THROUGH
6267
6268 case STARTING:
6269 // clear auxiliary effect input buffer for next accumulation
6270 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6271 memset(mConfig.inputCfg.buffer.raw,
6272 0,
6273 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6274 }
6275 start_l();
6276 mState = ACTIVE;
6277 break;
6278 case STOPPING:
6279 stop_l();
6280 mDisableWaitCnt = mMaxDisableWaitCnt;
6281 mState = STOPPED;
6282 break;
6283 case STOPPED:
6284 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6285 // turn off sequence.
6286 if (--mDisableWaitCnt == 0) {
6287 reset_l();
6288 mState = IDLE;
6289 }
6290 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006291 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 break;
6293 }
6294}
6295
6296void AudioFlinger::EffectModule::process()
6297{
6298 Mutex::Autolock _l(mLock);
6299
Eric Laurentec437d82011-07-26 20:54:46 -07006300 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006301 mConfig.inputCfg.buffer.raw == NULL ||
6302 mConfig.outputCfg.buffer.raw == NULL) {
6303 return;
6304 }
6305
Eric Laurent8f45bd72010-08-31 13:50:07 -07006306 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6308 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006309 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006311 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 }
6313
6314 // do the actual processing in the effect engine
6315 int ret = (*mEffectInterface)->process(mEffectInterface,
6316 &mConfig.inputCfg.buffer,
6317 &mConfig.outputCfg.buffer);
6318
6319 // force transition to IDLE state when engine is ready
6320 if (mState == STOPPED && ret == -ENODATA) {
6321 mDisableWaitCnt = 1;
6322 }
6323
6324 // clear auxiliary effect input buffer for next accumulation
6325 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006326 memset(mConfig.inputCfg.buffer.raw, 0,
6327 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006328 }
6329 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006330 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6331 // If an insert effect is idle and input buffer is different from output buffer,
6332 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006334 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006335 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6336 int16_t *in = mConfig.inputCfg.buffer.s16;
6337 int16_t *out = mConfig.outputCfg.buffer.s16;
6338 for (size_t i = 0; i < frameCnt; i++) {
6339 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 }
6342 }
6343}
6344
6345void AudioFlinger::EffectModule::reset_l()
6346{
6347 if (mEffectInterface == NULL) {
6348 return;
6349 }
6350 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6351}
6352
6353status_t AudioFlinger::EffectModule::configure()
6354{
6355 uint32_t channels;
6356 if (mEffectInterface == NULL) {
6357 return NO_INIT;
6358 }
6359
6360 sp<ThreadBase> thread = mThread.promote();
6361 if (thread == 0) {
6362 return DEAD_OBJECT;
6363 }
6364
6365 // TODO: handle configuration of effects replacing track process
6366 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006367 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006369 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 }
6371
6372 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006373 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 } else {
6375 mConfig.inputCfg.channels = channels;
6376 }
6377 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006378 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6379 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 mConfig.inputCfg.samplingRate = thread->sampleRate();
6381 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6382 mConfig.inputCfg.bufferProvider.cookie = NULL;
6383 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6384 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6385 mConfig.outputCfg.bufferProvider.cookie = NULL;
6386 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6387 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6388 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6389 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006390 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006391 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 // - in other sessions:
6393 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6394 // other effect: overwrites output buffer: input buffer == output buffer
6395 // Auxiliary effect:
6396 // accumulates in output buffer: input buffer != output buffer
6397 // Therefore: accumulate <=> input buffer != output buffer
6398 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6399 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6400 } else {
6401 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6402 }
6403 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6404 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6405 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6406 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6407
Steve Block3856b092011-10-20 11:56:00 +01006408 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006409 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6410
Mathias Agopian65ab4712010-07-14 17:59:35 -07006411 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006412 uint32_t size = sizeof(int);
6413 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006414 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006415 sizeof(effect_config_t),
6416 &mConfig,
6417 &size,
6418 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006419 if (status == 0) {
6420 status = cmdStatus;
6421 }
6422
6423 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6424 (1000 * mConfig.outputCfg.buffer.frameCount);
6425
6426 return status;
6427}
6428
6429status_t AudioFlinger::EffectModule::init()
6430{
6431 Mutex::Autolock _l(mLock);
6432 if (mEffectInterface == NULL) {
6433 return NO_INIT;
6434 }
6435 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006436 uint32_t size = sizeof(status_t);
6437 status_t status = (*mEffectInterface)->command(mEffectInterface,
6438 EFFECT_CMD_INIT,
6439 0,
6440 NULL,
6441 &size,
6442 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006443 if (status == 0) {
6444 status = cmdStatus;
6445 }
6446 return status;
6447}
6448
Eric Laurentec35a142011-10-05 17:42:25 -07006449status_t AudioFlinger::EffectModule::start()
6450{
6451 Mutex::Autolock _l(mLock);
6452 return start_l();
6453}
6454
Mathias Agopian65ab4712010-07-14 17:59:35 -07006455status_t AudioFlinger::EffectModule::start_l()
6456{
6457 if (mEffectInterface == NULL) {
6458 return NO_INIT;
6459 }
6460 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006461 uint32_t size = sizeof(status_t);
6462 status_t status = (*mEffectInterface)->command(mEffectInterface,
6463 EFFECT_CMD_ENABLE,
6464 0,
6465 NULL,
6466 &size,
6467 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 if (status == 0) {
6469 status = cmdStatus;
6470 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006471 if (status == 0 &&
6472 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6473 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6474 sp<ThreadBase> thread = mThread.promote();
6475 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006476 audio_stream_t *stream = thread->stream();
6477 if (stream != NULL) {
6478 stream->add_audio_effect(stream, mEffectInterface);
6479 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006480 }
6481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006482 return status;
6483}
6484
Eric Laurentec437d82011-07-26 20:54:46 -07006485status_t AudioFlinger::EffectModule::stop()
6486{
6487 Mutex::Autolock _l(mLock);
6488 return stop_l();
6489}
6490
Mathias Agopian65ab4712010-07-14 17:59:35 -07006491status_t AudioFlinger::EffectModule::stop_l()
6492{
6493 if (mEffectInterface == NULL) {
6494 return NO_INIT;
6495 }
6496 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006497 uint32_t size = sizeof(status_t);
6498 status_t status = (*mEffectInterface)->command(mEffectInterface,
6499 EFFECT_CMD_DISABLE,
6500 0,
6501 NULL,
6502 &size,
6503 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 if (status == 0) {
6505 status = cmdStatus;
6506 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006507 if (status == 0 &&
6508 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6509 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6510 sp<ThreadBase> thread = mThread.promote();
6511 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006512 audio_stream_t *stream = thread->stream();
6513 if (stream != NULL) {
6514 stream->remove_audio_effect(stream, mEffectInterface);
6515 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006516 }
6517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006518 return status;
6519}
6520
Eric Laurent25f43952010-07-28 05:40:18 -07006521status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6522 uint32_t cmdSize,
6523 void *pCmdData,
6524 uint32_t *replySize,
6525 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526{
6527 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006528// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006529
Eric Laurentec437d82011-07-26 20:54:46 -07006530 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531 return NO_INIT;
6532 }
Eric Laurent25f43952010-07-28 05:40:18 -07006533 status_t status = (*mEffectInterface)->command(mEffectInterface,
6534 cmdCode,
6535 cmdSize,
6536 pCmdData,
6537 replySize,
6538 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006540 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541 for (size_t i = 1; i < mHandles.size(); i++) {
6542 sp<EffectHandle> h = mHandles[i].promote();
6543 if (h != 0) {
6544 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6545 }
6546 }
6547 }
6548 return status;
6549}
6550
6551status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6552{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006553
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006555 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556
6557 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006558 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6559 if (enabled && status != NO_ERROR) {
6560 return status;
6561 }
6562
Mathias Agopian65ab4712010-07-14 17:59:35 -07006563 switch (mState) {
6564 // going from disabled to enabled
6565 case IDLE:
6566 mState = STARTING;
6567 break;
6568 case STOPPED:
6569 mState = RESTART;
6570 break;
6571 case STOPPING:
6572 mState = ACTIVE;
6573 break;
6574
6575 // going from enabled to disabled
6576 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006577 mState = STOPPED;
6578 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 case STARTING:
6580 mState = IDLE;
6581 break;
6582 case ACTIVE:
6583 mState = STOPPING;
6584 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006585 case DESTROYED:
6586 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006587 }
6588 for (size_t i = 1; i < mHandles.size(); i++) {
6589 sp<EffectHandle> h = mHandles[i].promote();
6590 if (h != 0) {
6591 h->setEnabled(enabled);
6592 }
6593 }
6594 }
6595 return NO_ERROR;
6596}
6597
6598bool AudioFlinger::EffectModule::isEnabled()
6599{
6600 switch (mState) {
6601 case RESTART:
6602 case STARTING:
6603 case ACTIVE:
6604 return true;
6605 case IDLE:
6606 case STOPPING:
6607 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006608 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006609 default:
6610 return false;
6611 }
6612}
6613
Eric Laurent8f45bd72010-08-31 13:50:07 -07006614bool AudioFlinger::EffectModule::isProcessEnabled()
6615{
6616 switch (mState) {
6617 case RESTART:
6618 case ACTIVE:
6619 case STOPPING:
6620 case STOPPED:
6621 return true;
6622 case IDLE:
6623 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006624 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006625 default:
6626 return false;
6627 }
6628}
6629
Mathias Agopian65ab4712010-07-14 17:59:35 -07006630status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6631{
6632 Mutex::Autolock _l(mLock);
6633 status_t status = NO_ERROR;
6634
6635 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6636 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006637 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006638 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6639 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640 status_t cmdStatus;
6641 uint32_t volume[2];
6642 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006643 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006644 volume[0] = *left;
6645 volume[1] = *right;
6646 if (controller) {
6647 pVolume = volume;
6648 }
Eric Laurent25f43952010-07-28 05:40:18 -07006649 status = (*mEffectInterface)->command(mEffectInterface,
6650 EFFECT_CMD_SET_VOLUME,
6651 size,
6652 volume,
6653 &size,
6654 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006655 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6656 *left = volume[0];
6657 *right = volume[1];
6658 }
6659 }
6660 return status;
6661}
6662
6663status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6664{
6665 Mutex::Autolock _l(mLock);
6666 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006667 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6668 // audio pre processing modules on RecordThread can receive both output and
6669 // input device indication in the same call
6670 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6671 if (dev) {
6672 status_t cmdStatus;
6673 uint32_t size = sizeof(status_t);
6674
6675 status = (*mEffectInterface)->command(mEffectInterface,
6676 EFFECT_CMD_SET_DEVICE,
6677 sizeof(uint32_t),
6678 &dev,
6679 &size,
6680 &cmdStatus);
6681 if (status == NO_ERROR) {
6682 status = cmdStatus;
6683 }
6684 }
6685 dev = device & AUDIO_DEVICE_IN_ALL;
6686 if (dev) {
6687 status_t cmdStatus;
6688 uint32_t size = sizeof(status_t);
6689
6690 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6691 EFFECT_CMD_SET_INPUT_DEVICE,
6692 sizeof(uint32_t),
6693 &dev,
6694 &size,
6695 &cmdStatus);
6696 if (status2 == NO_ERROR) {
6697 status2 = cmdStatus;
6698 }
6699 if (status == NO_ERROR) {
6700 status = status2;
6701 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 }
6703 }
6704 return status;
6705}
6706
Glenn Kastenf78aee72012-01-04 11:00:47 -08006707status_t AudioFlinger::EffectModule::setMode(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006708{
6709 Mutex::Autolock _l(mLock);
6710 status_t status = NO_ERROR;
6711 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006712 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006713 uint32_t size = sizeof(status_t);
6714 status = (*mEffectInterface)->command(mEffectInterface,
6715 EFFECT_CMD_SET_AUDIO_MODE,
Glenn Kastenf78aee72012-01-04 11:00:47 -08006716 sizeof(audio_mode_t),
Eric Laurente1315cf2011-05-17 19:16:02 -07006717 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006718 &size,
6719 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006720 if (status == NO_ERROR) {
6721 status = cmdStatus;
6722 }
6723 }
6724 return status;
6725}
6726
Eric Laurent59255e42011-07-27 19:49:51 -07006727void AudioFlinger::EffectModule::setSuspended(bool suspended)
6728{
6729 Mutex::Autolock _l(mLock);
6730 mSuspended = suspended;
6731}
Glenn Kastena3a85482012-01-04 11:01:11 -08006732
6733bool AudioFlinger::EffectModule::suspended() const
Eric Laurent59255e42011-07-27 19:49:51 -07006734{
6735 Mutex::Autolock _l(mLock);
6736 return mSuspended;
6737}
6738
Mathias Agopian65ab4712010-07-14 17:59:35 -07006739status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6740{
6741 const size_t SIZE = 256;
6742 char buffer[SIZE];
6743 String8 result;
6744
6745 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6746 result.append(buffer);
6747
6748 bool locked = tryLock(mLock);
6749 // failed to lock - AudioFlinger is probably deadlocked
6750 if (!locked) {
6751 result.append("\t\tCould not lock Fx mutex:\n");
6752 }
6753
6754 result.append("\t\tSession Status State Engine:\n");
6755 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6756 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6757 result.append(buffer);
6758
6759 result.append("\t\tDescriptor:\n");
6760 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6761 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6762 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6763 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6764 result.append(buffer);
6765 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6766 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6767 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6768 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6769 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006770 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006771 mDescriptor.apiVersion,
6772 mDescriptor.flags);
6773 result.append(buffer);
6774 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6775 mDescriptor.name);
6776 result.append(buffer);
6777 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6778 mDescriptor.implementor);
6779 result.append(buffer);
6780
6781 result.append("\t\t- Input configuration:\n");
6782 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6783 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6784 (uint32_t)mConfig.inputCfg.buffer.raw,
6785 mConfig.inputCfg.buffer.frameCount,
6786 mConfig.inputCfg.samplingRate,
6787 mConfig.inputCfg.channels,
6788 mConfig.inputCfg.format);
6789 result.append(buffer);
6790
6791 result.append("\t\t- Output configuration:\n");
6792 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6793 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6794 (uint32_t)mConfig.outputCfg.buffer.raw,
6795 mConfig.outputCfg.buffer.frameCount,
6796 mConfig.outputCfg.samplingRate,
6797 mConfig.outputCfg.channels,
6798 mConfig.outputCfg.format);
6799 result.append(buffer);
6800
6801 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6802 result.append(buffer);
6803 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6804 for (size_t i = 0; i < mHandles.size(); ++i) {
6805 sp<EffectHandle> handle = mHandles[i].promote();
6806 if (handle != 0) {
6807 handle->dump(buffer, SIZE);
6808 result.append(buffer);
6809 }
6810 }
6811
6812 result.append("\n");
6813
6814 write(fd, result.string(), result.length());
6815
6816 if (locked) {
6817 mLock.unlock();
6818 }
6819
6820 return NO_ERROR;
6821}
6822
6823// ----------------------------------------------------------------------------
6824// EffectHandle implementation
6825// ----------------------------------------------------------------------------
6826
6827#undef LOG_TAG
6828#define LOG_TAG "AudioFlinger::EffectHandle"
6829
6830AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6831 const sp<AudioFlinger::Client>& client,
6832 const sp<IEffectClient>& effectClient,
6833 int32_t priority)
6834 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006835 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006836 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837{
Steve Block3856b092011-10-20 11:56:00 +01006838 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006840 if (client == 0) {
6841 return;
6842 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006843 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6844 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6845 if (mCblkMemory != 0) {
6846 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6847
6848 if (mCblk) {
6849 new(mCblk) effect_param_cblk_t();
6850 mBuffer = (uint8_t *)mCblk + bufOffset;
6851 }
6852 } else {
Steve Block29357bc2012-01-06 19:20:56 +00006853 ALOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854 return;
6855 }
6856}
6857
6858AudioFlinger::EffectHandle::~EffectHandle()
6859{
Steve Block3856b092011-10-20 11:56:00 +01006860 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006861 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006862 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006863}
6864
6865status_t AudioFlinger::EffectHandle::enable()
6866{
Steve Block3856b092011-10-20 11:56:00 +01006867 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868 if (!mHasControl) return INVALID_OPERATION;
6869 if (mEffect == 0) return DEAD_OBJECT;
6870
Eric Laurentdb7c0792011-08-10 10:37:50 -07006871 if (mEnabled) {
6872 return NO_ERROR;
6873 }
6874
Eric Laurent59255e42011-07-27 19:49:51 -07006875 mEnabled = true;
6876
6877 sp<ThreadBase> thread = mEffect->thread().promote();
6878 if (thread != 0) {
6879 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6880 }
6881
6882 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6883 if (mEffect->suspended()) {
6884 return NO_ERROR;
6885 }
6886
Eric Laurentdb7c0792011-08-10 10:37:50 -07006887 status_t status = mEffect->setEnabled(true);
6888 if (status != NO_ERROR) {
6889 if (thread != 0) {
6890 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6891 }
6892 mEnabled = false;
6893 }
6894 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006895}
6896
6897status_t AudioFlinger::EffectHandle::disable()
6898{
Steve Block3856b092011-10-20 11:56:00 +01006899 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006901 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902
Eric Laurentdb7c0792011-08-10 10:37:50 -07006903 if (!mEnabled) {
6904 return NO_ERROR;
6905 }
Eric Laurent59255e42011-07-27 19:49:51 -07006906 mEnabled = false;
6907
6908 if (mEffect->suspended()) {
6909 return NO_ERROR;
6910 }
6911
6912 status_t status = mEffect->setEnabled(false);
6913
6914 sp<ThreadBase> thread = mEffect->thread().promote();
6915 if (thread != 0) {
6916 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6917 }
6918
6919 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920}
6921
6922void AudioFlinger::EffectHandle::disconnect()
6923{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006924 disconnect(true);
6925}
6926
6927void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6928{
Steve Block3856b092011-10-20 11:56:00 +01006929 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930 if (mEffect == 0) {
6931 return;
6932 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006933 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006934
Eric Laurenta85a74a2011-10-19 11:44:54 -07006935 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006936 sp<ThreadBase> thread = mEffect->thread().promote();
6937 if (thread != 0) {
6938 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6939 }
Eric Laurent59255e42011-07-27 19:49:51 -07006940 }
6941
Mathias Agopian65ab4712010-07-14 17:59:35 -07006942 // release sp on module => module destructor can be called now
6943 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006945 if (mCblk) {
6946 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6947 }
6948 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006949 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6950 mClient.clear();
6951 }
6952}
6953
Eric Laurent25f43952010-07-28 05:40:18 -07006954status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6955 uint32_t cmdSize,
6956 void *pCmdData,
6957 uint32_t *replySize,
6958 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959{
Steve Block3856b092011-10-20 11:56:00 +01006960// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006961// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006962
6963 // only get parameter command is permitted for applications not controlling the effect
6964 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6965 return INVALID_OPERATION;
6966 }
6967 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006968 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969
6970 // handle commands that are not forwarded transparently to effect engine
6971 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6972 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6973 // no risk to block the whole media server process or mixer threads is we are stuck here
6974 Mutex::Autolock _l(mCblk->lock);
6975 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6976 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6977 mCblk->serverIndex = 0;
6978 mCblk->clientIndex = 0;
6979 return BAD_VALUE;
6980 }
6981 status_t status = NO_ERROR;
6982 while (mCblk->serverIndex < mCblk->clientIndex) {
6983 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006984 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006985 int *p = (int *)(mBuffer + mCblk->serverIndex);
6986 int size = *p++;
6987 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006988 ALOGW("command(): invalid parameter block size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006989 break;
6990 }
6991 effect_param_t *param = (effect_param_t *)p;
6992 if (param->psize == 0 || param->vsize == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00006993 ALOGW("command(): null parameter or value size");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 mCblk->serverIndex += size;
6995 continue;
6996 }
Eric Laurent25f43952010-07-28 05:40:18 -07006997 uint32_t psize = sizeof(effect_param_t) +
6998 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6999 param->vsize;
7000 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7001 psize,
7002 p,
7003 &rsize,
7004 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007005 // stop at first error encountered
7006 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007008 *(int *)pReplyData = reply;
7009 break;
7010 } else if (reply != NO_ERROR) {
7011 *(int *)pReplyData = reply;
7012 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013 }
7014 mCblk->serverIndex += size;
7015 }
7016 mCblk->serverIndex = 0;
7017 mCblk->clientIndex = 0;
7018 return status;
7019 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007020 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 return enable();
7022 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007023 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007024 return disable();
7025 }
7026
7027 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7028}
7029
7030sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7031 return mCblkMemory;
7032}
7033
Eric Laurent59255e42011-07-27 19:49:51 -07007034void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007035{
Steve Block3856b092011-10-20 11:56:00 +01007036 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007037
7038 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007039 mEnabled = enabled;
7040
Mathias Agopian65ab4712010-07-14 17:59:35 -07007041 if (signal && mEffectClient != 0) {
7042 mEffectClient->controlStatusChanged(hasControl);
7043 }
7044}
7045
Eric Laurent25f43952010-07-28 05:40:18 -07007046void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7047 uint32_t cmdSize,
7048 void *pCmdData,
7049 uint32_t replySize,
7050 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051{
7052 if (mEffectClient != 0) {
7053 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7054 }
7055}
7056
7057
7058
7059void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7060{
7061 if (mEffectClient != 0) {
7062 mEffectClient->enableStatusChanged(enabled);
7063 }
7064}
7065
7066status_t AudioFlinger::EffectHandle::onTransact(
7067 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7068{
7069 return BnEffect::onTransact(code, data, reply, flags);
7070}
7071
7072
7073void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7074{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007075 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076
7077 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7078 (mClient == NULL) ? getpid() : mClient->pid(),
7079 mPriority,
7080 mHasControl,
7081 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007082 mCblk ? mCblk->clientIndex : 0,
7083 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 );
7085
7086 if (locked) {
7087 mCblk->lock.unlock();
7088 }
7089}
7090
7091#undef LOG_TAG
7092#define LOG_TAG "AudioFlinger::EffectChain"
7093
7094AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7095 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007096 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007097 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7098 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099{
Dima Zavinfce7a472011-04-19 22:30:36 -07007100 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007101 sp<ThreadBase> thread = mThread.promote();
7102 if (thread == 0) {
7103 return;
7104 }
7105 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7106 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107}
7108
7109AudioFlinger::EffectChain::~EffectChain()
7110{
7111 if (mOwnInBuffer) {
7112 delete mInBuffer;
7113 }
7114
7115}
7116
Eric Laurent59255e42011-07-27 19:49:51 -07007117// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007118sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119{
7120 sp<EffectModule> effect;
7121 size_t size = mEffects.size();
7122
7123 for (size_t i = 0; i < size; i++) {
7124 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7125 effect = mEffects[i];
7126 break;
7127 }
7128 }
7129 return effect;
7130}
7131
Eric Laurent59255e42011-07-27 19:49:51 -07007132// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007133sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007134{
7135 sp<EffectModule> effect;
7136 size_t size = mEffects.size();
7137
7138 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007139 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7140 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007141 effect = mEffects[i];
7142 break;
7143 }
7144 }
7145 return effect;
7146}
7147
Eric Laurent59255e42011-07-27 19:49:51 -07007148// getEffectFromType_l() must be called with ThreadBase::mLock held
7149sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7150 const effect_uuid_t *type)
7151{
7152 sp<EffectModule> effect;
7153 size_t size = mEffects.size();
7154
7155 for (size_t i = 0; i < size; i++) {
7156 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7157 effect = mEffects[i];
7158 break;
7159 }
7160 }
7161 return effect;
7162}
7163
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164// Must be called with EffectChain::mLock locked
7165void AudioFlinger::EffectChain::process_l()
7166{
Eric Laurentdac69112010-09-28 14:09:57 -07007167 sp<ThreadBase> thread = mThread.promote();
7168 if (thread == 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007169 ALOGW("process_l(): cannot promote mixer thread");
Eric Laurentdac69112010-09-28 14:09:57 -07007170 return;
7171 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007172 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7173 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007174 // always process effects unless no more tracks are on the session and the effect tail
7175 // has been rendered
7176 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007177 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007178 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007179
Eric Laurent544fe9b2011-11-11 15:42:52 -08007180 if (!tracksOnSession && mTailBufferCount == 0) {
7181 doProcess = false;
7182 }
7183
7184 if (activeTrackCnt() == 0) {
7185 // if no track is active and the effect tail has not been rendered,
7186 // the input buffer must be cleared here as the mixer process will not do it
7187 if (tracksOnSession || mTailBufferCount > 0) {
7188 size_t numSamples = thread->frameCount() * thread->channelCount();
7189 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7190 if (mTailBufferCount > 0) {
7191 mTailBufferCount--;
7192 }
7193 }
7194 }
Eric Laurentdac69112010-09-28 14:09:57 -07007195 }
7196
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007198 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007199 for (size_t i = 0; i < size; i++) {
7200 mEffects[i]->process();
7201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202 }
7203 for (size_t i = 0; i < size; i++) {
7204 mEffects[i]->updateState();
7205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206}
7207
Eric Laurentcab11242010-07-15 12:50:15 -07007208// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007209status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007210{
7211 effect_descriptor_t desc = effect->desc();
7212 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7213
7214 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007215 effect->setChain(this);
7216 sp<ThreadBase> thread = mThread.promote();
7217 if (thread == 0) {
7218 return NO_INIT;
7219 }
7220 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221
7222 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7223 // Auxiliary effects are inserted at the beginning of mEffects vector as
7224 // they are processed first and accumulated in chain input buffer
7225 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007226
Mathias Agopian65ab4712010-07-14 17:59:35 -07007227 // the input buffer for auxiliary effect contains mono samples in
7228 // 32 bit format. This is to avoid saturation in AudoMixer
7229 // accumulation stage. Saturation is done in EffectModule::process() before
7230 // calling the process in effect engine
7231 size_t numSamples = thread->frameCount();
7232 int32_t *buffer = new int32_t[numSamples];
7233 memset(buffer, 0, numSamples * sizeof(int32_t));
7234 effect->setInBuffer((int16_t *)buffer);
7235 // auxiliary effects output samples to chain input buffer for further processing
7236 // by insert effects
7237 effect->setOutBuffer(mInBuffer);
7238 } else {
7239 // Insert effects are inserted at the end of mEffects vector as they are processed
7240 // after track and auxiliary effects.
7241 // Insert effect order as a function of indicated preference:
7242 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7243 // another effect is present
7244 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7245 // last effect claiming first position
7246 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7247 // first effect claiming last position
7248 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7249 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7250 // already present
7251
7252 int size = (int)mEffects.size();
7253 int idx_insert = size;
7254 int idx_insert_first = -1;
7255 int idx_insert_last = -1;
7256
7257 for (int i = 0; i < size; i++) {
7258 effect_descriptor_t d = mEffects[i]->desc();
7259 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7260 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7261 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7262 // check invalid effect chaining combinations
7263 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7264 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007265 ALOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007266 return INVALID_OPERATION;
7267 }
7268 // remember position of first insert effect and by default
7269 // select this as insert position for new effect
7270 if (idx_insert == size) {
7271 idx_insert = i;
7272 }
7273 // remember position of last insert effect claiming
7274 // first position
7275 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7276 idx_insert_first = i;
7277 }
7278 // remember position of first insert effect claiming
7279 // last position
7280 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7281 idx_insert_last == -1) {
7282 idx_insert_last = i;
7283 }
7284 }
7285 }
7286
7287 // modify idx_insert from first position if needed
7288 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7289 if (idx_insert_last != -1) {
7290 idx_insert = idx_insert_last;
7291 } else {
7292 idx_insert = size;
7293 }
7294 } else {
7295 if (idx_insert_first != -1) {
7296 idx_insert = idx_insert_first + 1;
7297 }
7298 }
7299
7300 // always read samples from chain input buffer
7301 effect->setInBuffer(mInBuffer);
7302
7303 // if last effect in the chain, output samples to chain
7304 // output buffer, otherwise to chain input buffer
7305 if (idx_insert == size) {
7306 if (idx_insert != 0) {
7307 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7308 mEffects[idx_insert-1]->configure();
7309 }
7310 effect->setOutBuffer(mOutBuffer);
7311 } else {
7312 effect->setOutBuffer(mInBuffer);
7313 }
7314 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315
Steve Block3856b092011-10-20 11:56:00 +01007316 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007317 }
7318 effect->configure();
7319 return NO_ERROR;
7320}
7321
Eric Laurentcab11242010-07-15 12:50:15 -07007322// removeEffect_l() must be called with PlaybackThread::mLock held
7323size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324{
7325 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007326 int size = (int)mEffects.size();
7327 int i;
7328 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7329
7330 for (i = 0; i < size; i++) {
7331 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007332 // calling stop here will remove pre-processing effect from the audio HAL.
7333 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7334 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007335 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7336 mEffects[i]->state() == EffectModule::STOPPING) {
7337 mEffects[i]->stop();
7338 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7340 delete[] effect->inBuffer();
7341 } else {
7342 if (i == size - 1 && i != 0) {
7343 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7344 mEffects[i - 1]->configure();
7345 }
7346 }
7347 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007348 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349 break;
7350 }
7351 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352
7353 return mEffects.size();
7354}
7355
Eric Laurentcab11242010-07-15 12:50:15 -07007356// setDevice_l() must be called with PlaybackThread::mLock held
7357void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007358{
7359 size_t size = mEffects.size();
7360 for (size_t i = 0; i < size; i++) {
7361 mEffects[i]->setDevice(device);
7362 }
7363}
7364
Eric Laurentcab11242010-07-15 12:50:15 -07007365// setMode_l() must be called with PlaybackThread::mLock held
Glenn Kastenf78aee72012-01-04 11:00:47 -08007366void AudioFlinger::EffectChain::setMode_l(audio_mode_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367{
7368 size_t size = mEffects.size();
7369 for (size_t i = 0; i < size; i++) {
7370 mEffects[i]->setMode(mode);
7371 }
7372}
7373
Eric Laurentcab11242010-07-15 12:50:15 -07007374// setVolume_l() must be called with PlaybackThread::mLock held
7375bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376{
7377 uint32_t newLeft = *left;
7378 uint32_t newRight = *right;
7379 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007380 int ctrlIdx = -1;
7381 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007382
Eric Laurentcab11242010-07-15 12:50:15 -07007383 // first update volume controller
7384 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007385 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007386 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7387 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007388 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007389 break;
7390 }
7391 }
7392
7393 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007394 if (hasControl) {
7395 *left = mNewLeftVolume;
7396 *right = mNewRightVolume;
7397 }
7398 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007399 }
7400
7401 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007402 mLeftVolume = newLeft;
7403 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007404
7405 // second get volume update from volume controller
7406 if (ctrlIdx >= 0) {
7407 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007408 mNewLeftVolume = newLeft;
7409 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007410 }
7411 // then indicate volume to all other effects in chain.
7412 // Pass altered volume to effects before volume controller
7413 // and requested volume to effects after controller
7414 uint32_t lVol = newLeft;
7415 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007416
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007418 if ((int)i == ctrlIdx) continue;
7419 // this also works for ctrlIdx == -1 when there is no volume controller
7420 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 lVol = *left;
7422 rVol = *right;
7423 }
7424 mEffects[i]->setVolume(&lVol, &rVol, false);
7425 }
7426 *left = newLeft;
7427 *right = newRight;
7428
7429 return hasControl;
7430}
7431
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7433{
7434 const size_t SIZE = 256;
7435 char buffer[SIZE];
7436 String8 result;
7437
7438 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7439 result.append(buffer);
7440
7441 bool locked = tryLock(mLock);
7442 // failed to lock - AudioFlinger is probably deadlocked
7443 if (!locked) {
7444 result.append("\tCould not lock mutex:\n");
7445 }
7446
Eric Laurentcab11242010-07-15 12:50:15 -07007447 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7448 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007449 mEffects.size(),
7450 (uint32_t)mInBuffer,
7451 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 mActiveTrackCnt);
7453 result.append(buffer);
7454 write(fd, result.string(), result.size());
7455
7456 for (size_t i = 0; i < mEffects.size(); ++i) {
7457 sp<EffectModule> effect = mEffects[i];
7458 if (effect != 0) {
7459 effect->dump(fd, args);
7460 }
7461 }
7462
7463 if (locked) {
7464 mLock.unlock();
7465 }
7466
7467 return NO_ERROR;
7468}
7469
Eric Laurent59255e42011-07-27 19:49:51 -07007470// must be called with ThreadBase::mLock held
7471void AudioFlinger::EffectChain::setEffectSuspended_l(
7472 const effect_uuid_t *type, bool suspend)
7473{
7474 sp<SuspendedEffectDesc> desc;
7475 // use effect type UUID timelow as key as there is no real risk of identical
7476 // timeLow fields among effect type UUIDs.
7477 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7478 if (suspend) {
7479 if (index >= 0) {
7480 desc = mSuspendedEffects.valueAt(index);
7481 } else {
7482 desc = new SuspendedEffectDesc();
7483 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7484 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007485 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007486 }
7487 if (desc->mRefCount++ == 0) {
7488 sp<EffectModule> effect = getEffectIfEnabled(type);
7489 if (effect != 0) {
7490 desc->mEffect = effect;
7491 effect->setSuspended(true);
7492 effect->setEnabled(false);
7493 }
7494 }
7495 } else {
7496 if (index < 0) {
7497 return;
7498 }
7499 desc = mSuspendedEffects.valueAt(index);
7500 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007501 ALOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007502 desc->mRefCount = 1;
7503 }
7504 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007505 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007506 if (desc->mEffect != 0) {
7507 sp<EffectModule> effect = desc->mEffect.promote();
7508 if (effect != 0) {
7509 effect->setSuspended(false);
7510 sp<EffectHandle> handle = effect->controlHandle();
7511 if (handle != 0) {
7512 effect->setEnabled(handle->enabled());
7513 }
7514 }
7515 desc->mEffect.clear();
7516 }
7517 mSuspendedEffects.removeItemsAt(index);
7518 }
7519 }
7520}
7521
7522// must be called with ThreadBase::mLock held
7523void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7524{
7525 sp<SuspendedEffectDesc> desc;
7526
7527 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7528 if (suspend) {
7529 if (index >= 0) {
7530 desc = mSuspendedEffects.valueAt(index);
7531 } else {
7532 desc = new SuspendedEffectDesc();
7533 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007534 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007535 }
7536 if (desc->mRefCount++ == 0) {
7537 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7538 for (size_t i = 0; i < effects.size(); i++) {
7539 setEffectSuspended_l(&effects[i]->desc().type, true);
7540 }
7541 }
7542 } else {
7543 if (index < 0) {
7544 return;
7545 }
7546 desc = mSuspendedEffects.valueAt(index);
7547 if (desc->mRefCount <= 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007548 ALOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
Eric Laurent59255e42011-07-27 19:49:51 -07007549 desc->mRefCount = 1;
7550 }
7551 if (--desc->mRefCount == 0) {
7552 Vector<const effect_uuid_t *> types;
7553 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7554 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7555 continue;
7556 }
7557 types.add(&mSuspendedEffects.valueAt(i)->mType);
7558 }
7559 for (size_t i = 0; i < types.size(); i++) {
7560 setEffectSuspended_l(types[i], false);
7561 }
Steve Block3856b092011-10-20 11:56:00 +01007562 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007563 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7564 }
7565 }
7566}
7567
Eric Laurent6bffdb82011-09-23 08:40:41 -07007568
7569// The volume effect is used for automated tests only
7570#ifndef OPENSL_ES_H_
7571static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7572 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7573const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7574#endif //OPENSL_ES_H_
7575
Eric Laurentdb7c0792011-08-10 10:37:50 -07007576bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7577{
7578 // auxiliary effects and visualizer are never suspended on output mix
7579 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7580 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007581 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7582 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007583 return false;
7584 }
7585 return true;
7586}
7587
Eric Laurent59255e42011-07-27 19:49:51 -07007588Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7589{
7590 Vector< sp<EffectModule> > effects;
7591 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007592 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007593 continue;
7594 }
7595 effects.add(mEffects[i]);
7596 }
7597 return effects;
7598}
7599
7600sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7601 const effect_uuid_t *type)
7602{
7603 sp<EffectModule> effect;
7604 effect = getEffectFromType_l(type);
7605 if (effect != 0 && !effect->isEnabled()) {
7606 effect.clear();
7607 }
7608 return effect;
7609}
7610
7611void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7612 bool enabled)
7613{
7614 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7615 if (enabled) {
7616 if (index < 0) {
7617 // if the effect is not suspend check if all effects are suspended
7618 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7619 if (index < 0) {
7620 return;
7621 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007622 if (!isEffectEligibleForSuspend(effect->desc())) {
7623 return;
7624 }
Eric Laurent59255e42011-07-27 19:49:51 -07007625 setEffectSuspended_l(&effect->desc().type, enabled);
7626 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007627 if (index < 0) {
Steve Block5ff1dd52012-01-05 23:22:43 +00007628 ALOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
Eric Laurentdb7c0792011-08-10 10:37:50 -07007629 return;
7630 }
Eric Laurent59255e42011-07-27 19:49:51 -07007631 }
Steve Block3856b092011-10-20 11:56:00 +01007632 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007633 effect->desc().type.timeLow);
7634 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7635 // if effect is requested to suspended but was not yet enabled, supend it now.
7636 if (desc->mEffect == 0) {
7637 desc->mEffect = effect;
7638 effect->setEnabled(false);
7639 effect->setSuspended(true);
7640 }
7641 } else {
7642 if (index < 0) {
7643 return;
7644 }
Steve Block3856b092011-10-20 11:56:00 +01007645 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007646 effect->desc().type.timeLow);
7647 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7648 desc->mEffect.clear();
7649 effect->setSuspended(false);
7650 }
7651}
7652
Mathias Agopian65ab4712010-07-14 17:59:35 -07007653#undef LOG_TAG
7654#define LOG_TAG "AudioFlinger"
7655
7656// ----------------------------------------------------------------------------
7657
7658status_t AudioFlinger::onTransact(
7659 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7660{
7661 return BnAudioFlinger::onTransact(code, data, reply, flags);
7662}
7663
Mathias Agopian65ab4712010-07-14 17:59:35 -07007664}; // namespace android