blob: 3e0304f226fbc08cdc884913e98117ba11d5fbda [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>
38
39#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
Mathias Agopian65ab4712010-07-14 17:59:35 -070061// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Eric Laurentde070132010-07-13 04:45:46 -070063
Mathias Agopian65ab4712010-07-14 17:59:35 -070064namespace android {
65
66static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
67static const char* kHardwareLockedString = "Hardware lock is taken\n";
68
69//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
70static const float MAX_GAIN = 4096.0f;
71static const float MAX_GAIN_INT = 0x1000;
72
73// retry counts for buffer fill timeout
74// 50 * ~20msecs = 1 second
75static const int8_t kMaxTrackRetries = 50;
76static const int8_t kMaxTrackStartupRetries = 50;
77// allow less retry attempts on direct output thread.
78// direct outputs can be a scarce resource in audio hardware and should
79// be released as quickly as possible.
80static const int8_t kMaxTrackRetriesDirect = 2;
81
82static const int kDumpLockRetries = 50;
83static const int kDumpLockSleep = 20000;
84
85static const nsecs_t kWarningThrottle = seconds(5);
86
Eric Laurent7c7f10b2011-06-17 21:29:58 -070087// RecordThread loop sleep time upon application overrun or audio HAL read error
88static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent60cd0a02011-09-13 11:40:21 -070090static const nsecs_t kSetParametersTimeout = seconds(2);
91
Mathias Agopian65ab4712010-07-14 17:59:35 -070092// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070095 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
96 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
97 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
98 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099}
100
101static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
103 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
104 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
105 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106}
107
Gloria Wang9ee159b2011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
110 sp<IBinder> binder =
111 defaultServiceManager()->getService(String16("media.player"));
112 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
113 if (service.get() == NULL) {
114 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
115 return;
116 }
117
118 service->addBatteryData(params);
119}
120
Dima Zavin799a70e2011-04-18 16:57:27 -0700121static int load_audio_interface(const char *if_name, const hw_module_t **mod,
122 audio_hw_device_t **dev)
123{
124 int rc;
125
126 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
127 if (rc)
128 goto out;
129
130 rc = audio_hw_device_open(*mod, dev);
131 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
132 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
133 if (rc)
134 goto out;
135
136 return 0;
137
138out:
139 *mod = NULL;
140 *dev = NULL;
141 return rc;
142}
143
144static const char *audio_interfaces[] = {
145 "primary",
146 "a2dp",
147 "usb",
148};
149#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
150
Mathias Agopian65ab4712010-07-14 17:59:35 -0700151// ----------------------------------------------------------------------------
152
153AudioFlinger::AudioFlinger()
154 : BnAudioFlinger(),
Eric Laurent59bd0da2011-08-01 09:52:20 -0700155 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700156 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700158}
159
160void AudioFlinger::onFirstRef()
161{
Dima Zavin799a70e2011-04-18 16:57:27 -0700162 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700163
Eric Laurent93575202011-01-18 18:39:02 -0800164 Mutex::Autolock _l(mLock);
165
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167 mHardwareStatus = AUDIO_HW_IDLE;
168
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
170 const hw_module_t *mod;
171 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700172
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
174 if (rc)
175 continue;
176
177 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
178 mod->name, mod->id);
179 mAudioHwDevs.push(dev);
180
181 if (!mPrimaryHardwareDev) {
182 mPrimaryHardwareDev = dev;
183 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700184 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 }
186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187
188 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700189
Dima Zavin799a70e2011-04-18 16:57:27 -0700190 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
191 LOGE("Primary audio interface not found");
192 return;
193 }
194
195 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
196 audio_hw_device_t *dev = mAudioHwDevs[i];
197
198 mHardwareStatus = AUDIO_HW_INIT;
199 rc = dev->init_check(dev);
200 if (rc == 0) {
201 AutoMutex lock(mHardwareLock);
202
203 mMode = AUDIO_MODE_NORMAL;
204 mHardwareStatus = AUDIO_HW_SET_MODE;
205 dev->set_mode(dev, mMode);
206 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
207 dev->set_master_volume(dev, 1.0f);
208 mHardwareStatus = AUDIO_HW_IDLE;
209 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211}
212
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700213status_t AudioFlinger::initCheck() const
214{
215 Mutex::Autolock _l(mLock);
216 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
217 return NO_INIT;
218 return NO_ERROR;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221AudioFlinger::~AudioFlinger()
222{
Dima Zavin799a70e2011-04-18 16:57:27 -0700223 int num_devs = mAudioHwDevs.size();
224
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225 while (!mRecordThreads.isEmpty()) {
226 // closeInput() will remove first entry from mRecordThreads
227 closeInput(mRecordThreads.keyAt(0));
228 }
229 while (!mPlaybackThreads.isEmpty()) {
230 // closeOutput() will remove first entry from mPlaybackThreads
231 closeOutput(mPlaybackThreads.keyAt(0));
232 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700233
234 for (int i = 0; i < num_devs; i++) {
235 audio_hw_device_t *dev = mAudioHwDevs[i];
236 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700237 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700238 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239}
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
242{
243 /* first matching HW device is returned */
244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 if ((dev->get_supported_devices(dev) & devices) == devices)
247 return dev;
248 }
249 return NULL;
250}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251
252status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
253{
254 const size_t SIZE = 256;
255 char buffer[SIZE];
256 String8 result;
257
258 result.append("Clients:\n");
259 for (size_t i = 0; i < mClients.size(); ++i) {
260 wp<Client> wClient = mClients.valueAt(i);
261 if (wClient != 0) {
262 sp<Client> client = wClient.promote();
263 if (client != 0) {
264 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
265 result.append(buffer);
266 }
267 }
268 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700269
270 result.append("Global session refs:\n");
271 result.append(" session pid cnt\n");
272 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
273 AudioSessionRef *r = mAudioSessionRefs[i];
274 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
275 result.append(buffer);
276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277 write(fd, result.string(), result.size());
278 return NO_ERROR;
279}
280
281
282status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 int hardwareStatus = mHardwareStatus;
288
289 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
290 result.append(buffer);
291 write(fd, result.string(), result.size());
292 return NO_ERROR;
293}
294
295status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300 snprintf(buffer, SIZE, "Permission Denial: "
301 "can't dump AudioFlinger from pid=%d, uid=%d\n",
302 IPCThreadState::self()->getCallingPid(),
303 IPCThreadState::self()->getCallingUid());
304 result.append(buffer);
305 write(fd, result.string(), result.size());
306 return NO_ERROR;
307}
308
309static bool tryLock(Mutex& mutex)
310{
311 bool locked = false;
312 for (int i = 0; i < kDumpLockRetries; ++i) {
313 if (mutex.tryLock() == NO_ERROR) {
314 locked = true;
315 break;
316 }
317 usleep(kDumpLockSleep);
318 }
319 return locked;
320}
321
322status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
323{
324 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
325 dumpPermissionDenial(fd, args);
326 } else {
327 // get state of hardware lock
328 bool hardwareLocked = tryLock(mHardwareLock);
329 if (!hardwareLocked) {
330 String8 result(kHardwareLockedString);
331 write(fd, result.string(), result.size());
332 } else {
333 mHardwareLock.unlock();
334 }
335
336 bool locked = tryLock(mLock);
337
338 // failed to lock - AudioFlinger is probably deadlocked
339 if (!locked) {
340 String8 result(kDeadlockedString);
341 write(fd, result.string(), result.size());
342 }
343
344 dumpClients(fd, args);
345 dumpInternals(fd, args);
346
347 // dump playback threads
348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
349 mPlaybackThreads.valueAt(i)->dump(fd, args);
350 }
351
352 // dump record threads
353 for (size_t i = 0; i < mRecordThreads.size(); i++) {
354 mRecordThreads.valueAt(i)->dump(fd, args);
355 }
356
Dima Zavin799a70e2011-04-18 16:57:27 -0700357 // dump all hardware devs
358 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
359 audio_hw_device_t *dev = mAudioHwDevs[i];
360 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361 }
362 if (locked) mLock.unlock();
363 }
364 return NO_ERROR;
365}
366
367
368// IAudioFlinger interface
369
370
371sp<IAudioTrack> AudioFlinger::createTrack(
372 pid_t pid,
373 int streamType,
374 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700375 uint32_t format,
376 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377 int frameCount,
378 uint32_t flags,
379 const sp<IMemory>& sharedBuffer,
380 int output,
381 int *sessionId,
382 status_t *status)
383{
384 sp<PlaybackThread::Track> track;
385 sp<TrackHandle> trackHandle;
386 sp<Client> client;
387 wp<Client> wclient;
388 status_t lStatus;
389 int lSessionId;
390
Dima Zavinfce7a472011-04-19 22:30:36 -0700391 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392 LOGE("invalid stream type");
393 lStatus = BAD_VALUE;
394 goto Exit;
395 }
396
397 {
398 Mutex::Autolock _l(mLock);
399 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700400 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 if (thread == NULL) {
402 LOGE("unknown output thread");
403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
407 wclient = mClients.valueFor(pid);
408
409 if (wclient != NULL) {
410 client = wclient.promote();
411 } else {
412 client = new Client(this, pid);
413 mClients.add(pid, client);
414 }
415
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700417 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700419 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
420 if (mPlaybackThreads.keyAt(i) != output) {
421 // prevent same audio session on different output threads
422 uint32_t sessions = t->hasAudioSession(*sessionId);
423 if (sessions & PlaybackThread::TRACK_SESSION) {
424 lStatus = BAD_VALUE;
425 goto Exit;
426 }
427 // check if an effect with same session ID is waiting for a track to be created
428 if (sessions & PlaybackThread::EFFECT_SESSION) {
429 effectThread = t.get();
430 }
Eric Laurentde070132010-07-13 04:45:46 -0700431 }
432 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 lSessionId = *sessionId;
434 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700435 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700436 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 if (sessionId != NULL) {
438 *sessionId = lSessionId;
439 }
440 }
441 LOGV("createTrack() lSessionId: %d", lSessionId);
442
443 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700444 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700445
446 // move effect chain to this output thread if an effect on same session was waiting
447 // for a track to be created
448 if (lStatus == NO_ERROR && effectThread != NULL) {
449 Mutex::Autolock _dl(thread->mLock);
450 Mutex::Autolock _sl(effectThread->mLock);
451 moveEffectChain_l(lSessionId, effectThread, thread, true);
452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 }
454 if (lStatus == NO_ERROR) {
455 trackHandle = new TrackHandle(track);
456 } else {
457 // remove local strong reference to Client before deleting the Track so that the Client
458 // destructor is called by the TrackBase destructor with mLock held
459 client.clear();
460 track.clear();
461 }
462
463Exit:
464 if(status) {
465 *status = lStatus;
466 }
467 return trackHandle;
468}
469
470uint32_t AudioFlinger::sampleRate(int output) const
471{
472 Mutex::Autolock _l(mLock);
473 PlaybackThread *thread = checkPlaybackThread_l(output);
474 if (thread == NULL) {
475 LOGW("sampleRate() unknown thread %d", output);
476 return 0;
477 }
478 return thread->sampleRate();
479}
480
481int AudioFlinger::channelCount(int output) const
482{
483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
486 LOGW("channelCount() unknown thread %d", output);
487 return 0;
488 }
489 return thread->channelCount();
490}
491
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700492uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493{
494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
497 LOGW("format() unknown thread %d", output);
498 return 0;
499 }
500 return thread->format();
501}
502
503size_t AudioFlinger::frameCount(int output) const
504{
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
508 LOGW("frameCount() unknown thread %d", output);
509 return 0;
510 }
511 return thread->frameCount();
512}
513
514uint32_t AudioFlinger::latency(int output) const
515{
516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
519 LOGW("latency() unknown thread %d", output);
520 return 0;
521 }
522 return thread->latency();
523}
524
525status_t AudioFlinger::setMasterVolume(float value)
526{
Eric Laurenta1884f92011-08-23 08:25:03 -0700527 status_t ret = initCheck();
528 if (ret != NO_ERROR) {
529 return ret;
530 }
531
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 // check calling permissions
533 if (!settingsAllowed()) {
534 return PERMISSION_DENIED;
535 }
536
537 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800538 { // scope for the lock
539 AutoMutex lock(mHardwareLock);
540 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700541 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800542 value = 1.0f;
543 }
544 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546
Eric Laurent93575202011-01-18 18:39:02 -0800547 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 mMasterVolume = value;
549 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
550 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
551
552 return NO_ERROR;
553}
554
555status_t AudioFlinger::setMode(int mode)
556{
Eric Laurenta1884f92011-08-23 08:25:03 -0700557 status_t ret = initCheck();
558 if (ret != NO_ERROR) {
559 return ret;
560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561
562 // check calling permissions
563 if (!settingsAllowed()) {
564 return PERMISSION_DENIED;
565 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700566 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 LOGW("Illegal value: setMode(%d)", mode);
568 return BAD_VALUE;
569 }
570
571 { // scope for the lock
572 AutoMutex lock(mHardwareLock);
573 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700574 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 mHardwareStatus = AUDIO_HW_IDLE;
576 }
577
578 if (NO_ERROR == ret) {
579 Mutex::Autolock _l(mLock);
580 mMode = mode;
581 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
582 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 }
584
585 return ret;
586}
587
588status_t AudioFlinger::setMicMute(bool state)
589{
Eric Laurenta1884f92011-08-23 08:25:03 -0700590 status_t ret = initCheck();
591 if (ret != NO_ERROR) {
592 return ret;
593 }
594
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 // check calling permissions
596 if (!settingsAllowed()) {
597 return PERMISSION_DENIED;
598 }
599
600 AutoMutex lock(mHardwareLock);
601 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700602 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 mHardwareStatus = AUDIO_HW_IDLE;
604 return ret;
605}
606
607bool AudioFlinger::getMicMute() const
608{
Eric Laurenta1884f92011-08-23 08:25:03 -0700609 status_t ret = initCheck();
610 if (ret != NO_ERROR) {
611 return false;
612 }
613
Dima Zavinfce7a472011-04-19 22:30:36 -0700614 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700616 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 mHardwareStatus = AUDIO_HW_IDLE;
618 return state;
619}
620
621status_t AudioFlinger::setMasterMute(bool muted)
622{
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
627
Eric Laurent93575202011-01-18 18:39:02 -0800628 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 mMasterMute = muted;
630 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
631 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
632
633 return NO_ERROR;
634}
635
636float AudioFlinger::masterVolume() const
637{
638 return mMasterVolume;
639}
640
641bool AudioFlinger::masterMute() const
642{
643 return mMasterMute;
644}
645
646status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
647{
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
652
Dima Zavinfce7a472011-04-19 22:30:36 -0700653 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 return BAD_VALUE;
655 }
656
657 AutoMutex lock(mLock);
658 PlaybackThread *thread = NULL;
659 if (output) {
660 thread = checkPlaybackThread_l(output);
661 if (thread == NULL) {
662 return BAD_VALUE;
663 }
664 }
665
666 mStreamTypes[stream].volume = value;
667
668 if (thread == NULL) {
669 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
670 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
671 }
672 } else {
673 thread->setStreamVolume(stream, value);
674 }
675
676 return NO_ERROR;
677}
678
679status_t AudioFlinger::setStreamMute(int stream, bool muted)
680{
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
Dima Zavinfce7a472011-04-19 22:30:36 -0700686 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
687 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 return BAD_VALUE;
689 }
690
Eric Laurent93575202011-01-18 18:39:02 -0800691 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 mStreamTypes[stream].mute = muted;
693 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
694 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
695
696 return NO_ERROR;
697}
698
699float AudioFlinger::streamVolume(int stream, int output) const
700{
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return 0.0f;
703 }
704
705 AutoMutex lock(mLock);
706 float volume;
707 if (output) {
708 PlaybackThread *thread = checkPlaybackThread_l(output);
709 if (thread == NULL) {
710 return 0.0f;
711 }
712 volume = thread->streamVolume(stream);
713 } else {
714 volume = mStreamTypes[stream].volume;
715 }
716
717 return volume;
718}
719
720bool AudioFlinger::streamMute(int stream) const
721{
Dima Zavinfce7a472011-04-19 22:30:36 -0700722 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 return true;
724 }
725
726 return mStreamTypes[stream].mute;
727}
728
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
730{
731 status_t result;
732
733 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
734 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
735 // check calling permissions
736 if (!settingsAllowed()) {
737 return PERMISSION_DENIED;
738 }
739
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 // ioHandle == 0 means the parameters are global to the audio hardware interface
741 if (ioHandle == 0) {
742 AutoMutex lock(mHardwareLock);
743 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700744 status_t final_result = NO_ERROR;
745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 audio_hw_device_t *dev = mAudioHwDevs[i];
747 result = dev->set_parameters(dev, keyValuePairs.string());
748 final_result = result ?: final_result;
749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700751 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
752 AudioParameter param = AudioParameter(keyValuePairs);
753 String8 value;
754 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
755 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700756 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
757 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700758 for (size_t i = 0; i < mRecordThreads.size(); i++) {
759 sp<RecordThread> thread = mRecordThreads.valueAt(i);
760 RecordThread::RecordTrack *track = thread->track();
761 if (track != NULL) {
762 audio_devices_t device = (audio_devices_t)(
763 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700764 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 thread->setEffectSuspended(FX_IID_AEC,
766 suspend,
767 track->sessionId());
768 thread->setEffectSuspended(FX_IID_NS,
769 suspend,
770 track->sessionId());
771 }
772 }
Eric Laurentbee53372011-08-29 12:42:48 -0700773 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700774 }
775 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700776 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777 }
778
779 // hold a strong ref on thread in case closeOutput() or closeInput() is called
780 // and the thread is exited once the lock is released
781 sp<ThreadBase> thread;
782 {
783 Mutex::Autolock _l(mLock);
784 thread = checkPlaybackThread_l(ioHandle);
785 if (thread == NULL) {
786 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700787 } else if (thread.get() == primaryPlaybackThread_l()) {
788 // indicate output device change to all input threads for pre processing
789 AudioParameter param = AudioParameter(keyValuePairs);
790 int value;
791 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
792 for (size_t i = 0; i < mRecordThreads.size(); i++) {
793 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
794 }
795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
797 }
798 if (thread != NULL) {
799 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 return result;
801 }
802 return BAD_VALUE;
803}
804
805String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
806{
807// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
808// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
809
810 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700811 String8 out_s8;
812
Dima Zavin799a70e2011-04-18 16:57:27 -0700813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
814 audio_hw_device_t *dev = mAudioHwDevs[i];
815 char *s = dev->get_parameters(dev, keys.string());
816 out_s8 += String8(s);
817 free(s);
818 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700819 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 }
821
822 Mutex::Autolock _l(mLock);
823
824 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
825 if (playbackThread != NULL) {
826 return playbackThread->getParameters(keys);
827 }
828 RecordThread *recordThread = checkRecordThread_l(ioHandle);
829 if (recordThread != NULL) {
830 return recordThread->getParameters(keys);
831 }
832 return String8("");
833}
834
835size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
836{
Eric Laurenta1884f92011-08-23 08:25:03 -0700837 status_t ret = initCheck();
838 if (ret != NO_ERROR) {
839 return 0;
840 }
841
Dima Zavin799a70e2011-04-18 16:57:27 -0700842 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843}
844
845unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
846{
847 if (ioHandle == 0) {
848 return 0;
849 }
850
851 Mutex::Autolock _l(mLock);
852
853 RecordThread *recordThread = checkRecordThread_l(ioHandle);
854 if (recordThread != NULL) {
855 return recordThread->getInputFramesLost();
856 }
857 return 0;
858}
859
860status_t AudioFlinger::setVoiceVolume(float value)
861{
Eric Laurenta1884f92011-08-23 08:25:03 -0700862 status_t ret = initCheck();
863 if (ret != NO_ERROR) {
864 return ret;
865 }
866
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
872 AutoMutex lock(mHardwareLock);
873 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700874 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 mHardwareStatus = AUDIO_HW_IDLE;
876
877 return ret;
878}
879
880status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
881{
882 status_t status;
883
884 Mutex::Autolock _l(mLock);
885
886 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
887 if (playbackThread != NULL) {
888 return playbackThread->getRenderPosition(halFrames, dspFrames);
889 }
890
891 return BAD_VALUE;
892}
893
894void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
895{
896
897 Mutex::Autolock _l(mLock);
898
899 int pid = IPCThreadState::self()->getCallingPid();
900 if (mNotificationClients.indexOfKey(pid) < 0) {
901 sp<NotificationClient> notificationClient = new NotificationClient(this,
902 client,
903 pid);
904 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
905
906 mNotificationClients.add(pid, notificationClient);
907
908 sp<IBinder> binder = client->asBinder();
909 binder->linkToDeath(notificationClient);
910
911 // the config change is always sent from playback or record threads to avoid deadlock
912 // with AudioSystem::gLock
913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
914 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
915 }
916
917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
918 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
919 }
920 }
921}
922
923void AudioFlinger::removeNotificationClient(pid_t pid)
924{
925 Mutex::Autolock _l(mLock);
926
927 int index = mNotificationClients.indexOfKey(pid);
928 if (index >= 0) {
929 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
930 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 mNotificationClients.removeItem(pid);
932 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700933
934 LOGV("%d died, releasing its sessions", pid);
935 int num = mAudioSessionRefs.size();
936 bool removed = false;
937 for (int i = 0; i< num; i++) {
938 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
939 LOGV(" pid %d @ %d", ref->pid, i);
940 if (ref->pid == pid) {
941 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
942 mAudioSessionRefs.removeAt(i);
943 delete ref;
944 removed = true;
945 i--;
946 num--;
947 }
948 }
949 if (removed) {
950 purgeStaleEffects_l();
951 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952}
953
954// audioConfigChanged_l() must be called with AudioFlinger::mLock held
955void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
956{
957 size_t size = mNotificationClients.size();
958 for (size_t i = 0; i < size; i++) {
959 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
960 }
961}
962
963// removeClient_l() must be called with AudioFlinger::mLock held
964void AudioFlinger::removeClient_l(pid_t pid)
965{
966 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
967 mClients.removeItem(pid);
968}
969
970
971// ----------------------------------------------------------------------------
972
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700973AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 : Thread(false),
975 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700976 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
977 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700979 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980}
981
982AudioFlinger::ThreadBase::~ThreadBase()
983{
984 mParamCond.broadcast();
985 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700986 // do not lock the mutex in destructor
987 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700988 if (mPowerManager != 0) {
989 sp<IBinder> binder = mPowerManager->asBinder();
990 binder->unlinkToDeath(mDeathRecipient);
991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992}
993
994void AudioFlinger::ThreadBase::exit()
995{
996 // keep a strong ref on ourself so that we wont get
997 // destroyed in the middle of requestExitAndWait()
998 sp <ThreadBase> strongMe = this;
999
1000 LOGV("ThreadBase::exit");
1001 {
1002 AutoMutex lock(&mLock);
1003 mExiting = true;
1004 requestExit();
1005 mWaitWorkCV.signal();
1006 }
1007 requestExitAndWait();
1008}
1009
1010uint32_t AudioFlinger::ThreadBase::sampleRate() const
1011{
1012 return mSampleRate;
1013}
1014
1015int AudioFlinger::ThreadBase::channelCount() const
1016{
1017 return (int)mChannelCount;
1018}
1019
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001020uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021{
1022 return mFormat;
1023}
1024
1025size_t AudioFlinger::ThreadBase::frameCount() const
1026{
1027 return mFrameCount;
1028}
1029
1030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
1032 status_t status;
1033
1034 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1035 Mutex::Autolock _l(mLock);
1036
1037 mNewParameters.add(keyValuePairs);
1038 mWaitWorkCV.signal();
1039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
1047 return status;
1048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
1053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
1059 ConfigEvent *configEvent = new ConfigEvent();
1060 configEvent->mEvent = event;
1061 configEvent->mParam = param;
1062 mConfigEvents.add(configEvent);
1063 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
1071 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1072 ConfigEvent *configEvent = mConfigEvents[0];
1073 mConfigEvents.removeAt(0);
1074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
1076 mLock.unlock();
1077 mAudioFlinger->mLock.lock();
1078 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1079 mAudioFlinger->mLock.unlock();
1080 delete configEvent;
1081 mLock.lock();
1082 }
1083 mLock.unlock();
1084}
1085
1086status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1087{
1088 const size_t SIZE = 256;
1089 char buffer[SIZE];
1090 String8 result;
1091
1092 bool locked = tryLock(mLock);
1093 if (!locked) {
1094 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1095 write(fd, buffer, strlen(buffer));
1096 }
1097
1098 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1105 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001106 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1107 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1111 result.append(buffer);
1112
1113 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1114 result.append(buffer);
1115 result.append(" Index Command");
1116 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1117 snprintf(buffer, SIZE, "\n %02d ", i);
1118 result.append(buffer);
1119 result.append(mNewParameters[i]);
1120 }
1121
1122 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, " Index event param\n");
1125 result.append(buffer);
1126 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1127 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1128 result.append(buffer);
1129 }
1130 result.append("\n");
1131
1132 write(fd, result.string(), result.size());
1133
1134 if (locked) {
1135 mLock.unlock();
1136 }
1137 return NO_ERROR;
1138}
1139
Eric Laurent1d2bff02011-07-24 17:49:51 -07001140status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1141{
1142 const size_t SIZE = 256;
1143 char buffer[SIZE];
1144 String8 result;
1145
1146 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1147 write(fd, buffer, strlen(buffer));
1148
1149 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1150 sp<EffectChain> chain = mEffectChains[i];
1151 if (chain != 0) {
1152 chain->dump(fd, args);
1153 }
1154 }
1155 return NO_ERROR;
1156}
1157
Eric Laurentfeb0db62011-07-22 09:04:31 -07001158void AudioFlinger::ThreadBase::acquireWakeLock()
1159{
1160 Mutex::Autolock _l(mLock);
1161 acquireWakeLock_l();
1162}
1163
1164void AudioFlinger::ThreadBase::acquireWakeLock_l()
1165{
1166 if (mPowerManager == 0) {
1167 // use checkService() to avoid blocking if power service is not up yet
1168 sp<IBinder> binder =
1169 defaultServiceManager()->checkService(String16("power"));
1170 if (binder == 0) {
1171 LOGW("Thread %s cannot connect to the power manager service", mName);
1172 } else {
1173 mPowerManager = interface_cast<IPowerManager>(binder);
1174 binder->linkToDeath(mDeathRecipient);
1175 }
1176 }
1177 if (mPowerManager != 0) {
1178 sp<IBinder> binder = new BBinder();
1179 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1180 binder,
1181 String16(mName));
1182 if (status == NO_ERROR) {
1183 mWakeLockToken = binder;
1184 }
1185 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1186 }
1187}
1188
1189void AudioFlinger::ThreadBase::releaseWakeLock()
1190{
1191 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001192 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001193}
1194
1195void AudioFlinger::ThreadBase::releaseWakeLock_l()
1196{
1197 if (mWakeLockToken != 0) {
1198 LOGV("releaseWakeLock_l() %s", mName);
1199 if (mPowerManager != 0) {
1200 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1201 }
1202 mWakeLockToken.clear();
1203 }
1204}
1205
1206void AudioFlinger::ThreadBase::clearPowerManager()
1207{
1208 Mutex::Autolock _l(mLock);
1209 releaseWakeLock_l();
1210 mPowerManager.clear();
1211}
1212
1213void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1214{
1215 sp<ThreadBase> thread = mThread.promote();
1216 if (thread != 0) {
1217 thread->clearPowerManager();
1218 }
1219 LOGW("power manager service died !!!");
1220}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001221
Eric Laurent59255e42011-07-27 19:49:51 -07001222void AudioFlinger::ThreadBase::setEffectSuspended(
1223 const effect_uuid_t *type, bool suspend, int sessionId)
1224{
1225 Mutex::Autolock _l(mLock);
1226 setEffectSuspended_l(type, suspend, sessionId);
1227}
1228
1229void AudioFlinger::ThreadBase::setEffectSuspended_l(
1230 const effect_uuid_t *type, bool suspend, int sessionId)
1231{
1232 sp<EffectChain> chain;
1233 chain = getEffectChain_l(sessionId);
1234 if (chain != 0) {
1235 if (type != NULL) {
1236 chain->setEffectSuspended_l(type, suspend);
1237 } else {
1238 chain->setEffectSuspendedAll_l(suspend);
1239 }
1240 }
1241
1242 updateSuspendedSessions_l(type, suspend, sessionId);
1243}
1244
1245void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1246{
1247 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1248 if (index < 0) {
1249 return;
1250 }
1251
1252 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1253 mSuspendedSessions.editValueAt(index);
1254
1255 for (size_t i = 0; i < sessionEffects.size(); i++) {
1256 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1257 for (int j = 0; j < desc->mRefCount; j++) {
1258 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1259 chain->setEffectSuspendedAll_l(true);
1260 } else {
1261 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1262 desc->mType.timeLow);
1263 chain->setEffectSuspended_l(&desc->mType, true);
1264 }
1265 }
1266 }
1267}
1268
Eric Laurent59255e42011-07-27 19:49:51 -07001269void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1270 bool suspend,
1271 int sessionId)
1272{
1273 int index = mSuspendedSessions.indexOfKey(sessionId);
1274
1275 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1276
1277 if (suspend) {
1278 if (index >= 0) {
1279 sessionEffects = mSuspendedSessions.editValueAt(index);
1280 } else {
1281 mSuspendedSessions.add(sessionId, sessionEffects);
1282 }
1283 } else {
1284 if (index < 0) {
1285 return;
1286 }
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 }
1289
1290
1291 int key = EffectChain::kKeyForSuspendAll;
1292 if (type != NULL) {
1293 key = type->timeLow;
1294 }
1295 index = sessionEffects.indexOfKey(key);
1296
1297 sp <SuspendedSessionDesc> desc;
1298 if (suspend) {
1299 if (index >= 0) {
1300 desc = sessionEffects.valueAt(index);
1301 } else {
1302 desc = new SuspendedSessionDesc();
1303 if (type != NULL) {
1304 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1305 }
1306 sessionEffects.add(key, desc);
1307 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1308 }
1309 desc->mRefCount++;
1310 } else {
1311 if (index < 0) {
1312 return;
1313 }
1314 desc = sessionEffects.valueAt(index);
1315 if (--desc->mRefCount == 0) {
1316 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1317 sessionEffects.removeItemsAt(index);
1318 if (sessionEffects.isEmpty()) {
1319 LOGV("updateSuspendedSessions_l() restore removing session %d",
1320 sessionId);
1321 mSuspendedSessions.removeItem(sessionId);
1322 }
1323 }
1324 }
1325 if (!sessionEffects.isEmpty()) {
1326 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1327 }
1328}
1329
1330void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1331 bool enabled,
1332 int sessionId)
1333{
1334 Mutex::Autolock _l(mLock);
1335
Eric Laurentdb7c0792011-08-10 10:37:50 -07001336 if (mType != RECORD) {
1337 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1338 // another session. This gives the priority to well behaved effect control panels
1339 // and applications not using global effects.
1340 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1341 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1342 }
1343 }
Eric Laurent59255e42011-07-27 19:49:51 -07001344
1345 sp<EffectChain> chain = getEffectChain_l(sessionId);
1346 if (chain != 0) {
1347 chain->checkSuspendOnEffectEnabled(effect, enabled);
1348 }
1349}
1350
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351// ----------------------------------------------------------------------------
1352
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001353AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1354 AudioStreamOut* output,
1355 int id,
1356 uint32_t device)
1357 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001359 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001361 snprintf(mName, kNameLength, "AudioOut_%d", id);
1362
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363 readOutputParameters();
1364
1365 mMasterVolume = mAudioFlinger->masterVolume();
1366 mMasterMute = mAudioFlinger->masterMute();
1367
Dima Zavinfce7a472011-04-19 22:30:36 -07001368 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1370 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001371 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372 }
1373}
1374
1375AudioFlinger::PlaybackThread::~PlaybackThread()
1376{
1377 delete [] mMixBuffer;
1378}
1379
1380status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1381{
1382 dumpInternals(fd, args);
1383 dumpTracks(fd, args);
1384 dumpEffectChains(fd, args);
1385 return NO_ERROR;
1386}
1387
1388status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1389{
1390 const size_t SIZE = 256;
1391 char buffer[SIZE];
1392 String8 result;
1393
1394 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1395 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001396 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 -07001397 for (size_t i = 0; i < mTracks.size(); ++i) {
1398 sp<Track> track = mTracks[i];
1399 if (track != 0) {
1400 track->dump(buffer, SIZE);
1401 result.append(buffer);
1402 }
1403 }
1404
1405 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1406 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001407 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 -07001408 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1409 wp<Track> wTrack = mActiveTracks[i];
1410 if (wTrack != 0) {
1411 sp<Track> track = wTrack.promote();
1412 if (track != 0) {
1413 track->dump(buffer, SIZE);
1414 result.append(buffer);
1415 }
1416 }
1417 }
1418 write(fd, result.string(), result.size());
1419 return NO_ERROR;
1420}
1421
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1423{
1424 const size_t SIZE = 256;
1425 char buffer[SIZE];
1426 String8 result;
1427
1428 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1429 result.append(buffer);
1430 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1431 result.append(buffer);
1432 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1433 result.append(buffer);
1434 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1435 result.append(buffer);
1436 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1437 result.append(buffer);
1438 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1439 result.append(buffer);
1440 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1441 result.append(buffer);
1442 write(fd, result.string(), result.size());
1443
1444 dumpBase(fd, args);
1445
1446 return NO_ERROR;
1447}
1448
1449// Thread virtuals
1450status_t AudioFlinger::PlaybackThread::readyToRun()
1451{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001452 status_t status = initCheck();
1453 if (status == NO_ERROR) {
1454 LOGI("AudioFlinger's thread %p ready to run", this);
1455 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001458 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459}
1460
1461void AudioFlinger::PlaybackThread::onFirstRef()
1462{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001463 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464}
1465
1466// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1467sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1468 const sp<AudioFlinger::Client>& client,
1469 int streamType,
1470 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001471 uint32_t format,
1472 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 int frameCount,
1474 const sp<IMemory>& sharedBuffer,
1475 int sessionId,
1476 status_t *status)
1477{
1478 sp<Track> track;
1479 status_t lStatus;
1480
1481 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001482 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1483 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1484 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1485 "for output %p with format %d",
1486 sampleRate, format, channelMask, mOutput, mFormat);
1487 lStatus = BAD_VALUE;
1488 goto Exit;
1489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490 }
1491 } else {
1492 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1493 if (sampleRate > mSampleRate*2) {
1494 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1495 lStatus = BAD_VALUE;
1496 goto Exit;
1497 }
1498 }
1499
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001500 lStatus = initCheck();
1501 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 goto Exit;
1504 }
1505
1506 { // scope for mLock
1507 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001508
1509 // all tracks in same audio session must share the same routing strategy otherwise
1510 // conflicts will happen when tracks are moved from one output to another by audio policy
1511 // manager
1512 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001513 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001514 for (size_t i = 0; i < mTracks.size(); ++i) {
1515 sp<Track> t = mTracks[i];
1516 if (t != 0) {
1517 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001518 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
1522 }
1523 }
1524
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001526 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 if (track->getCblk() == NULL || track->name() < 0) {
1528 lStatus = NO_MEMORY;
1529 goto Exit;
1530 }
1531 mTracks.add(track);
1532
1533 sp<EffectChain> chain = getEffectChain_l(sessionId);
1534 if (chain != 0) {
1535 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1536 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001537 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001538 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001540
1541 // invalidate track immediately if the stream type was moved to another thread since
1542 // createTrack() was called by the client process.
1543 if (!mStreamTypes[streamType].valid) {
1544 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1545 this, streamType);
1546 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548 }
1549 lStatus = NO_ERROR;
1550
1551Exit:
1552 if(status) {
1553 *status = lStatus;
1554 }
1555 return track;
1556}
1557
1558uint32_t AudioFlinger::PlaybackThread::latency() const
1559{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001560 Mutex::Autolock _l(mLock);
1561 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001562 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001563 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 return 0;
1565 }
1566}
1567
1568status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1569{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 mMasterVolume = value;
1571 return NO_ERROR;
1572}
1573
1574status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1575{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 mMasterMute = muted;
1577 return NO_ERROR;
1578}
1579
1580float AudioFlinger::PlaybackThread::masterVolume() const
1581{
1582 return mMasterVolume;
1583}
1584
1585bool AudioFlinger::PlaybackThread::masterMute() const
1586{
1587 return mMasterMute;
1588}
1589
1590status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1591{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 mStreamTypes[stream].volume = value;
1593 return NO_ERROR;
1594}
1595
1596status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1597{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 mStreamTypes[stream].mute = muted;
1599 return NO_ERROR;
1600}
1601
1602float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1603{
1604 return mStreamTypes[stream].volume;
1605}
1606
1607bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1608{
1609 return mStreamTypes[stream].mute;
1610}
1611
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612// addTrack_l() must be called with ThreadBase::mLock held
1613status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1614{
1615 status_t status = ALREADY_EXISTS;
1616
1617 // set retry count for buffer fill
1618 track->mRetryCount = kMaxTrackStartupRetries;
1619 if (mActiveTracks.indexOf(track) < 0) {
1620 // the track is newly added, make sure it fills up all its
1621 // buffers before playing. This is to ensure the client will
1622 // effectively get the latency it requested.
1623 track->mFillingUpStatus = Track::FS_FILLING;
1624 track->mResetDone = false;
1625 mActiveTracks.add(track);
1626 if (track->mainBuffer() != mMixBuffer) {
1627 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1628 if (chain != 0) {
1629 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001630 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631 }
1632 }
1633
1634 status = NO_ERROR;
1635 }
1636
1637 LOGV("mWaitWorkCV.broadcast");
1638 mWaitWorkCV.broadcast();
1639
1640 return status;
1641}
1642
1643// destroyTrack_l() must be called with ThreadBase::mLock held
1644void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1645{
1646 track->mState = TrackBase::TERMINATED;
1647 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001648 removeTrack_l(track);
1649 }
1650}
1651
1652void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1653{
1654 mTracks.remove(track);
1655 deleteTrackName_l(track->name());
1656 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1657 if (chain != 0) {
1658 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 }
1660}
1661
1662String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1663{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001664 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001665 char *s;
1666
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001667 Mutex::Autolock _l(mLock);
1668 if (initCheck() != NO_ERROR) {
1669 return out_s8;
1670 }
1671
Dima Zavin799a70e2011-04-18 16:57:27 -07001672 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001673 out_s8 = String8(s);
1674 free(s);
1675 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676}
1677
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001678// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1680 AudioSystem::OutputDescriptor desc;
1681 void *param2 = 0;
1682
1683 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1684
1685 switch (event) {
1686 case AudioSystem::OUTPUT_OPENED:
1687 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001688 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 desc.samplingRate = mSampleRate;
1690 desc.format = mFormat;
1691 desc.frameCount = mFrameCount;
1692 desc.latency = latency();
1693 param2 = &desc;
1694 break;
1695
1696 case AudioSystem::STREAM_CONFIG_CHANGED:
1697 param2 = &param;
1698 case AudioSystem::OUTPUT_CLOSED:
1699 default:
1700 break;
1701 }
1702 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1703}
1704
1705void AudioFlinger::PlaybackThread::readOutputParameters()
1706{
Dima Zavin799a70e2011-04-18 16:57:27 -07001707 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001708 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1709 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001710 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1711 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1712 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713
1714 // FIXME - Current mixer implementation only supports stereo output: Always
1715 // Allocate a stereo buffer even if HW output is mono.
1716 if (mMixBuffer != NULL) delete[] mMixBuffer;
1717 mMixBuffer = new int16_t[mFrameCount * 2];
1718 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1719
Eric Laurentde070132010-07-13 04:45:46 -07001720 // force reconfiguration of effect chains and engines to take new buffer size and audio
1721 // parameters into account
1722 // Note that mLock is not held when readOutputParameters() is called from the constructor
1723 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1724 // matter.
1725 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1726 Vector< sp<EffectChain> > effectChains = mEffectChains;
1727 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001728 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730}
1731
1732status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1733{
1734 if (halFrames == 0 || dspFrames == 0) {
1735 return BAD_VALUE;
1736 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001737 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001738 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739 return INVALID_OPERATION;
1740 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001741 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
Dima Zavin799a70e2011-04-18 16:57:27 -07001743 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744}
1745
Eric Laurent39e94f82010-07-28 01:32:47 -07001746uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747{
1748 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001749 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001751 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 }
1753
1754 for (size_t i = 0; i < mTracks.size(); ++i) {
1755 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001756 if (sessionId == track->sessionId() &&
1757 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001758 result |= TRACK_SESSION;
1759 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001760 }
1761 }
1762
Eric Laurent39e94f82010-07-28 01:32:47 -07001763 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
Eric Laurentde070132010-07-13 04:45:46 -07001766uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1767{
Dima Zavinfce7a472011-04-19 22:30:36 -07001768 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001769 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001770 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1771 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001772 }
1773 for (size_t i = 0; i < mTracks.size(); i++) {
1774 sp<Track> track = mTracks[i];
1775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001777 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001778 }
1779 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001781}
1782
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001784AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1785{
1786 Mutex::Autolock _l(mLock);
1787 return mOutput;
1788}
1789
1790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1791{
1792 Mutex::Autolock _l(mLock);
1793 AudioStreamOut *output = mOutput;
1794 mOutput = NULL;
1795 return output;
1796}
1797
1798// this method must always be called either with ThreadBase mLock held or inside the thread loop
1799audio_stream_t* AudioFlinger::PlaybackThread::stream()
1800{
1801 if (mOutput == NULL) {
1802 return NULL;
1803 }
1804 return &mOutput->stream->common;
1805}
1806
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807// ----------------------------------------------------------------------------
1808
Dima Zavin799a70e2011-04-18 16:57:27 -07001809AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 : PlaybackThread(audioFlinger, output, id, device),
1811 mAudioMixer(0)
1812{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001813 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1815
1816 // FIXME - Current mixer implementation only supports stereo output
1817 if (mChannelCount == 1) {
1818 LOGE("Invalid audio hardware channel count");
1819 }
1820}
1821
1822AudioFlinger::MixerThread::~MixerThread()
1823{
1824 delete mAudioMixer;
1825}
1826
1827bool AudioFlinger::MixerThread::threadLoop()
1828{
1829 Vector< sp<Track> > tracksToRemove;
1830 uint32_t mixerStatus = MIXER_IDLE;
1831 nsecs_t standbyTime = systemTime();
1832 size_t mixBufferSize = mFrameCount * mFrameSize;
1833 // FIXME: Relaxed timing because of a certain device that can't meet latency
1834 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001835 // increase threshold again due to low power audio mode. The way this warning threshold is
1836 // calculated and its usefulness should be reconsidered anyway.
1837 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 nsecs_t lastWarning = 0;
1839 bool longStandbyExit = false;
1840 uint32_t activeSleepTime = activeSleepTimeUs();
1841 uint32_t idleSleepTime = idleSleepTimeUs();
1842 uint32_t sleepTime = idleSleepTime;
1843 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001844#ifdef DEBUG_CPU_USAGE
1845 ThreadCpuUsage cpu;
1846 const CentralTendencyStatistics& stats = cpu.statistics();
1847#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001848
Eric Laurentfeb0db62011-07-22 09:04:31 -07001849 acquireWakeLock();
1850
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 while (!exitPending())
1852 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001853#ifdef DEBUG_CPU_USAGE
1854 cpu.sampleAndEnable();
1855 unsigned n = stats.n();
1856 // cpu.elapsed() is expensive, so don't call it every loop
1857 if ((n & 127) == 1) {
1858 long long elapsed = cpu.elapsed();
1859 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1860 double perLoop = elapsed / (double) n;
1861 double perLoop100 = perLoop * 0.01;
1862 double mean = stats.mean();
1863 double stddev = stats.stddev();
1864 double minimum = stats.minimum();
1865 double maximum = stats.maximum();
1866 cpu.resetStatistics();
1867 LOGI("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",
1868 elapsed * .000000001, n, perLoop * .000001,
1869 mean * .001,
1870 stddev * .001,
1871 minimum * .001,
1872 maximum * .001,
1873 mean / perLoop100,
1874 stddev / perLoop100,
1875 minimum / perLoop100,
1876 maximum / perLoop100);
1877 }
1878 }
1879#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880 processConfigEvents();
1881
1882 mixerStatus = MIXER_IDLE;
1883 { // scope for mLock
1884
1885 Mutex::Autolock _l(mLock);
1886
1887 if (checkForNewParameters_l()) {
1888 mixBufferSize = mFrameCount * mFrameSize;
1889 // FIXME: Relaxed timing because of a certain device that can't meet latency
1890 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001891 // increase threshold again due to low power audio mode. The way this warning
1892 // threshold is calculated and its usefulness should be reconsidered anyway.
1893 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001894 activeSleepTime = activeSleepTimeUs();
1895 idleSleepTime = idleSleepTimeUs();
1896 }
1897
1898 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1899
1900 // put audio hardware into standby after short delay
1901 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1902 mSuspended) {
1903 if (!mStandby) {
1904 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001905 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001906 mStandby = true;
1907 mBytesWritten = 0;
1908 }
1909
1910 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1911 // we're about to wait, flush the binder command buffer
1912 IPCThreadState::self()->flushCommands();
1913
1914 if (exitPending()) break;
1915
Eric Laurentfeb0db62011-07-22 09:04:31 -07001916 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 // wait until we have something to do...
1918 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1919 mWaitWorkCV.wait(mLock);
1920 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001921 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922
1923 if (mMasterMute == false) {
1924 char value[PROPERTY_VALUE_MAX];
1925 property_get("ro.audio.silent", value, "0");
1926 if (atoi(value)) {
1927 LOGD("Silence is golden");
1928 setMasterMute(true);
1929 }
1930 }
1931
1932 standbyTime = systemTime() + kStandbyTimeInNsecs;
1933 sleepTime = idleSleepTime;
1934 continue;
1935 }
1936 }
1937
1938 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1939
1940 // prevent any changes in effect chain list and in each effect chain
1941 // during mixing and effect process as the audio buffers could be deleted
1942 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001943 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 }
1945
1946 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1947 // mix buffers...
1948 mAudioMixer->process();
1949 sleepTime = 0;
1950 standbyTime = systemTime() + kStandbyTimeInNsecs;
1951 //TODO: delay standby when effects have a tail
1952 } else {
1953 // If no tracks are ready, sleep once for the duration of an output
1954 // buffer size, then write 0s to the output
1955 if (sleepTime == 0) {
1956 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1957 sleepTime = activeSleepTime;
1958 } else {
1959 sleepTime = idleSleepTime;
1960 }
1961 } else if (mBytesWritten != 0 ||
1962 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1963 memset (mMixBuffer, 0, mixBufferSize);
1964 sleepTime = 0;
1965 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1966 }
1967 // TODO add standby time extension fct of effect tail
1968 }
1969
1970 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001971 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973 // sleepTime == 0 means we must write to audio hardware
1974 if (sleepTime == 0) {
1975 for (size_t i = 0; i < effectChains.size(); i ++) {
1976 effectChains[i]->process_l();
1977 }
1978 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001979 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 mLastWriteTime = systemTime();
1981 mInWrite = true;
1982 mBytesWritten += mixBufferSize;
1983
Dima Zavin799a70e2011-04-18 16:57:27 -07001984 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1986 mNumWrites++;
1987 mInWrite = false;
1988 nsecs_t now = systemTime();
1989 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07001990 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001991 mNumDelayedWrites++;
1992 if ((now - lastWarning) > kWarningThrottle) {
1993 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1994 ns2ms(delta), mNumDelayedWrites, this);
1995 lastWarning = now;
1996 }
1997 if (mStandby) {
1998 longStandbyExit = true;
1999 }
2000 }
2001 mStandby = false;
2002 } else {
2003 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002004 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 usleep(sleepTime);
2006 }
2007
2008 // finally let go of all our tracks, without the lock held
2009 // since we can't guarantee the destructors won't acquire that
2010 // same lock.
2011 tracksToRemove.clear();
2012
2013 // Effect chains will be actually deleted here if they were removed from
2014 // mEffectChains list during mixing or effects processing
2015 effectChains.clear();
2016 }
2017
2018 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002019 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 }
2021
Eric Laurentfeb0db62011-07-22 09:04:31 -07002022 releaseWakeLock();
2023
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 LOGV("MixerThread %p exiting", this);
2025 return false;
2026}
2027
2028// prepareTracks_l() must be called with ThreadBase::mLock held
2029uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2030{
2031
2032 uint32_t mixerStatus = MIXER_IDLE;
2033 // find out which tracks need to be processed
2034 size_t count = activeTracks.size();
2035 size_t mixedTracks = 0;
2036 size_t tracksWithEffect = 0;
2037
2038 float masterVolume = mMasterVolume;
2039 bool masterMute = mMasterMute;
2040
Eric Laurent571d49c2010-08-11 05:20:11 -07002041 if (masterMute) {
2042 masterVolume = 0;
2043 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002045 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002047 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002048 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 masterVolume = (float)((v + (1 << 23)) >> 24);
2050 chain.clear();
2051 }
2052
2053 for (size_t i=0 ; i<count ; i++) {
2054 sp<Track> t = activeTracks[i].promote();
2055 if (t == 0) continue;
2056
2057 Track* const track = t.get();
2058 audio_track_cblk_t* cblk = track->cblk();
2059
2060 // The first time a track is added we wait
2061 // for all its buffers to be filled before processing it
2062 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07002063 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002064 !track->isPaused() && !track->isTerminated())
2065 {
2066 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2067
2068 mixedTracks++;
2069
2070 // track->mainBuffer() != mMixBuffer means there is an effect chain
2071 // connected to the track
2072 chain.clear();
2073 if (track->mainBuffer() != mMixBuffer) {
2074 chain = getEffectChain_l(track->sessionId());
2075 // Delegate volume control to effect in track effect chain if needed
2076 if (chain != 0) {
2077 tracksWithEffect++;
2078 } else {
2079 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2080 track->name(), track->sessionId());
2081 }
2082 }
2083
2084
2085 int param = AudioMixer::VOLUME;
2086 if (track->mFillingUpStatus == Track::FS_FILLED) {
2087 // no ramp for the first volume setting
2088 track->mFillingUpStatus = Track::FS_ACTIVE;
2089 if (track->mState == TrackBase::RESUMING) {
2090 track->mState = TrackBase::ACTIVE;
2091 param = AudioMixer::RAMP_VOLUME;
2092 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002093 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 } else if (cblk->server != 0) {
2095 // If the track is stopped before the first frame was mixed,
2096 // do not apply ramp
2097 param = AudioMixer::RAMP_VOLUME;
2098 }
2099
2100 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002101 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002102 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002103 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002104 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 if (track->isPausing()) {
2106 track->setPaused();
2107 }
2108 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002109
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 // read original volumes with volume control
2111 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002112 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002113 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2114 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115
Eric Laurente0aed6d2010-09-10 17:44:44 -07002116 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002117 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002118 // Delegate volume control to effect in track effect chain if needed
2119 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2120 // Do not ramp volume if volume is controlled by effect
2121 param = AudioMixer::VOLUME;
2122 track->mHasVolumeController = true;
2123 } else {
2124 // force no volume ramp when volume controller was just disabled or removed
2125 // from effect chain to avoid volume spike
2126 if (track->mHasVolumeController) {
2127 param = AudioMixer::VOLUME;
2128 }
2129 track->mHasVolumeController = false;
2130 }
2131
2132 // Convert volumes from 8.24 to 4.12 format
2133 int16_t left, right, aux;
2134 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2135 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2136 left = int16_t(v_clamped);
2137 v_clamped = (vr + (1 << 11)) >> 12;
2138 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2139 right = int16_t(v_clamped);
2140
2141 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2142 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 // XXX: these things DON'T need to be done each time
2145 mAudioMixer->setBufferProvider(track);
2146 mAudioMixer->enable(AudioMixer::MIXING);
2147
2148 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2149 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2150 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2151 mAudioMixer->setParameter(
2152 AudioMixer::TRACK,
2153 AudioMixer::FORMAT, (void *)track->format());
2154 mAudioMixer->setParameter(
2155 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002156 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 mAudioMixer->setParameter(
2158 AudioMixer::RESAMPLE,
2159 AudioMixer::SAMPLE_RATE,
2160 (void *)(cblk->sampleRate));
2161 mAudioMixer->setParameter(
2162 AudioMixer::TRACK,
2163 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2164 mAudioMixer->setParameter(
2165 AudioMixer::TRACK,
2166 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2167
2168 // reset retry count
2169 track->mRetryCount = kMaxTrackRetries;
2170 mixerStatus = MIXER_TRACKS_READY;
2171 } else {
2172 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2173 if (track->isStopped()) {
2174 track->reset();
2175 }
2176 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2177 // We have consumed all the buffers of this track.
2178 // Remove it from the list of active tracks.
2179 tracksToRemove->add(track);
2180 } else {
2181 // No buffers for this track. Give it a few chances to
2182 // fill a buffer, then remove it from active list.
2183 if (--(track->mRetryCount) <= 0) {
2184 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2185 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002186 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002187 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 } else if (mixerStatus != MIXER_TRACKS_READY) {
2189 mixerStatus = MIXER_TRACKS_ENABLED;
2190 }
2191 }
2192 mAudioMixer->disable(AudioMixer::MIXING);
2193 }
2194 }
2195
2196 // remove all the tracks that need to be...
2197 count = tracksToRemove->size();
2198 if (UNLIKELY(count)) {
2199 for (size_t i=0 ; i<count ; i++) {
2200 const sp<Track>& track = tracksToRemove->itemAt(i);
2201 mActiveTracks.remove(track);
2202 if (track->mainBuffer() != mMixBuffer) {
2203 chain = getEffectChain_l(track->sessionId());
2204 if (chain != 0) {
2205 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002206 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 }
2208 }
2209 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002210 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002211 }
2212 }
2213 }
2214
2215 // mix buffer must be cleared if all tracks are connected to an
2216 // effect chain as in this case the mixer will not write to
2217 // mix buffer and track effects will accumulate into it
2218 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2219 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2220 }
2221
2222 return mixerStatus;
2223}
2224
2225void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2226{
Eric Laurentde070132010-07-13 04:45:46 -07002227 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2228 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002230
Mathias Agopian65ab4712010-07-14 17:59:35 -07002231 size_t size = mTracks.size();
2232 for (size_t i = 0; i < size; i++) {
2233 sp<Track> t = mTracks[i];
2234 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002235 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002236 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002237 }
2238 }
2239}
2240
Eric Laurent9f6530f2011-08-30 10:18:54 -07002241void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2242{
2243 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2244 this, streamType, valid);
2245 Mutex::Autolock _l(mLock);
2246
2247 mStreamTypes[streamType].valid = valid;
2248}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249
2250// getTrackName_l() must be called with ThreadBase::mLock held
2251int AudioFlinger::MixerThread::getTrackName_l()
2252{
2253 return mAudioMixer->getTrackName();
2254}
2255
2256// deleteTrackName_l() must be called with ThreadBase::mLock held
2257void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2258{
2259 LOGV("remove track (%d) and delete from mixer", name);
2260 mAudioMixer->deleteTrackName(name);
2261}
2262
2263// checkForNewParameters_l() must be called with ThreadBase::mLock held
2264bool AudioFlinger::MixerThread::checkForNewParameters_l()
2265{
2266 bool reconfig = false;
2267
2268 while (!mNewParameters.isEmpty()) {
2269 status_t status = NO_ERROR;
2270 String8 keyValuePair = mNewParameters[0];
2271 AudioParameter param = AudioParameter(keyValuePair);
2272 int value;
2273
2274 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2275 reconfig = true;
2276 }
2277 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002278 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002279 status = BAD_VALUE;
2280 } else {
2281 reconfig = true;
2282 }
2283 }
2284 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002285 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 status = BAD_VALUE;
2287 } else {
2288 reconfig = true;
2289 }
2290 }
2291 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2292 // do not accept frame count changes if tracks are open as the track buffer
2293 // size depends on frame count and correct behavior would not be garantied
2294 // if frame count is changed after track creation
2295 if (!mTracks.isEmpty()) {
2296 status = INVALID_OPERATION;
2297 } else {
2298 reconfig = true;
2299 }
2300 }
2301 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002302 // when changing the audio output device, call addBatteryData to notify
2303 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002304 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002305 uint32_t params = 0;
2306 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002307 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002308 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2309 }
2310
2311 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002312 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002313 // check if any other device (except speaker) is on
2314 if (value & deviceWithoutSpeaker ) {
2315 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2316 }
2317
2318 if (params != 0) {
2319 addBatteryData(params);
2320 }
2321 }
2322
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 // forward device change to effects that have requested to be
2324 // aware of attached audio device.
2325 mDevice = (uint32_t)value;
2326 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002327 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 }
2329 }
2330
2331 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002332 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002333 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002334 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002335 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 mStandby = true;
2337 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002338 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002339 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 }
2341 if (status == NO_ERROR && reconfig) {
2342 delete mAudioMixer;
2343 readOutputParameters();
2344 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2345 for (size_t i = 0; i < mTracks.size() ; i++) {
2346 int name = getTrackName_l();
2347 if (name < 0) break;
2348 mTracks[i]->mName = name;
2349 // limit track sample rate to 2 x new output sample rate
2350 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2351 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2352 }
2353 }
2354 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2355 }
2356 }
2357
2358 mNewParameters.removeAt(0);
2359
2360 mParamStatus = status;
2361 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002362 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2363 // already timed out waiting for the status and will never signal the condition.
2364 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 }
2366 return reconfig;
2367}
2368
2369status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2370{
2371 const size_t SIZE = 256;
2372 char buffer[SIZE];
2373 String8 result;
2374
2375 PlaybackThread::dumpInternals(fd, args);
2376
2377 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2378 result.append(buffer);
2379 write(fd, result.string(), result.size());
2380 return NO_ERROR;
2381}
2382
2383uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2384{
Dima Zavin799a70e2011-04-18 16:57:27 -07002385 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386}
2387
2388uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2389{
Eric Laurent60e18242010-07-29 06:50:24 -07002390 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002391}
2392
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002393uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2394{
2395 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2396}
2397
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002399AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 : PlaybackThread(audioFlinger, output, id, device)
2401{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002402 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403}
2404
2405AudioFlinger::DirectOutputThread::~DirectOutputThread()
2406{
2407}
2408
2409
2410static inline int16_t clamp16(int32_t sample)
2411{
2412 if ((sample>>15) ^ (sample>>31))
2413 sample = 0x7FFF ^ (sample>>31);
2414 return sample;
2415}
2416
2417static inline
2418int32_t mul(int16_t in, int16_t v)
2419{
2420#if defined(__arm__) && !defined(__thumb__)
2421 int32_t out;
2422 asm( "smulbb %[out], %[in], %[v] \n"
2423 : [out]"=r"(out)
2424 : [in]"%r"(in), [v]"r"(v)
2425 : );
2426 return out;
2427#else
2428 return in * int32_t(v);
2429#endif
2430}
2431
2432void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2433{
2434 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002435 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 return;
2437 }
2438
2439 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002440 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002441 size_t count = mFrameCount * mChannelCount;
2442 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2443 int16_t *dst = mMixBuffer + count-1;
2444 while(count--) {
2445 *dst-- = (int16_t)(*src--^0x80) << 8;
2446 }
2447 }
2448
2449 size_t frameCount = mFrameCount;
2450 int16_t *out = mMixBuffer;
2451 if (ramp) {
2452 if (mChannelCount == 1) {
2453 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2454 int32_t vlInc = d / (int32_t)frameCount;
2455 int32_t vl = ((int32_t)mLeftVolShort << 16);
2456 do {
2457 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2458 out++;
2459 vl += vlInc;
2460 } while (--frameCount);
2461
2462 } else {
2463 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2464 int32_t vlInc = d / (int32_t)frameCount;
2465 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2466 int32_t vrInc = d / (int32_t)frameCount;
2467 int32_t vl = ((int32_t)mLeftVolShort << 16);
2468 int32_t vr = ((int32_t)mRightVolShort << 16);
2469 do {
2470 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2471 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2472 out += 2;
2473 vl += vlInc;
2474 vr += vrInc;
2475 } while (--frameCount);
2476 }
2477 } else {
2478 if (mChannelCount == 1) {
2479 do {
2480 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2481 out++;
2482 } while (--frameCount);
2483 } else {
2484 do {
2485 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2486 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2487 out += 2;
2488 } while (--frameCount);
2489 }
2490 }
2491
2492 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002493 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002494 size_t count = mFrameCount * mChannelCount;
2495 int16_t *src = mMixBuffer;
2496 uint8_t *dst = (uint8_t *)mMixBuffer;
2497 while(count--) {
2498 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2499 }
2500 }
2501
2502 mLeftVolShort = leftVol;
2503 mRightVolShort = rightVol;
2504}
2505
2506bool AudioFlinger::DirectOutputThread::threadLoop()
2507{
2508 uint32_t mixerStatus = MIXER_IDLE;
2509 sp<Track> trackToRemove;
2510 sp<Track> activeTrack;
2511 nsecs_t standbyTime = systemTime();
2512 int8_t *curBuf;
2513 size_t mixBufferSize = mFrameCount*mFrameSize;
2514 uint32_t activeSleepTime = activeSleepTimeUs();
2515 uint32_t idleSleepTime = idleSleepTimeUs();
2516 uint32_t sleepTime = idleSleepTime;
2517 // use shorter standby delay as on normal output to release
2518 // hardware resources as soon as possible
2519 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2520
Eric Laurentfeb0db62011-07-22 09:04:31 -07002521 acquireWakeLock();
2522
Mathias Agopian65ab4712010-07-14 17:59:35 -07002523 while (!exitPending())
2524 {
2525 bool rampVolume;
2526 uint16_t leftVol;
2527 uint16_t rightVol;
2528 Vector< sp<EffectChain> > effectChains;
2529
2530 processConfigEvents();
2531
2532 mixerStatus = MIXER_IDLE;
2533
2534 { // scope for the mLock
2535
2536 Mutex::Autolock _l(mLock);
2537
2538 if (checkForNewParameters_l()) {
2539 mixBufferSize = mFrameCount*mFrameSize;
2540 activeSleepTime = activeSleepTimeUs();
2541 idleSleepTime = idleSleepTimeUs();
2542 standbyDelay = microseconds(activeSleepTime*2);
2543 }
2544
2545 // put audio hardware into standby after short delay
2546 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2547 mSuspended) {
2548 // wait until we have something to do...
2549 if (!mStandby) {
2550 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002551 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002552 mStandby = true;
2553 mBytesWritten = 0;
2554 }
2555
2556 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2557 // we're about to wait, flush the binder command buffer
2558 IPCThreadState::self()->flushCommands();
2559
2560 if (exitPending()) break;
2561
Eric Laurentfeb0db62011-07-22 09:04:31 -07002562 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2564 mWaitWorkCV.wait(mLock);
2565 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002566 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002567
2568 if (mMasterMute == false) {
2569 char value[PROPERTY_VALUE_MAX];
2570 property_get("ro.audio.silent", value, "0");
2571 if (atoi(value)) {
2572 LOGD("Silence is golden");
2573 setMasterMute(true);
2574 }
2575 }
2576
2577 standbyTime = systemTime() + standbyDelay;
2578 sleepTime = idleSleepTime;
2579 continue;
2580 }
2581 }
2582
2583 effectChains = mEffectChains;
2584
2585 // find out which tracks need to be processed
2586 if (mActiveTracks.size() != 0) {
2587 sp<Track> t = mActiveTracks[0].promote();
2588 if (t == 0) continue;
2589
2590 Track* const track = t.get();
2591 audio_track_cblk_t* cblk = track->cblk();
2592
2593 // The first time a track is added we wait
2594 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002595 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002596 !track->isPaused() && !track->isTerminated())
2597 {
2598 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2599
2600 if (track->mFillingUpStatus == Track::FS_FILLED) {
2601 track->mFillingUpStatus = Track::FS_ACTIVE;
2602 mLeftVolFloat = mRightVolFloat = 0;
2603 mLeftVolShort = mRightVolShort = 0;
2604 if (track->mState == TrackBase::RESUMING) {
2605 track->mState = TrackBase::ACTIVE;
2606 rampVolume = true;
2607 }
2608 } else if (cblk->server != 0) {
2609 // If the track is stopped before the first frame was mixed,
2610 // do not apply ramp
2611 rampVolume = true;
2612 }
2613 // compute volume for this track
2614 float left, right;
2615 if (track->isMuted() || mMasterMute || track->isPausing() ||
2616 mStreamTypes[track->type()].mute) {
2617 left = right = 0;
2618 if (track->isPausing()) {
2619 track->setPaused();
2620 }
2621 } else {
2622 float typeVolume = mStreamTypes[track->type()].volume;
2623 float v = mMasterVolume * typeVolume;
2624 float v_clamped = v * cblk->volume[0];
2625 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2626 left = v_clamped/MAX_GAIN;
2627 v_clamped = v * cblk->volume[1];
2628 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2629 right = v_clamped/MAX_GAIN;
2630 }
2631
2632 if (left != mLeftVolFloat || right != mRightVolFloat) {
2633 mLeftVolFloat = left;
2634 mRightVolFloat = right;
2635
2636 // If audio HAL implements volume control,
2637 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002638 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 left = 1.0f;
2640 right = 1.0f;
2641 }
2642
2643 // Convert volumes from float to 8.24
2644 uint32_t vl = (uint32_t)(left * (1 << 24));
2645 uint32_t vr = (uint32_t)(right * (1 << 24));
2646
2647 // Delegate volume control to effect in track effect chain if needed
2648 // only one effect chain can be present on DirectOutputThread, so if
2649 // there is one, the track is connected to it
2650 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002651 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002652 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 rampVolume = false;
2654 }
2655 }
2656
2657 // Convert volumes from 8.24 to 4.12 format
2658 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2659 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2660 leftVol = (uint16_t)v_clamped;
2661 v_clamped = (vr + (1 << 11)) >> 12;
2662 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2663 rightVol = (uint16_t)v_clamped;
2664 } else {
2665 leftVol = mLeftVolShort;
2666 rightVol = mRightVolShort;
2667 rampVolume = false;
2668 }
2669
2670 // reset retry count
2671 track->mRetryCount = kMaxTrackRetriesDirect;
2672 activeTrack = t;
2673 mixerStatus = MIXER_TRACKS_READY;
2674 } else {
2675 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2676 if (track->isStopped()) {
2677 track->reset();
2678 }
2679 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2680 // We have consumed all the buffers of this track.
2681 // Remove it from the list of active tracks.
2682 trackToRemove = track;
2683 } else {
2684 // No buffers for this track. Give it a few chances to
2685 // fill a buffer, then remove it from active list.
2686 if (--(track->mRetryCount) <= 0) {
2687 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2688 trackToRemove = track;
2689 } else {
2690 mixerStatus = MIXER_TRACKS_ENABLED;
2691 }
2692 }
2693 }
2694 }
2695
2696 // remove all the tracks that need to be...
2697 if (UNLIKELY(trackToRemove != 0)) {
2698 mActiveTracks.remove(trackToRemove);
2699 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002700 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2701 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002702 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002703 }
2704 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002705 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 }
2707 }
2708
Eric Laurentde070132010-07-13 04:45:46 -07002709 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 }
2711
2712 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2713 AudioBufferProvider::Buffer buffer;
2714 size_t frameCount = mFrameCount;
2715 curBuf = (int8_t *)mMixBuffer;
2716 // output audio to hardware
2717 while (frameCount) {
2718 buffer.frameCount = frameCount;
2719 activeTrack->getNextBuffer(&buffer);
2720 if (UNLIKELY(buffer.raw == 0)) {
2721 memset(curBuf, 0, frameCount * mFrameSize);
2722 break;
2723 }
2724 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2725 frameCount -= buffer.frameCount;
2726 curBuf += buffer.frameCount * mFrameSize;
2727 activeTrack->releaseBuffer(&buffer);
2728 }
2729 sleepTime = 0;
2730 standbyTime = systemTime() + standbyDelay;
2731 } else {
2732 if (sleepTime == 0) {
2733 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2734 sleepTime = activeSleepTime;
2735 } else {
2736 sleepTime = idleSleepTime;
2737 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002738 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2740 sleepTime = 0;
2741 }
2742 }
2743
2744 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002745 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746 }
2747 // sleepTime == 0 means we must write to audio hardware
2748 if (sleepTime == 0) {
2749 if (mixerStatus == MIXER_TRACKS_READY) {
2750 applyVolume(leftVol, rightVol, rampVolume);
2751 }
2752 for (size_t i = 0; i < effectChains.size(); i ++) {
2753 effectChains[i]->process_l();
2754 }
Eric Laurentde070132010-07-13 04:45:46 -07002755 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002756
2757 mLastWriteTime = systemTime();
2758 mInWrite = true;
2759 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002760 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2762 mNumWrites++;
2763 mInWrite = false;
2764 mStandby = false;
2765 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002766 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 usleep(sleepTime);
2768 }
2769
2770 // finally let go of removed track, without the lock held
2771 // since we can't guarantee the destructors won't acquire that
2772 // same lock.
2773 trackToRemove.clear();
2774 activeTrack.clear();
2775
2776 // Effect chains will be actually deleted here if they were removed from
2777 // mEffectChains list during mixing or effects processing
2778 effectChains.clear();
2779 }
2780
2781 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002782 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783 }
2784
Eric Laurentfeb0db62011-07-22 09:04:31 -07002785 releaseWakeLock();
2786
Mathias Agopian65ab4712010-07-14 17:59:35 -07002787 LOGV("DirectOutputThread %p exiting", this);
2788 return false;
2789}
2790
2791// getTrackName_l() must be called with ThreadBase::mLock held
2792int AudioFlinger::DirectOutputThread::getTrackName_l()
2793{
2794 return 0;
2795}
2796
2797// deleteTrackName_l() must be called with ThreadBase::mLock held
2798void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2799{
2800}
2801
2802// checkForNewParameters_l() must be called with ThreadBase::mLock held
2803bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2804{
2805 bool reconfig = false;
2806
2807 while (!mNewParameters.isEmpty()) {
2808 status_t status = NO_ERROR;
2809 String8 keyValuePair = mNewParameters[0];
2810 AudioParameter param = AudioParameter(keyValuePair);
2811 int value;
2812
2813 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2814 // do not accept frame count changes if tracks are open as the track buffer
2815 // size depends on frame count and correct behavior would not be garantied
2816 // if frame count is changed after track creation
2817 if (!mTracks.isEmpty()) {
2818 status = INVALID_OPERATION;
2819 } else {
2820 reconfig = true;
2821 }
2822 }
2823 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002824 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002825 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002827 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 mStandby = true;
2829 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002830 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002831 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002832 }
2833 if (status == NO_ERROR && reconfig) {
2834 readOutputParameters();
2835 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2836 }
2837 }
2838
2839 mNewParameters.removeAt(0);
2840
2841 mParamStatus = status;
2842 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002843 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2844 // already timed out waiting for the status and will never signal the condition.
2845 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002846 }
2847 return reconfig;
2848}
2849
2850uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2851{
2852 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002853 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002854 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002855 } else {
2856 time = 10000;
2857 }
2858 return time;
2859}
2860
2861uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2862{
2863 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002864 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002865 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002866 } else {
2867 time = 10000;
2868 }
2869 return time;
2870}
2871
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002872uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2873{
2874 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002875 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002876 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2877 } else {
2878 time = 10000;
2879 }
2880 return time;
2881}
2882
2883
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884// ----------------------------------------------------------------------------
2885
2886AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2887 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2888{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002889 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002890 addOutputTrack(mainThread);
2891}
2892
2893AudioFlinger::DuplicatingThread::~DuplicatingThread()
2894{
2895 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2896 mOutputTracks[i]->destroy();
2897 }
2898 mOutputTracks.clear();
2899}
2900
2901bool AudioFlinger::DuplicatingThread::threadLoop()
2902{
2903 Vector< sp<Track> > tracksToRemove;
2904 uint32_t mixerStatus = MIXER_IDLE;
2905 nsecs_t standbyTime = systemTime();
2906 size_t mixBufferSize = mFrameCount*mFrameSize;
2907 SortedVector< sp<OutputTrack> > outputTracks;
2908 uint32_t writeFrames = 0;
2909 uint32_t activeSleepTime = activeSleepTimeUs();
2910 uint32_t idleSleepTime = idleSleepTimeUs();
2911 uint32_t sleepTime = idleSleepTime;
2912 Vector< sp<EffectChain> > effectChains;
2913
Eric Laurentfeb0db62011-07-22 09:04:31 -07002914 acquireWakeLock();
2915
Mathias Agopian65ab4712010-07-14 17:59:35 -07002916 while (!exitPending())
2917 {
2918 processConfigEvents();
2919
2920 mixerStatus = MIXER_IDLE;
2921 { // scope for the mLock
2922
2923 Mutex::Autolock _l(mLock);
2924
2925 if (checkForNewParameters_l()) {
2926 mixBufferSize = mFrameCount*mFrameSize;
2927 updateWaitTime();
2928 activeSleepTime = activeSleepTimeUs();
2929 idleSleepTime = idleSleepTimeUs();
2930 }
2931
2932 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2933
2934 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2935 outputTracks.add(mOutputTracks[i]);
2936 }
2937
2938 // put audio hardware into standby after short delay
2939 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2940 mSuspended) {
2941 if (!mStandby) {
2942 for (size_t i = 0; i < outputTracks.size(); i++) {
2943 outputTracks[i]->stop();
2944 }
2945 mStandby = true;
2946 mBytesWritten = 0;
2947 }
2948
2949 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2950 // we're about to wait, flush the binder command buffer
2951 IPCThreadState::self()->flushCommands();
2952 outputTracks.clear();
2953
2954 if (exitPending()) break;
2955
Eric Laurentfeb0db62011-07-22 09:04:31 -07002956 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002957 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2958 mWaitWorkCV.wait(mLock);
2959 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002960 acquireWakeLock_l();
2961
Mathias Agopian65ab4712010-07-14 17:59:35 -07002962 if (mMasterMute == false) {
2963 char value[PROPERTY_VALUE_MAX];
2964 property_get("ro.audio.silent", value, "0");
2965 if (atoi(value)) {
2966 LOGD("Silence is golden");
2967 setMasterMute(true);
2968 }
2969 }
2970
2971 standbyTime = systemTime() + kStandbyTimeInNsecs;
2972 sleepTime = idleSleepTime;
2973 continue;
2974 }
2975 }
2976
2977 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2978
2979 // prevent any changes in effect chain list and in each effect chain
2980 // during mixing and effect process as the audio buffers could be deleted
2981 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002982 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002983 }
2984
2985 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2986 // mix buffers...
2987 if (outputsReady(outputTracks)) {
2988 mAudioMixer->process();
2989 } else {
2990 memset(mMixBuffer, 0, mixBufferSize);
2991 }
2992 sleepTime = 0;
2993 writeFrames = mFrameCount;
2994 } else {
2995 if (sleepTime == 0) {
2996 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2997 sleepTime = activeSleepTime;
2998 } else {
2999 sleepTime = idleSleepTime;
3000 }
3001 } else if (mBytesWritten != 0) {
3002 // flush remaining overflow buffers in output tracks
3003 for (size_t i = 0; i < outputTracks.size(); i++) {
3004 if (outputTracks[i]->isActive()) {
3005 sleepTime = 0;
3006 writeFrames = 0;
3007 memset(mMixBuffer, 0, mixBufferSize);
3008 break;
3009 }
3010 }
3011 }
3012 }
3013
3014 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003015 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016 }
3017 // sleepTime == 0 means we must write to audio hardware
3018 if (sleepTime == 0) {
3019 for (size_t i = 0; i < effectChains.size(); i ++) {
3020 effectChains[i]->process_l();
3021 }
3022 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003023 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024
3025 standbyTime = systemTime() + kStandbyTimeInNsecs;
3026 for (size_t i = 0; i < outputTracks.size(); i++) {
3027 outputTracks[i]->write(mMixBuffer, writeFrames);
3028 }
3029 mStandby = false;
3030 mBytesWritten += mixBufferSize;
3031 } else {
3032 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003033 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034 usleep(sleepTime);
3035 }
3036
3037 // finally let go of all our tracks, without the lock held
3038 // since we can't guarantee the destructors won't acquire that
3039 // same lock.
3040 tracksToRemove.clear();
3041 outputTracks.clear();
3042
3043 // Effect chains will be actually deleted here if they were removed from
3044 // mEffectChains list during mixing or effects processing
3045 effectChains.clear();
3046 }
3047
Eric Laurentfeb0db62011-07-22 09:04:31 -07003048 releaseWakeLock();
3049
Mathias Agopian65ab4712010-07-14 17:59:35 -07003050 return false;
3051}
3052
3053void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3054{
3055 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3056 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3057 this,
3058 mSampleRate,
3059 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003060 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003061 frameCount);
3062 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003063 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003064 mOutputTracks.add(outputTrack);
3065 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3066 updateWaitTime();
3067 }
3068}
3069
3070void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3071{
3072 Mutex::Autolock _l(mLock);
3073 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3074 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3075 mOutputTracks[i]->destroy();
3076 mOutputTracks.removeAt(i);
3077 updateWaitTime();
3078 return;
3079 }
3080 }
3081 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3082}
3083
3084void AudioFlinger::DuplicatingThread::updateWaitTime()
3085{
3086 mWaitTimeMs = UINT_MAX;
3087 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3088 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3089 if (strong != NULL) {
3090 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3091 if (waitTimeMs < mWaitTimeMs) {
3092 mWaitTimeMs = waitTimeMs;
3093 }
3094 }
3095 }
3096}
3097
3098
3099bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3100{
3101 for (size_t i = 0; i < outputTracks.size(); i++) {
3102 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3103 if (thread == 0) {
3104 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3105 return false;
3106 }
3107 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3108 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3109 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3110 return false;
3111 }
3112 }
3113 return true;
3114}
3115
3116uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3117{
3118 return (mWaitTimeMs * 1000) / 2;
3119}
3120
3121// ----------------------------------------------------------------------------
3122
3123// TrackBase constructor must be called with AudioFlinger::mLock held
3124AudioFlinger::ThreadBase::TrackBase::TrackBase(
3125 const wp<ThreadBase>& thread,
3126 const sp<Client>& client,
3127 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003128 uint32_t format,
3129 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003130 int frameCount,
3131 uint32_t flags,
3132 const sp<IMemory>& sharedBuffer,
3133 int sessionId)
3134 : RefBase(),
3135 mThread(thread),
3136 mClient(client),
3137 mCblk(0),
3138 mFrameCount(0),
3139 mState(IDLE),
3140 mClientTid(-1),
3141 mFormat(format),
3142 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3143 mSessionId(sessionId)
3144{
3145 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3146
3147 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3148 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003149 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003150 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3151 if (sharedBuffer == 0) {
3152 size += bufferSize;
3153 }
3154
3155 if (client != NULL) {
3156 mCblkMemory = client->heap()->allocate(size);
3157 if (mCblkMemory != 0) {
3158 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3159 if (mCblk) { // construct the shared structure in-place.
3160 new(mCblk) audio_track_cblk_t();
3161 // clear all buffers
3162 mCblk->frameCount = frameCount;
3163 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003164 mChannelCount = channelCount;
3165 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003166 if (sharedBuffer == 0) {
3167 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3168 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3169 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003170 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 mCblk->flags = CBLK_UNDERRUN_ON;
3172 } else {
3173 mBuffer = sharedBuffer->pointer();
3174 }
3175 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3176 }
3177 } else {
3178 LOGE("not enough memory for AudioTrack size=%u", size);
3179 client->heap()->dump("AudioTrack");
3180 return;
3181 }
3182 } else {
3183 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3184 if (mCblk) { // construct the shared structure in-place.
3185 new(mCblk) audio_track_cblk_t();
3186 // clear all buffers
3187 mCblk->frameCount = frameCount;
3188 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003189 mChannelCount = channelCount;
3190 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3192 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3193 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003194 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003195 mCblk->flags = CBLK_UNDERRUN_ON;
3196 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3197 }
3198 }
3199}
3200
3201AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3202{
3203 if (mCblk) {
3204 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3205 if (mClient == NULL) {
3206 delete mCblk;
3207 }
3208 }
3209 mCblkMemory.clear(); // and free the shared memory
3210 if (mClient != NULL) {
3211 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3212 mClient.clear();
3213 }
3214}
3215
3216void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3217{
3218 buffer->raw = 0;
3219 mFrameCount = buffer->frameCount;
3220 step();
3221 buffer->frameCount = 0;
3222}
3223
3224bool AudioFlinger::ThreadBase::TrackBase::step() {
3225 bool result;
3226 audio_track_cblk_t* cblk = this->cblk();
3227
3228 result = cblk->stepServer(mFrameCount);
3229 if (!result) {
3230 LOGV("stepServer failed acquiring cblk mutex");
3231 mFlags |= STEPSERVER_FAILED;
3232 }
3233 return result;
3234}
3235
3236void AudioFlinger::ThreadBase::TrackBase::reset() {
3237 audio_track_cblk_t* cblk = this->cblk();
3238
3239 cblk->user = 0;
3240 cblk->server = 0;
3241 cblk->userBase = 0;
3242 cblk->serverBase = 0;
3243 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3244 LOGV("TrackBase::reset");
3245}
3246
3247sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3248{
3249 return mCblkMemory;
3250}
3251
3252int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3253 return (int)mCblk->sampleRate;
3254}
3255
3256int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003257 return (const int)mChannelCount;
3258}
3259
3260uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3261 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003262}
3263
3264void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3265 audio_track_cblk_t* cblk = this->cblk();
3266 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3267 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3268
3269 // Check validity of returned pointer in case the track control block would have been corrupted.
3270 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3271 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3272 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003273 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003275 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003276 return 0;
3277 }
3278
3279 return bufferStart;
3280}
3281
3282// ----------------------------------------------------------------------------
3283
3284// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3285AudioFlinger::PlaybackThread::Track::Track(
3286 const wp<ThreadBase>& thread,
3287 const sp<Client>& client,
3288 int streamType,
3289 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003290 uint32_t format,
3291 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 int frameCount,
3293 const sp<IMemory>& sharedBuffer,
3294 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003295 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003296 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3297 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003298{
3299 if (mCblk != NULL) {
3300 sp<ThreadBase> baseThread = thread.promote();
3301 if (baseThread != 0) {
3302 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3303 mName = playbackThread->getTrackName_l();
3304 mMainBuffer = playbackThread->mixBuffer();
3305 }
3306 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3307 if (mName < 0) {
3308 LOGE("no more track names available");
3309 }
3310 mVolume[0] = 1.0f;
3311 mVolume[1] = 1.0f;
3312 mStreamType = streamType;
3313 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3314 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003315 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316 }
3317}
3318
3319AudioFlinger::PlaybackThread::Track::~Track()
3320{
3321 LOGV("PlaybackThread::Track destructor");
3322 sp<ThreadBase> thread = mThread.promote();
3323 if (thread != 0) {
3324 Mutex::Autolock _l(thread->mLock);
3325 mState = TERMINATED;
3326 }
3327}
3328
3329void AudioFlinger::PlaybackThread::Track::destroy()
3330{
3331 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3332 // by removing it from mTracks vector, so there is a risk that this Tracks's
3333 // desctructor is called. As the destructor needs to lock mLock,
3334 // we must acquire a strong reference on this Track before locking mLock
3335 // here so that the destructor is called only when exiting this function.
3336 // On the other hand, as long as Track::destroy() is only called by
3337 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3338 // this Track with its member mTrack.
3339 sp<Track> keep(this);
3340 { // scope for mLock
3341 sp<ThreadBase> thread = mThread.promote();
3342 if (thread != 0) {
3343 if (!isOutputTrack()) {
3344 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003345 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003346 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003347 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003348
3349 // to track the speaker usage
3350 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 }
3352 AudioSystem::releaseOutput(thread->id());
3353 }
3354 Mutex::Autolock _l(thread->mLock);
3355 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3356 playbackThread->destroyTrack_l(this);
3357 }
3358 }
3359}
3360
3361void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3362{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003363 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 -07003364 mName - AudioMixer::TRACK0,
3365 (mClient == NULL) ? getpid() : mClient->pid(),
3366 mStreamType,
3367 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003368 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003369 mSessionId,
3370 mFrameCount,
3371 mState,
3372 mMute,
3373 mFillingUpStatus,
3374 mCblk->sampleRate,
3375 mCblk->volume[0],
3376 mCblk->volume[1],
3377 mCblk->server,
3378 mCblk->user,
3379 (int)mMainBuffer,
3380 (int)mAuxBuffer);
3381}
3382
3383status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3384{
3385 audio_track_cblk_t* cblk = this->cblk();
3386 uint32_t framesReady;
3387 uint32_t framesReq = buffer->frameCount;
3388
3389 // Check if last stepServer failed, try to step now
3390 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3391 if (!step()) goto getNextBuffer_exit;
3392 LOGV("stepServer recovered");
3393 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3394 }
3395
3396 framesReady = cblk->framesReady();
3397
3398 if (LIKELY(framesReady)) {
3399 uint32_t s = cblk->server;
3400 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3401
3402 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3403 if (framesReq > framesReady) {
3404 framesReq = framesReady;
3405 }
3406 if (s + framesReq > bufferEnd) {
3407 framesReq = bufferEnd - s;
3408 }
3409
3410 buffer->raw = getBuffer(s, framesReq);
3411 if (buffer->raw == 0) goto getNextBuffer_exit;
3412
3413 buffer->frameCount = framesReq;
3414 return NO_ERROR;
3415 }
3416
3417getNextBuffer_exit:
3418 buffer->raw = 0;
3419 buffer->frameCount = 0;
3420 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3421 return NOT_ENOUGH_DATA;
3422}
3423
3424bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003425 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003426
3427 if (mCblk->framesReady() >= mCblk->frameCount ||
3428 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3429 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003430 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003431 return true;
3432 }
3433 return false;
3434}
3435
3436status_t AudioFlinger::PlaybackThread::Track::start()
3437{
3438 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003439 LOGV("start(%d), calling thread %d session %d",
3440 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003441 sp<ThreadBase> thread = mThread.promote();
3442 if (thread != 0) {
3443 Mutex::Autolock _l(thread->mLock);
3444 int state = mState;
3445 // here the track could be either new, or restarted
3446 // in both cases "unstop" the track
3447 if (mState == PAUSED) {
3448 mState = TrackBase::RESUMING;
3449 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3450 } else {
3451 mState = TrackBase::ACTIVE;
3452 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3453 }
3454
3455 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3456 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003457 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003458 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003459 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003460 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003461
3462 // to track the speaker usage
3463 if (status == NO_ERROR) {
3464 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 }
3467 if (status == NO_ERROR) {
3468 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3469 playbackThread->addTrack_l(this);
3470 } else {
3471 mState = state;
3472 }
3473 } else {
3474 status = BAD_VALUE;
3475 }
3476 return status;
3477}
3478
3479void AudioFlinger::PlaybackThread::Track::stop()
3480{
3481 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3482 sp<ThreadBase> thread = mThread.promote();
3483 if (thread != 0) {
3484 Mutex::Autolock _l(thread->mLock);
3485 int state = mState;
3486 if (mState > STOPPED) {
3487 mState = STOPPED;
3488 // If the track is not active (PAUSED and buffers full), flush buffers
3489 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3490 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3491 reset();
3492 }
3493 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3494 }
3495 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3496 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003497 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003498 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003499 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003501
3502 // to track the speaker usage
3503 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 }
3505 }
3506}
3507
3508void AudioFlinger::PlaybackThread::Track::pause()
3509{
3510 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3511 sp<ThreadBase> thread = mThread.promote();
3512 if (thread != 0) {
3513 Mutex::Autolock _l(thread->mLock);
3514 if (mState == ACTIVE || mState == RESUMING) {
3515 mState = PAUSING;
3516 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3517 if (!isOutputTrack()) {
3518 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003519 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003520 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003521 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003523
3524 // to track the speaker usage
3525 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003526 }
3527 }
3528 }
3529}
3530
3531void AudioFlinger::PlaybackThread::Track::flush()
3532{
3533 LOGV("flush(%d)", mName);
3534 sp<ThreadBase> thread = mThread.promote();
3535 if (thread != 0) {
3536 Mutex::Autolock _l(thread->mLock);
3537 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3538 return;
3539 }
3540 // No point remaining in PAUSED state after a flush => go to
3541 // STOPPED state
3542 mState = STOPPED;
3543
Eric Laurent38ccae22011-03-28 18:37:07 -07003544 // do not reset the track if it is still in the process of being stopped or paused.
3545 // this will be done by prepareTracks_l() when the track is stopped.
3546 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3547 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3548 reset();
3549 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 }
3551}
3552
3553void AudioFlinger::PlaybackThread::Track::reset()
3554{
3555 // Do not reset twice to avoid discarding data written just after a flush and before
3556 // the audioflinger thread detects the track is stopped.
3557 if (!mResetDone) {
3558 TrackBase::reset();
3559 // Force underrun condition to avoid false underrun callback until first data is
3560 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003561 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3562 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003563 mFillingUpStatus = FS_FILLING;
3564 mResetDone = true;
3565 }
3566}
3567
3568void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3569{
3570 mMute = muted;
3571}
3572
3573void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3574{
3575 mVolume[0] = left;
3576 mVolume[1] = right;
3577}
3578
3579status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3580{
3581 status_t status = DEAD_OBJECT;
3582 sp<ThreadBase> thread = mThread.promote();
3583 if (thread != 0) {
3584 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3585 status = playbackThread->attachAuxEffect(this, EffectId);
3586 }
3587 return status;
3588}
3589
3590void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3591{
3592 mAuxEffectId = EffectId;
3593 mAuxBuffer = buffer;
3594}
3595
3596// ----------------------------------------------------------------------------
3597
3598// RecordTrack constructor must be called with AudioFlinger::mLock held
3599AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3600 const wp<ThreadBase>& thread,
3601 const sp<Client>& client,
3602 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003603 uint32_t format,
3604 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003605 int frameCount,
3606 uint32_t flags,
3607 int sessionId)
3608 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003609 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 mOverflow(false)
3611{
3612 if (mCblk != NULL) {
3613 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003614 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003615 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003616 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003617 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 } else {
3619 mCblk->frameSize = sizeof(int8_t);
3620 }
3621 }
3622}
3623
3624AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3625{
3626 sp<ThreadBase> thread = mThread.promote();
3627 if (thread != 0) {
3628 AudioSystem::releaseInput(thread->id());
3629 }
3630}
3631
3632status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3633{
3634 audio_track_cblk_t* cblk = this->cblk();
3635 uint32_t framesAvail;
3636 uint32_t framesReq = buffer->frameCount;
3637
3638 // Check if last stepServer failed, try to step now
3639 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3640 if (!step()) goto getNextBuffer_exit;
3641 LOGV("stepServer recovered");
3642 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3643 }
3644
3645 framesAvail = cblk->framesAvailable_l();
3646
3647 if (LIKELY(framesAvail)) {
3648 uint32_t s = cblk->server;
3649 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3650
3651 if (framesReq > framesAvail) {
3652 framesReq = framesAvail;
3653 }
3654 if (s + framesReq > bufferEnd) {
3655 framesReq = bufferEnd - s;
3656 }
3657
3658 buffer->raw = getBuffer(s, framesReq);
3659 if (buffer->raw == 0) goto getNextBuffer_exit;
3660
3661 buffer->frameCount = framesReq;
3662 return NO_ERROR;
3663 }
3664
3665getNextBuffer_exit:
3666 buffer->raw = 0;
3667 buffer->frameCount = 0;
3668 return NOT_ENOUGH_DATA;
3669}
3670
3671status_t AudioFlinger::RecordThread::RecordTrack::start()
3672{
3673 sp<ThreadBase> thread = mThread.promote();
3674 if (thread != 0) {
3675 RecordThread *recordThread = (RecordThread *)thread.get();
3676 return recordThread->start(this);
3677 } else {
3678 return BAD_VALUE;
3679 }
3680}
3681
3682void AudioFlinger::RecordThread::RecordTrack::stop()
3683{
3684 sp<ThreadBase> thread = mThread.promote();
3685 if (thread != 0) {
3686 RecordThread *recordThread = (RecordThread *)thread.get();
3687 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003688 TrackBase::reset();
3689 // Force overerrun condition to avoid false overrun callback until first data is
3690 // read from buffer
3691 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003692 }
3693}
3694
3695void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3696{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003697 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 (mClient == NULL) ? getpid() : mClient->pid(),
3699 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003700 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003701 mSessionId,
3702 mFrameCount,
3703 mState,
3704 mCblk->sampleRate,
3705 mCblk->server,
3706 mCblk->user);
3707}
3708
3709
3710// ----------------------------------------------------------------------------
3711
3712AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3713 const wp<ThreadBase>& thread,
3714 DuplicatingThread *sourceThread,
3715 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003716 uint32_t format,
3717 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003719 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003720 mActive(false), mSourceThread(sourceThread)
3721{
3722
3723 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3724 if (mCblk != NULL) {
3725 mCblk->flags |= CBLK_DIRECTION_OUT;
3726 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3727 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3728 mOutBuffer.frameCount = 0;
3729 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003730 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3731 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3732 mCblk, mBuffer, mCblk->buffers,
3733 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003734 } else {
3735 LOGW("Error creating output track on thread %p", playbackThread);
3736 }
3737}
3738
3739AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3740{
3741 clearBufferQueue();
3742}
3743
3744status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3745{
3746 status_t status = Track::start();
3747 if (status != NO_ERROR) {
3748 return status;
3749 }
3750
3751 mActive = true;
3752 mRetryCount = 127;
3753 return status;
3754}
3755
3756void AudioFlinger::PlaybackThread::OutputTrack::stop()
3757{
3758 Track::stop();
3759 clearBufferQueue();
3760 mOutBuffer.frameCount = 0;
3761 mActive = false;
3762}
3763
3764bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3765{
3766 Buffer *pInBuffer;
3767 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003768 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 bool outputBufferFull = false;
3770 inBuffer.frameCount = frames;
3771 inBuffer.i16 = data;
3772
3773 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3774
3775 if (!mActive && frames != 0) {
3776 start();
3777 sp<ThreadBase> thread = mThread.promote();
3778 if (thread != 0) {
3779 MixerThread *mixerThread = (MixerThread *)thread.get();
3780 if (mCblk->frameCount > frames){
3781 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3782 uint32_t startFrames = (mCblk->frameCount - frames);
3783 pInBuffer = new Buffer;
3784 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3785 pInBuffer->frameCount = startFrames;
3786 pInBuffer->i16 = pInBuffer->mBuffer;
3787 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3788 mBufferQueue.add(pInBuffer);
3789 } else {
3790 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3791 }
3792 }
3793 }
3794 }
3795
3796 while (waitTimeLeftMs) {
3797 // First write pending buffers, then new data
3798 if (mBufferQueue.size()) {
3799 pInBuffer = mBufferQueue.itemAt(0);
3800 } else {
3801 pInBuffer = &inBuffer;
3802 }
3803
3804 if (pInBuffer->frameCount == 0) {
3805 break;
3806 }
3807
3808 if (mOutBuffer.frameCount == 0) {
3809 mOutBuffer.frameCount = pInBuffer->frameCount;
3810 nsecs_t startTime = systemTime();
3811 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3812 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3813 outputBufferFull = true;
3814 break;
3815 }
3816 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3817 if (waitTimeLeftMs >= waitTimeMs) {
3818 waitTimeLeftMs -= waitTimeMs;
3819 } else {
3820 waitTimeLeftMs = 0;
3821 }
3822 }
3823
3824 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3825 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3826 mCblk->stepUser(outFrames);
3827 pInBuffer->frameCount -= outFrames;
3828 pInBuffer->i16 += outFrames * channelCount;
3829 mOutBuffer.frameCount -= outFrames;
3830 mOutBuffer.i16 += outFrames * channelCount;
3831
3832 if (pInBuffer->frameCount == 0) {
3833 if (mBufferQueue.size()) {
3834 mBufferQueue.removeAt(0);
3835 delete [] pInBuffer->mBuffer;
3836 delete pInBuffer;
3837 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3838 } else {
3839 break;
3840 }
3841 }
3842 }
3843
3844 // If we could not write all frames, allocate a buffer and queue it for next time.
3845 if (inBuffer.frameCount) {
3846 sp<ThreadBase> thread = mThread.promote();
3847 if (thread != 0 && !thread->standby()) {
3848 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3849 pInBuffer = new Buffer;
3850 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3851 pInBuffer->frameCount = inBuffer.frameCount;
3852 pInBuffer->i16 = pInBuffer->mBuffer;
3853 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3854 mBufferQueue.add(pInBuffer);
3855 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3856 } else {
3857 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3858 }
3859 }
3860 }
3861
3862 // Calling write() with a 0 length buffer, means that no more data will be written:
3863 // If no more buffers are pending, fill output track buffer to make sure it is started
3864 // by output mixer.
3865 if (frames == 0 && mBufferQueue.size() == 0) {
3866 if (mCblk->user < mCblk->frameCount) {
3867 frames = mCblk->frameCount - mCblk->user;
3868 pInBuffer = new Buffer;
3869 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3870 pInBuffer->frameCount = frames;
3871 pInBuffer->i16 = pInBuffer->mBuffer;
3872 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3873 mBufferQueue.add(pInBuffer);
3874 } else if (mActive) {
3875 stop();
3876 }
3877 }
3878
3879 return outputBufferFull;
3880}
3881
3882status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3883{
3884 int active;
3885 status_t result;
3886 audio_track_cblk_t* cblk = mCblk;
3887 uint32_t framesReq = buffer->frameCount;
3888
3889// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3890 buffer->frameCount = 0;
3891
3892 uint32_t framesAvail = cblk->framesAvailable();
3893
3894
3895 if (framesAvail == 0) {
3896 Mutex::Autolock _l(cblk->lock);
3897 goto start_loop_here;
3898 while (framesAvail == 0) {
3899 active = mActive;
3900 if (UNLIKELY(!active)) {
3901 LOGV("Not active and NO_MORE_BUFFERS");
3902 return AudioTrack::NO_MORE_BUFFERS;
3903 }
3904 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3905 if (result != NO_ERROR) {
3906 return AudioTrack::NO_MORE_BUFFERS;
3907 }
3908 // read the server count again
3909 start_loop_here:
3910 framesAvail = cblk->framesAvailable_l();
3911 }
3912 }
3913
3914// if (framesAvail < framesReq) {
3915// return AudioTrack::NO_MORE_BUFFERS;
3916// }
3917
3918 if (framesReq > framesAvail) {
3919 framesReq = framesAvail;
3920 }
3921
3922 uint32_t u = cblk->user;
3923 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3924
3925 if (u + framesReq > bufferEnd) {
3926 framesReq = bufferEnd - u;
3927 }
3928
3929 buffer->frameCount = framesReq;
3930 buffer->raw = (void *)cblk->buffer(u);
3931 return NO_ERROR;
3932}
3933
3934
3935void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3936{
3937 size_t size = mBufferQueue.size();
3938 Buffer *pBuffer;
3939
3940 for (size_t i = 0; i < size; i++) {
3941 pBuffer = mBufferQueue.itemAt(i);
3942 delete [] pBuffer->mBuffer;
3943 delete pBuffer;
3944 }
3945 mBufferQueue.clear();
3946}
3947
3948// ----------------------------------------------------------------------------
3949
3950AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3951 : RefBase(),
3952 mAudioFlinger(audioFlinger),
3953 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3954 mPid(pid)
3955{
3956 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3957}
3958
3959// Client destructor must be called with AudioFlinger::mLock held
3960AudioFlinger::Client::~Client()
3961{
3962 mAudioFlinger->removeClient_l(mPid);
3963}
3964
3965const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3966{
3967 return mMemoryDealer;
3968}
3969
3970// ----------------------------------------------------------------------------
3971
3972AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3973 const sp<IAudioFlingerClient>& client,
3974 pid_t pid)
3975 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3976{
3977}
3978
3979AudioFlinger::NotificationClient::~NotificationClient()
3980{
3981 mClient.clear();
3982}
3983
3984void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3985{
3986 sp<NotificationClient> keep(this);
3987 {
3988 mAudioFlinger->removeNotificationClient(mPid);
3989 }
3990}
3991
3992// ----------------------------------------------------------------------------
3993
3994AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3995 : BnAudioTrack(),
3996 mTrack(track)
3997{
3998}
3999
4000AudioFlinger::TrackHandle::~TrackHandle() {
4001 // just stop the track on deletion, associated resources
4002 // will be freed from the main thread once all pending buffers have
4003 // been played. Unless it's not in the active track list, in which
4004 // case we free everything now...
4005 mTrack->destroy();
4006}
4007
4008status_t AudioFlinger::TrackHandle::start() {
4009 return mTrack->start();
4010}
4011
4012void AudioFlinger::TrackHandle::stop() {
4013 mTrack->stop();
4014}
4015
4016void AudioFlinger::TrackHandle::flush() {
4017 mTrack->flush();
4018}
4019
4020void AudioFlinger::TrackHandle::mute(bool e) {
4021 mTrack->mute(e);
4022}
4023
4024void AudioFlinger::TrackHandle::pause() {
4025 mTrack->pause();
4026}
4027
4028void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4029 mTrack->setVolume(left, right);
4030}
4031
4032sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4033 return mTrack->getCblk();
4034}
4035
4036status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4037{
4038 return mTrack->attachAuxEffect(EffectId);
4039}
4040
4041status_t AudioFlinger::TrackHandle::onTransact(
4042 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4043{
4044 return BnAudioTrack::onTransact(code, data, reply, flags);
4045}
4046
4047// ----------------------------------------------------------------------------
4048
4049sp<IAudioRecord> AudioFlinger::openRecord(
4050 pid_t pid,
4051 int input,
4052 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004053 uint32_t format,
4054 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 int frameCount,
4056 uint32_t flags,
4057 int *sessionId,
4058 status_t *status)
4059{
4060 sp<RecordThread::RecordTrack> recordTrack;
4061 sp<RecordHandle> recordHandle;
4062 sp<Client> client;
4063 wp<Client> wclient;
4064 status_t lStatus;
4065 RecordThread *thread;
4066 size_t inFrameCount;
4067 int lSessionId;
4068
4069 // check calling permissions
4070 if (!recordingAllowed()) {
4071 lStatus = PERMISSION_DENIED;
4072 goto Exit;
4073 }
4074
4075 // add client to list
4076 { // scope for mLock
4077 Mutex::Autolock _l(mLock);
4078 thread = checkRecordThread_l(input);
4079 if (thread == NULL) {
4080 lStatus = BAD_VALUE;
4081 goto Exit;
4082 }
4083
4084 wclient = mClients.valueFor(pid);
4085 if (wclient != NULL) {
4086 client = wclient.promote();
4087 } else {
4088 client = new Client(this, pid);
4089 mClients.add(pid, client);
4090 }
4091
4092 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004093 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 lSessionId = *sessionId;
4095 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004096 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 if (sessionId != NULL) {
4098 *sessionId = lSessionId;
4099 }
4100 }
4101 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004102 recordTrack = thread->createRecordTrack_l(client,
4103 sampleRate,
4104 format,
4105 channelMask,
4106 frameCount,
4107 flags,
4108 lSessionId,
4109 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004111 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4113 // destructor is called by the TrackBase destructor with mLock held
4114 client.clear();
4115 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 goto Exit;
4117 }
4118
4119 // return to handle to client
4120 recordHandle = new RecordHandle(recordTrack);
4121 lStatus = NO_ERROR;
4122
4123Exit:
4124 if (status) {
4125 *status = lStatus;
4126 }
4127 return recordHandle;
4128}
4129
4130// ----------------------------------------------------------------------------
4131
4132AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4133 : BnAudioRecord(),
4134 mRecordTrack(recordTrack)
4135{
4136}
4137
4138AudioFlinger::RecordHandle::~RecordHandle() {
4139 stop();
4140}
4141
4142status_t AudioFlinger::RecordHandle::start() {
4143 LOGV("RecordHandle::start()");
4144 return mRecordTrack->start();
4145}
4146
4147void AudioFlinger::RecordHandle::stop() {
4148 LOGV("RecordHandle::stop()");
4149 mRecordTrack->stop();
4150}
4151
4152sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4153 return mRecordTrack->getCblk();
4154}
4155
4156status_t AudioFlinger::RecordHandle::onTransact(
4157 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4158{
4159 return BnAudioRecord::onTransact(code, data, reply, flags);
4160}
4161
4162// ----------------------------------------------------------------------------
4163
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004164AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4165 AudioStreamIn *input,
4166 uint32_t sampleRate,
4167 uint32_t channels,
4168 int id,
4169 uint32_t device) :
4170 ThreadBase(audioFlinger, id, device),
4171 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004173 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004174
4175 snprintf(mName, kNameLength, "AudioIn_%d", id);
4176
Dima Zavinfce7a472011-04-19 22:30:36 -07004177 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004178 mReqSampleRate = sampleRate;
4179 readInputParameters();
4180}
4181
4182
4183AudioFlinger::RecordThread::~RecordThread()
4184{
4185 delete[] mRsmpInBuffer;
4186 if (mResampler != 0) {
4187 delete mResampler;
4188 delete[] mRsmpOutBuffer;
4189 }
4190}
4191
4192void AudioFlinger::RecordThread::onFirstRef()
4193{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004194 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195}
4196
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004197status_t AudioFlinger::RecordThread::readyToRun()
4198{
4199 status_t status = initCheck();
4200 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4201 return status;
4202}
4203
Mathias Agopian65ab4712010-07-14 17:59:35 -07004204bool AudioFlinger::RecordThread::threadLoop()
4205{
4206 AudioBufferProvider::Buffer buffer;
4207 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004208 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004209
Eric Laurent44d98482010-09-30 16:12:31 -07004210 nsecs_t lastWarning = 0;
4211
Eric Laurentfeb0db62011-07-22 09:04:31 -07004212 acquireWakeLock();
4213
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 // start recording
4215 while (!exitPending()) {
4216
4217 processConfigEvents();
4218
4219 { // scope for mLock
4220 Mutex::Autolock _l(mLock);
4221 checkForNewParameters_l();
4222 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4223 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004224 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 mStandby = true;
4226 }
4227
4228 if (exitPending()) break;
4229
Eric Laurentfeb0db62011-07-22 09:04:31 -07004230 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 LOGV("RecordThread: loop stopping");
4232 // go to sleep
4233 mWaitWorkCV.wait(mLock);
4234 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004235 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004236 continue;
4237 }
4238 if (mActiveTrack != 0) {
4239 if (mActiveTrack->mState == TrackBase::PAUSING) {
4240 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004241 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242 mStandby = true;
4243 }
4244 mActiveTrack.clear();
4245 mStartStopCond.broadcast();
4246 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4247 if (mReqChannelCount != mActiveTrack->channelCount()) {
4248 mActiveTrack.clear();
4249 mStartStopCond.broadcast();
4250 } else if (mBytesRead != 0) {
4251 // record start succeeds only if first read from audio input
4252 // succeeds
4253 if (mBytesRead > 0) {
4254 mActiveTrack->mState = TrackBase::ACTIVE;
4255 } else {
4256 mActiveTrack.clear();
4257 }
4258 mStartStopCond.broadcast();
4259 }
4260 mStandby = false;
4261 }
4262 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004263 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 }
4265
4266 if (mActiveTrack != 0) {
4267 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4268 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004269 unlockEffectChains(effectChains);
4270 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271 continue;
4272 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004273 for (size_t i = 0; i < effectChains.size(); i ++) {
4274 effectChains[i]->process_l();
4275 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004276
Mathias Agopian65ab4712010-07-14 17:59:35 -07004277 buffer.frameCount = mFrameCount;
4278 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4279 size_t framesOut = buffer.frameCount;
4280 if (mResampler == 0) {
4281 // no resampling
4282 while (framesOut) {
4283 size_t framesIn = mFrameCount - mRsmpInIndex;
4284 if (framesIn) {
4285 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4286 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4287 if (framesIn > framesOut)
4288 framesIn = framesOut;
4289 mRsmpInIndex += framesIn;
4290 framesOut -= framesIn;
4291 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004292 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 memcpy(dst, src, framesIn * mFrameSize);
4294 } else {
4295 int16_t *src16 = (int16_t *)src;
4296 int16_t *dst16 = (int16_t *)dst;
4297 if (mChannelCount == 1) {
4298 while (framesIn--) {
4299 *dst16++ = *src16;
4300 *dst16++ = *src16++;
4301 }
4302 } else {
4303 while (framesIn--) {
4304 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4305 src16 += 2;
4306 }
4307 }
4308 }
4309 }
4310 if (framesOut && mFrameCount == mRsmpInIndex) {
4311 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004312 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004313 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 framesOut = 0;
4315 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004316 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004317 mRsmpInIndex = 0;
4318 }
4319 if (mBytesRead < 0) {
4320 LOGE("Error reading audio input");
4321 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4322 // Force input into standby so that it tries to
4323 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004324 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004325 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 }
4327 mRsmpInIndex = mFrameCount;
4328 framesOut = 0;
4329 buffer.frameCount = 0;
4330 }
4331 }
4332 }
4333 } else {
4334 // resampling
4335
4336 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4337 // alter output frame count as if we were expecting stereo samples
4338 if (mChannelCount == 1 && mReqChannelCount == 1) {
4339 framesOut >>= 1;
4340 }
4341 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4342 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4343 // are 32 bit aligned which should be always true.
4344 if (mChannelCount == 2 && mReqChannelCount == 1) {
4345 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4346 // the resampler always outputs stereo samples: do post stereo to mono conversion
4347 int16_t *src = (int16_t *)mRsmpOutBuffer;
4348 int16_t *dst = buffer.i16;
4349 while (framesOut--) {
4350 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4351 src += 2;
4352 }
4353 } else {
4354 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4355 }
4356
4357 }
4358 mActiveTrack->releaseBuffer(&buffer);
4359 mActiveTrack->overflow();
4360 }
4361 // client isn't retrieving buffers fast enough
4362 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004363 if (!mActiveTrack->setOverflow()) {
4364 nsecs_t now = systemTime();
4365 if ((now - lastWarning) > kWarningThrottle) {
4366 LOGW("RecordThread: buffer overflow");
4367 lastWarning = now;
4368 }
4369 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 // Release the processor for a while before asking for a new buffer.
4371 // This will give the application more chance to read from the buffer and
4372 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004373 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004374 }
4375 }
Eric Laurentec437d82011-07-26 20:54:46 -07004376 // enable changes in effect chain
4377 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004378 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 }
4380
4381 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004382 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004383 }
4384 mActiveTrack.clear();
4385
4386 mStartStopCond.broadcast();
4387
Eric Laurentfeb0db62011-07-22 09:04:31 -07004388 releaseWakeLock();
4389
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390 LOGV("RecordThread %p exiting", this);
4391 return false;
4392}
4393
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004394
4395sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4396 const sp<AudioFlinger::Client>& client,
4397 uint32_t sampleRate,
4398 int format,
4399 int channelMask,
4400 int frameCount,
4401 uint32_t flags,
4402 int sessionId,
4403 status_t *status)
4404{
4405 sp<RecordTrack> track;
4406 status_t lStatus;
4407
4408 lStatus = initCheck();
4409 if (lStatus != NO_ERROR) {
4410 LOGE("Audio driver not initialized.");
4411 goto Exit;
4412 }
4413
4414 { // scope for mLock
4415 Mutex::Autolock _l(mLock);
4416
4417 track = new RecordTrack(this, client, sampleRate,
4418 format, channelMask, frameCount, flags, sessionId);
4419
4420 if (track->getCblk() == NULL) {
4421 lStatus = NO_MEMORY;
4422 goto Exit;
4423 }
4424
4425 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004426 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4427 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004428 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004429 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4430 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004431 }
4432 lStatus = NO_ERROR;
4433
4434Exit:
4435 if (status) {
4436 *status = lStatus;
4437 }
4438 return track;
4439}
4440
Mathias Agopian65ab4712010-07-14 17:59:35 -07004441status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4442{
4443 LOGV("RecordThread::start");
4444 sp <ThreadBase> strongMe = this;
4445 status_t status = NO_ERROR;
4446 {
4447 AutoMutex lock(&mLock);
4448 if (mActiveTrack != 0) {
4449 if (recordTrack != mActiveTrack.get()) {
4450 status = -EBUSY;
4451 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4452 mActiveTrack->mState = TrackBase::ACTIVE;
4453 }
4454 return status;
4455 }
4456
4457 recordTrack->mState = TrackBase::IDLE;
4458 mActiveTrack = recordTrack;
4459 mLock.unlock();
4460 status_t status = AudioSystem::startInput(mId);
4461 mLock.lock();
4462 if (status != NO_ERROR) {
4463 mActiveTrack.clear();
4464 return status;
4465 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 mRsmpInIndex = mFrameCount;
4467 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004468 if (mResampler != NULL) {
4469 mResampler->reset();
4470 }
4471 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004472 // signal thread to start
4473 LOGV("Signal record thread");
4474 mWaitWorkCV.signal();
4475 // do not wait for mStartStopCond if exiting
4476 if (mExiting) {
4477 mActiveTrack.clear();
4478 status = INVALID_OPERATION;
4479 goto startError;
4480 }
4481 mStartStopCond.wait(mLock);
4482 if (mActiveTrack == 0) {
4483 LOGV("Record failed to start");
4484 status = BAD_VALUE;
4485 goto startError;
4486 }
4487 LOGV("Record started OK");
4488 return status;
4489 }
4490startError:
4491 AudioSystem::stopInput(mId);
4492 return status;
4493}
4494
4495void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4496 LOGV("RecordThread::stop");
4497 sp <ThreadBase> strongMe = this;
4498 {
4499 AutoMutex lock(&mLock);
4500 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4501 mActiveTrack->mState = TrackBase::PAUSING;
4502 // do not wait for mStartStopCond if exiting
4503 if (mExiting) {
4504 return;
4505 }
4506 mStartStopCond.wait(mLock);
4507 // if we have been restarted, recordTrack == mActiveTrack.get() here
4508 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4509 mLock.unlock();
4510 AudioSystem::stopInput(mId);
4511 mLock.lock();
4512 LOGV("Record stopped OK");
4513 }
4514 }
4515 }
4516}
4517
4518status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4519{
4520 const size_t SIZE = 256;
4521 char buffer[SIZE];
4522 String8 result;
4523 pid_t pid = 0;
4524
4525 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4526 result.append(buffer);
4527
4528 if (mActiveTrack != 0) {
4529 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004530 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 mActiveTrack->dump(buffer, SIZE);
4532 result.append(buffer);
4533
4534 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4535 result.append(buffer);
4536 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4537 result.append(buffer);
4538 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4539 result.append(buffer);
4540 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4541 result.append(buffer);
4542 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4543 result.append(buffer);
4544
4545
4546 } else {
4547 result.append("No record client\n");
4548 }
4549 write(fd, result.string(), result.size());
4550
4551 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004552 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553
4554 return NO_ERROR;
4555}
4556
4557status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4558{
4559 size_t framesReq = buffer->frameCount;
4560 size_t framesReady = mFrameCount - mRsmpInIndex;
4561 int channelCount;
4562
4563 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004564 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004565 if (mBytesRead < 0) {
4566 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4567 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4568 // Force input into standby so that it tries to
4569 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004570 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004571 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004572 }
4573 buffer->raw = 0;
4574 buffer->frameCount = 0;
4575 return NOT_ENOUGH_DATA;
4576 }
4577 mRsmpInIndex = 0;
4578 framesReady = mFrameCount;
4579 }
4580
4581 if (framesReq > framesReady) {
4582 framesReq = framesReady;
4583 }
4584
4585 if (mChannelCount == 1 && mReqChannelCount == 2) {
4586 channelCount = 1;
4587 } else {
4588 channelCount = 2;
4589 }
4590 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4591 buffer->frameCount = framesReq;
4592 return NO_ERROR;
4593}
4594
4595void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4596{
4597 mRsmpInIndex += buffer->frameCount;
4598 buffer->frameCount = 0;
4599}
4600
4601bool AudioFlinger::RecordThread::checkForNewParameters_l()
4602{
4603 bool reconfig = false;
4604
4605 while (!mNewParameters.isEmpty()) {
4606 status_t status = NO_ERROR;
4607 String8 keyValuePair = mNewParameters[0];
4608 AudioParameter param = AudioParameter(keyValuePair);
4609 int value;
4610 int reqFormat = mFormat;
4611 int reqSamplingRate = mReqSampleRate;
4612 int reqChannelCount = mReqChannelCount;
4613
4614 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4615 reqSamplingRate = value;
4616 reconfig = true;
4617 }
4618 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4619 reqFormat = value;
4620 reconfig = true;
4621 }
4622 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004623 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 reconfig = true;
4625 }
4626 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4627 // do not accept frame count changes if tracks are open as the track buffer
4628 // size depends on frame count and correct behavior would not be garantied
4629 // if frame count is changed after track creation
4630 if (mActiveTrack != 0) {
4631 status = INVALID_OPERATION;
4632 } else {
4633 reconfig = true;
4634 }
4635 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004636 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4637 // forward device change to effects that have requested to be
4638 // aware of attached audio device.
4639 for (size_t i = 0; i < mEffectChains.size(); i++) {
4640 mEffectChains[i]->setDevice_l(value);
4641 }
4642 // store input device and output device but do not forward output device to audio HAL.
4643 // Note that status is ignored by the caller for output device
4644 // (see AudioFlinger::setParameters()
4645 if (value & AUDIO_DEVICE_OUT_ALL) {
4646 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4647 status = BAD_VALUE;
4648 } else {
4649 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004650 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4651 if (mTrack != NULL) {
4652 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004653 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004654 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4655 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4656 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004657 }
4658 mDevice |= (uint32_t)value;
4659 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004660 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004661 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004662 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004663 mInput->stream->common.standby(&mInput->stream->common);
4664 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 }
4666 if (reconfig) {
4667 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004668 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004669 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004670 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4671 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004672 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673 status = NO_ERROR;
4674 }
4675 if (status == NO_ERROR) {
4676 readInputParameters();
4677 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4678 }
4679 }
4680 }
4681
4682 mNewParameters.removeAt(0);
4683
4684 mParamStatus = status;
4685 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004686 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4687 // already timed out waiting for the status and will never signal the condition.
4688 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 }
4690 return reconfig;
4691}
4692
4693String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4694{
Dima Zavinfce7a472011-04-19 22:30:36 -07004695 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004696 String8 out_s8 = String8();
4697
4698 Mutex::Autolock _l(mLock);
4699 if (initCheck() != NO_ERROR) {
4700 return out_s8;
4701 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004702
Dima Zavin799a70e2011-04-18 16:57:27 -07004703 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004704 out_s8 = String8(s);
4705 free(s);
4706 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707}
4708
4709void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4710 AudioSystem::OutputDescriptor desc;
4711 void *param2 = 0;
4712
4713 switch (event) {
4714 case AudioSystem::INPUT_OPENED:
4715 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004716 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717 desc.samplingRate = mSampleRate;
4718 desc.format = mFormat;
4719 desc.frameCount = mFrameCount;
4720 desc.latency = 0;
4721 param2 = &desc;
4722 break;
4723
4724 case AudioSystem::INPUT_CLOSED:
4725 default:
4726 break;
4727 }
4728 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4729}
4730
4731void AudioFlinger::RecordThread::readInputParameters()
4732{
4733 if (mRsmpInBuffer) delete mRsmpInBuffer;
4734 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4735 if (mResampler) delete mResampler;
4736 mResampler = 0;
4737
Dima Zavin799a70e2011-04-18 16:57:27 -07004738 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004739 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4740 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004741 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4742 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4743 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004744 mFrameCount = mInputBytes / mFrameSize;
4745 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4746
4747 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4748 {
4749 int channelCount;
4750 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4751 // stereo to mono post process as the resampler always outputs stereo.
4752 if (mChannelCount == 1 && mReqChannelCount == 2) {
4753 channelCount = 1;
4754 } else {
4755 channelCount = 2;
4756 }
4757 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4758 mResampler->setSampleRate(mSampleRate);
4759 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4760 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4761
4762 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4763 if (mChannelCount == 1 && mReqChannelCount == 1) {
4764 mFrameCount >>= 1;
4765 }
4766
4767 }
4768 mRsmpInIndex = mFrameCount;
4769}
4770
4771unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4772{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004773 Mutex::Autolock _l(mLock);
4774 if (initCheck() != NO_ERROR) {
4775 return 0;
4776 }
4777
Dima Zavin799a70e2011-04-18 16:57:27 -07004778 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779}
4780
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004781uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4782{
4783 Mutex::Autolock _l(mLock);
4784 uint32_t result = 0;
4785 if (getEffectChain_l(sessionId) != 0) {
4786 result = EFFECT_SESSION;
4787 }
4788
4789 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4790 result |= TRACK_SESSION;
4791 }
4792
4793 return result;
4794}
4795
Eric Laurent59bd0da2011-08-01 09:52:20 -07004796AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4797{
4798 Mutex::Autolock _l(mLock);
4799 return mTrack;
4800}
4801
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004802AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4803{
4804 Mutex::Autolock _l(mLock);
4805 return mInput;
4806}
4807
4808AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4809{
4810 Mutex::Autolock _l(mLock);
4811 AudioStreamIn *input = mInput;
4812 mInput = NULL;
4813 return input;
4814}
4815
4816// this method must always be called either with ThreadBase mLock held or inside the thread loop
4817audio_stream_t* AudioFlinger::RecordThread::stream()
4818{
4819 if (mInput == NULL) {
4820 return NULL;
4821 }
4822 return &mInput->stream->common;
4823}
4824
4825
Mathias Agopian65ab4712010-07-14 17:59:35 -07004826// ----------------------------------------------------------------------------
4827
4828int AudioFlinger::openOutput(uint32_t *pDevices,
4829 uint32_t *pSamplingRate,
4830 uint32_t *pFormat,
4831 uint32_t *pChannels,
4832 uint32_t *pLatencyMs,
4833 uint32_t flags)
4834{
4835 status_t status;
4836 PlaybackThread *thread = NULL;
4837 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4838 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4839 uint32_t format = pFormat ? *pFormat : 0;
4840 uint32_t channels = pChannels ? *pChannels : 0;
4841 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004842 audio_stream_out_t *outStream;
4843 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004844
4845 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4846 pDevices ? *pDevices : 0,
4847 samplingRate,
4848 format,
4849 channels,
4850 flags);
4851
4852 if (pDevices == NULL || *pDevices == 0) {
4853 return 0;
4854 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004855
Mathias Agopian65ab4712010-07-14 17:59:35 -07004856 Mutex::Autolock _l(mLock);
4857
Dima Zavin799a70e2011-04-18 16:57:27 -07004858 outHwDev = findSuitableHwDev_l(*pDevices);
4859 if (outHwDev == NULL)
4860 return 0;
4861
4862 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4863 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004865 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 samplingRate,
4867 format,
4868 channels,
4869 status);
4870
4871 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004872 if (outStream != NULL) {
4873 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004874 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004875
Dima Zavinfce7a472011-04-19 22:30:36 -07004876 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4877 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4878 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004879 thread = new DirectOutputThread(this, output, id, *pDevices);
4880 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4881 } else {
4882 thread = new MixerThread(this, output, id, *pDevices);
4883 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004884 }
4885 mPlaybackThreads.add(id, thread);
4886
4887 if (pSamplingRate) *pSamplingRate = samplingRate;
4888 if (pFormat) *pFormat = format;
4889 if (pChannels) *pChannels = channels;
4890 if (pLatencyMs) *pLatencyMs = thread->latency();
4891
4892 // notify client processes of the new output creation
4893 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4894 return id;
4895 }
4896
4897 return 0;
4898}
4899
4900int AudioFlinger::openDuplicateOutput(int output1, int output2)
4901{
4902 Mutex::Autolock _l(mLock);
4903 MixerThread *thread1 = checkMixerThread_l(output1);
4904 MixerThread *thread2 = checkMixerThread_l(output2);
4905
4906 if (thread1 == NULL || thread2 == NULL) {
4907 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4908 return 0;
4909 }
4910
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004911 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4913 thread->addOutputTrack(thread2);
4914 mPlaybackThreads.add(id, thread);
4915 // notify client processes of the new output creation
4916 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4917 return id;
4918}
4919
4920status_t AudioFlinger::closeOutput(int output)
4921{
4922 // keep strong reference on the playback thread so that
4923 // it is not destroyed while exit() is executed
4924 sp <PlaybackThread> thread;
4925 {
4926 Mutex::Autolock _l(mLock);
4927 thread = checkPlaybackThread_l(output);
4928 if (thread == NULL) {
4929 return BAD_VALUE;
4930 }
4931
4932 LOGV("closeOutput() %d", output);
4933
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004934 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004936 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004937 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4938 dupThread->removeOutputTrack((MixerThread *)thread.get());
4939 }
4940 }
4941 }
4942 void *param2 = 0;
4943 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4944 mPlaybackThreads.removeItem(output);
4945 }
4946 thread->exit();
4947
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004948 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004949 AudioStreamOut *out = thread->clearOutput();
4950 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07004951 out->hwDev->close_output_stream(out->hwDev, out->stream);
4952 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004953 }
4954 return NO_ERROR;
4955}
4956
4957status_t AudioFlinger::suspendOutput(int output)
4958{
4959 Mutex::Autolock _l(mLock);
4960 PlaybackThread *thread = checkPlaybackThread_l(output);
4961
4962 if (thread == NULL) {
4963 return BAD_VALUE;
4964 }
4965
4966 LOGV("suspendOutput() %d", output);
4967 thread->suspend();
4968
4969 return NO_ERROR;
4970}
4971
4972status_t AudioFlinger::restoreOutput(int output)
4973{
4974 Mutex::Autolock _l(mLock);
4975 PlaybackThread *thread = checkPlaybackThread_l(output);
4976
4977 if (thread == NULL) {
4978 return BAD_VALUE;
4979 }
4980
4981 LOGV("restoreOutput() %d", output);
4982
4983 thread->restore();
4984
4985 return NO_ERROR;
4986}
4987
4988int AudioFlinger::openInput(uint32_t *pDevices,
4989 uint32_t *pSamplingRate,
4990 uint32_t *pFormat,
4991 uint32_t *pChannels,
4992 uint32_t acoustics)
4993{
4994 status_t status;
4995 RecordThread *thread = NULL;
4996 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4997 uint32_t format = pFormat ? *pFormat : 0;
4998 uint32_t channels = pChannels ? *pChannels : 0;
4999 uint32_t reqSamplingRate = samplingRate;
5000 uint32_t reqFormat = format;
5001 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005002 audio_stream_in_t *inStream;
5003 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004
5005 if (pDevices == NULL || *pDevices == 0) {
5006 return 0;
5007 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005008
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 Mutex::Autolock _l(mLock);
5010
Dima Zavin799a70e2011-04-18 16:57:27 -07005011 inHwDev = findSuitableHwDev_l(*pDevices);
5012 if (inHwDev == NULL)
5013 return 0;
5014
5015 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5016 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005017 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005018 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005019 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005020 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 samplingRate,
5022 format,
5023 channels,
5024 acoustics,
5025 status);
5026
5027 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5028 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5029 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005030 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005031 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005033 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005035 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5036 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005037 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005038 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005039 }
5040
Dima Zavin799a70e2011-04-18 16:57:27 -07005041 if (inStream != NULL) {
5042 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5043
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005044 int id = nextUniqueId();
5045 // Start record thread
5046 // RecorThread require both input and output device indication to forward to audio
5047 // pre processing modules
5048 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5049 thread = new RecordThread(this,
5050 input,
5051 reqSamplingRate,
5052 reqChannels,
5053 id,
5054 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055 mRecordThreads.add(id, thread);
5056 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5057 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5058 if (pFormat) *pFormat = format;
5059 if (pChannels) *pChannels = reqChannels;
5060
Dima Zavin799a70e2011-04-18 16:57:27 -07005061 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062
5063 // notify client processes of the new input creation
5064 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5065 return id;
5066 }
5067
5068 return 0;
5069}
5070
5071status_t AudioFlinger::closeInput(int input)
5072{
5073 // keep strong reference on the record thread so that
5074 // it is not destroyed while exit() is executed
5075 sp <RecordThread> thread;
5076 {
5077 Mutex::Autolock _l(mLock);
5078 thread = checkRecordThread_l(input);
5079 if (thread == NULL) {
5080 return BAD_VALUE;
5081 }
5082
5083 LOGV("closeInput() %d", input);
5084 void *param2 = 0;
5085 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5086 mRecordThreads.removeItem(input);
5087 }
5088 thread->exit();
5089
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005090 AudioStreamIn *in = thread->clearInput();
5091 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005092 in->hwDev->close_input_stream(in->hwDev, in->stream);
5093 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094
5095 return NO_ERROR;
5096}
5097
5098status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5099{
5100 Mutex::Autolock _l(mLock);
5101 MixerThread *dstThread = checkMixerThread_l(output);
5102 if (dstThread == NULL) {
5103 LOGW("setStreamOutput() bad output id %d", output);
5104 return BAD_VALUE;
5105 }
5106
5107 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5108 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5109
Eric Laurent9f6530f2011-08-30 10:18:54 -07005110 dstThread->setStreamValid(stream, true);
5111
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5113 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5114 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005115 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005117 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005119 }
Eric Laurentde070132010-07-13 04:45:46 -07005120 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005121
5122 return NO_ERROR;
5123}
5124
5125
5126int AudioFlinger::newAudioSessionId()
5127{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005128 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005129}
5130
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005131void AudioFlinger::acquireAudioSessionId(int audioSession)
5132{
5133 Mutex::Autolock _l(mLock);
5134 int caller = IPCThreadState::self()->getCallingPid();
5135 LOGV("acquiring %d from %d", audioSession, caller);
5136 int num = mAudioSessionRefs.size();
5137 for (int i = 0; i< num; i++) {
5138 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5139 if (ref->sessionid == audioSession && ref->pid == caller) {
5140 ref->cnt++;
5141 LOGV(" incremented refcount to %d", ref->cnt);
5142 return;
5143 }
5144 }
5145 AudioSessionRef *ref = new AudioSessionRef();
5146 ref->sessionid = audioSession;
5147 ref->pid = caller;
5148 ref->cnt = 1;
5149 mAudioSessionRefs.push(ref);
5150 LOGV(" added new entry for %d", ref->sessionid);
5151}
5152
5153void AudioFlinger::releaseAudioSessionId(int audioSession)
5154{
5155 Mutex::Autolock _l(mLock);
5156 int caller = IPCThreadState::self()->getCallingPid();
5157 LOGV("releasing %d from %d", audioSession, caller);
5158 int num = mAudioSessionRefs.size();
5159 for (int i = 0; i< num; i++) {
5160 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5161 if (ref->sessionid == audioSession && ref->pid == caller) {
5162 ref->cnt--;
5163 LOGV(" decremented refcount to %d", ref->cnt);
5164 if (ref->cnt == 0) {
5165 mAudioSessionRefs.removeAt(i);
5166 delete ref;
5167 purgeStaleEffects_l();
5168 }
5169 return;
5170 }
5171 }
5172 LOGW("session id %d not found for pid %d", audioSession, caller);
5173}
5174
5175void AudioFlinger::purgeStaleEffects_l() {
5176
5177 LOGV("purging stale effects");
5178
5179 Vector< sp<EffectChain> > chains;
5180
5181 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5182 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5183 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5184 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005185 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5186 chains.push(ec);
5187 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005188 }
5189 }
5190 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5191 sp<RecordThread> t = mRecordThreads.valueAt(i);
5192 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5193 sp<EffectChain> ec = t->mEffectChains[j];
5194 chains.push(ec);
5195 }
5196 }
5197
5198 for (size_t i = 0; i < chains.size(); i++) {
5199 sp<EffectChain> ec = chains[i];
5200 int sessionid = ec->sessionId();
5201 sp<ThreadBase> t = ec->mThread.promote();
5202 if (t == 0) {
5203 continue;
5204 }
5205 size_t numsessionrefs = mAudioSessionRefs.size();
5206 bool found = false;
5207 for (size_t k = 0; k < numsessionrefs; k++) {
5208 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5209 if (ref->sessionid == sessionid) {
5210 LOGV(" session %d still exists for %d with %d refs",
5211 sessionid, ref->pid, ref->cnt);
5212 found = true;
5213 break;
5214 }
5215 }
5216 if (!found) {
5217 // remove all effects from the chain
5218 while (ec->mEffects.size()) {
5219 sp<EffectModule> effect = ec->mEffects[0];
5220 effect->unPin();
5221 Mutex::Autolock _l (t->mLock);
5222 t->removeEffect_l(effect);
5223 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5224 sp<EffectHandle> handle = effect->mHandles[j].promote();
5225 if (handle != 0) {
5226 handle->mEffect.clear();
5227 }
5228 }
5229 AudioSystem::unregisterEffect(effect->id());
5230 }
5231 }
5232 }
5233 return;
5234}
5235
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5237AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5238{
5239 PlaybackThread *thread = NULL;
5240 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5241 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5242 }
5243 return thread;
5244}
5245
5246// checkMixerThread_l() must be called with AudioFlinger::mLock held
5247AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5248{
5249 PlaybackThread *thread = checkPlaybackThread_l(output);
5250 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005251 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005252 thread = NULL;
5253 }
5254 }
5255 return (MixerThread *)thread;
5256}
5257
5258// checkRecordThread_l() must be called with AudioFlinger::mLock held
5259AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5260{
5261 RecordThread *thread = NULL;
5262 if (mRecordThreads.indexOfKey(input) >= 0) {
5263 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5264 }
5265 return thread;
5266}
5267
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005268uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005269{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005270 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005271}
5272
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005273AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5274{
5275 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5276 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005277 AudioStreamOut *output = thread->getOutput();
5278 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005279 return thread;
5280 }
5281 }
5282 return NULL;
5283}
5284
5285uint32_t AudioFlinger::primaryOutputDevice_l()
5286{
5287 PlaybackThread *thread = primaryPlaybackThread_l();
5288
5289 if (thread == NULL) {
5290 return 0;
5291 }
5292
5293 return thread->device();
5294}
5295
5296
Mathias Agopian65ab4712010-07-14 17:59:35 -07005297// ----------------------------------------------------------------------------
5298// Effect management
5299// ----------------------------------------------------------------------------
5300
5301
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5303{
5304 Mutex::Autolock _l(mLock);
5305 return EffectQueryNumberEffects(numEffects);
5306}
5307
5308status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5309{
5310 Mutex::Autolock _l(mLock);
5311 return EffectQueryEffect(index, descriptor);
5312}
5313
5314status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5315{
5316 Mutex::Autolock _l(mLock);
5317 return EffectGetDescriptor(pUuid, descriptor);
5318}
5319
5320
Mathias Agopian65ab4712010-07-14 17:59:35 -07005321sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5322 effect_descriptor_t *pDesc,
5323 const sp<IEffectClient>& effectClient,
5324 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005325 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 int sessionId,
5327 status_t *status,
5328 int *id,
5329 int *enabled)
5330{
5331 status_t lStatus = NO_ERROR;
5332 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005333 effect_descriptor_t desc;
5334 sp<Client> client;
5335 wp<Client> wclient;
5336
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005337 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5338 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339
5340 if (pDesc == NULL) {
5341 lStatus = BAD_VALUE;
5342 goto Exit;
5343 }
5344
Eric Laurent84e9a102010-09-23 16:10:16 -07005345 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005346 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005347 lStatus = PERMISSION_DENIED;
5348 goto Exit;
5349 }
5350
Dima Zavinfce7a472011-04-19 22:30:36 -07005351 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005352 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005353 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005354 lStatus = PERMISSION_DENIED;
5355 goto Exit;
5356 }
5357
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005358 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005359 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005360 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005361 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005362 lStatus = BAD_VALUE;
5363 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005364 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005365 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005366 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005367 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005368 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005369 }
5370 }
5371
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 {
5373 Mutex::Autolock _l(mLock);
5374
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375
5376 if (!EffectIsNullUuid(&pDesc->uuid)) {
5377 // if uuid is specified, request effect descriptor
5378 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5379 if (lStatus < 0) {
5380 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5381 goto Exit;
5382 }
5383 } else {
5384 // if uuid is not specified, look for an available implementation
5385 // of the required type in effect factory
5386 if (EffectIsNullUuid(&pDesc->type)) {
5387 LOGW("createEffect() no effect type");
5388 lStatus = BAD_VALUE;
5389 goto Exit;
5390 }
5391 uint32_t numEffects = 0;
5392 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005393 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 bool found = false;
5395
5396 lStatus = EffectQueryNumberEffects(&numEffects);
5397 if (lStatus < 0) {
5398 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5399 goto Exit;
5400 }
5401 for (uint32_t i = 0; i < numEffects; i++) {
5402 lStatus = EffectQueryEffect(i, &desc);
5403 if (lStatus < 0) {
5404 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5405 continue;
5406 }
5407 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5408 // If matching type found save effect descriptor. If the session is
5409 // 0 and the effect is not auxiliary, continue enumeration in case
5410 // an auxiliary version of this effect type is available
5411 found = true;
5412 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005413 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005414 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5415 break;
5416 }
5417 }
5418 }
5419 if (!found) {
5420 lStatus = BAD_VALUE;
5421 LOGW("createEffect() effect not found");
5422 goto Exit;
5423 }
5424 // For same effect type, chose auxiliary version over insert version if
5425 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005426 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005427 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5428 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5429 }
5430 }
5431
5432 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005433 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5435 lStatus = INVALID_OPERATION;
5436 goto Exit;
5437 }
5438
Eric Laurent59255e42011-07-27 19:49:51 -07005439 // check recording permission for visualizer
5440 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5441 !recordingAllowed()) {
5442 lStatus = PERMISSION_DENIED;
5443 goto Exit;
5444 }
5445
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 // return effect descriptor
5447 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5448
5449 // If output is not specified try to find a matching audio session ID in one of the
5450 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005451 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5452 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005453 // Note: io is never 0 when creating an effect on an input
5454 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005455 // look for the thread where the specified audio session is present
5456 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5457 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005458 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005459 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005460 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005461 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005462 if (io == 0) {
5463 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5464 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5465 io = mRecordThreads.keyAt(i);
5466 break;
5467 }
5468 }
5469 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005470 // If no output thread contains the requested session ID, default to
5471 // first output. The effect chain will be moved to the correct output
5472 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005473 if (io == 0 && mPlaybackThreads.size()) {
5474 io = mPlaybackThreads.keyAt(0);
5475 }
5476 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5477 }
5478 ThreadBase *thread = checkRecordThread_l(io);
5479 if (thread == NULL) {
5480 thread = checkPlaybackThread_l(io);
5481 if (thread == NULL) {
5482 LOGE("createEffect() unknown output thread");
5483 lStatus = BAD_VALUE;
5484 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005487
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 wclient = mClients.valueFor(pid);
5489
5490 if (wclient != NULL) {
5491 client = wclient.promote();
5492 } else {
5493 client = new Client(this, pid);
5494 mClients.add(pid, client);
5495 }
5496
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005497 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005498 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5499 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 if (handle != 0 && id != NULL) {
5501 *id = handle->id();
5502 }
5503 }
5504
5505Exit:
5506 if(status) {
5507 *status = lStatus;
5508 }
5509 return handle;
5510}
5511
Eric Laurent59255e42011-07-27 19:49:51 -07005512status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005513{
5514 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005515 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005516 Mutex::Autolock _l(mLock);
5517 if (srcOutput == dstOutput) {
5518 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5519 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 }
Eric Laurentde070132010-07-13 04:45:46 -07005521 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5522 if (srcThread == NULL) {
5523 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5524 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005525 }
Eric Laurentde070132010-07-13 04:45:46 -07005526 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5527 if (dstThread == NULL) {
5528 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5529 return BAD_VALUE;
5530 }
5531
5532 Mutex::Autolock _dl(dstThread->mLock);
5533 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005534 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005535
Mathias Agopian65ab4712010-07-14 17:59:35 -07005536 return NO_ERROR;
5537}
5538
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005539// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005540status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005541 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005542 AudioFlinger::PlaybackThread *dstThread,
5543 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005544{
5545 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005546 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005547
Eric Laurent59255e42011-07-27 19:49:51 -07005548 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005549 if (chain == 0) {
5550 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005551 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005552 return INVALID_OPERATION;
5553 }
5554
Eric Laurent39e94f82010-07-28 01:32:47 -07005555 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005556 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005557 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005558 // removed.
5559 srcThread->removeEffectChain_l(chain);
5560
5561 // transfer all effects one by one so that new effect chain is created on new thread with
5562 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005563 int dstOutput = dstThread->id();
5564 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005565 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005566 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5567 while (effect != 0) {
5568 srcThread->removeEffect_l(effect);
5569 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005570 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5571 if (effect->state() == EffectModule::ACTIVE ||
5572 effect->state() == EffectModule::STOPPING) {
5573 effect->start();
5574 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005575 // if the move request is not received from audio policy manager, the effect must be
5576 // re-registered with the new strategy and output
5577 if (dstChain == 0) {
5578 dstChain = effect->chain().promote();
5579 if (dstChain == 0) {
5580 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5581 srcThread->addEffect_l(effect);
5582 return NO_INIT;
5583 }
5584 strategy = dstChain->strategy();
5585 }
5586 if (reRegister) {
5587 AudioSystem::unregisterEffect(effect->id());
5588 AudioSystem::registerEffect(&effect->desc(),
5589 dstOutput,
5590 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005591 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005592 effect->id());
5593 }
Eric Laurentde070132010-07-13 04:45:46 -07005594 effect = chain->getEffectFromId_l(0);
5595 }
5596
5597 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598}
5599
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005600
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005602sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005603 const sp<AudioFlinger::Client>& client,
5604 const sp<IEffectClient>& effectClient,
5605 int32_t priority,
5606 int sessionId,
5607 effect_descriptor_t *desc,
5608 int *enabled,
5609 status_t *status
5610 )
5611{
5612 sp<EffectModule> effect;
5613 sp<EffectHandle> handle;
5614 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005615 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005616 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 bool effectCreated = false;
5618 bool effectRegistered = false;
5619
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005620 lStatus = initCheck();
5621 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005623 goto Exit;
5624 }
5625
5626 // Do not allow effects with session ID 0 on direct output or duplicating threads
5627 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005628 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005629 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5630 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631 lStatus = BAD_VALUE;
5632 goto Exit;
5633 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005634 // Only Pre processor effects are allowed on input threads and only on input threads
5635 if ((mType == RECORD &&
5636 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5637 (mType != RECORD &&
5638 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5639 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5640 desc->name, desc->flags, mType);
5641 lStatus = BAD_VALUE;
5642 goto Exit;
5643 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644
5645 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5646
5647 { // scope for mLock
5648 Mutex::Autolock _l(mLock);
5649
5650 // check for existing effect chain with the requested audio session
5651 chain = getEffectChain_l(sessionId);
5652 if (chain == 0) {
5653 // create a new chain for this session
5654 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5655 chain = new EffectChain(this, sessionId);
5656 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005657 chain->setStrategy(getStrategyForSession_l(sessionId));
5658 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005660 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 }
5662
5663 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5664
5665 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005666 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005668 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 if (lStatus != NO_ERROR) {
5670 goto Exit;
5671 }
5672 effectRegistered = true;
5673 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005674 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005675 lStatus = effect->status();
5676 if (lStatus != NO_ERROR) {
5677 goto Exit;
5678 }
Eric Laurentcab11242010-07-15 12:50:15 -07005679 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 if (lStatus != NO_ERROR) {
5681 goto Exit;
5682 }
5683 effectCreated = true;
5684
5685 effect->setDevice(mDevice);
5686 effect->setMode(mAudioFlinger->getMode());
5687 }
5688 // create effect handle and connect it to effect module
5689 handle = new EffectHandle(effect, client, effectClient, priority);
5690 lStatus = effect->addHandle(handle);
5691 if (enabled) {
5692 *enabled = (int)effect->isEnabled();
5693 }
5694 }
5695
5696Exit:
5697 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005698 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005699 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005700 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 }
5702 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005703 AudioSystem::unregisterEffect(effect->id());
5704 }
5705 if (chainCreated) {
5706 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 }
5708 handle.clear();
5709 }
5710
5711 if(status) {
5712 *status = lStatus;
5713 }
5714 return handle;
5715}
5716
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005717sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5718{
5719 sp<EffectModule> effect;
5720
5721 sp<EffectChain> chain = getEffectChain_l(sessionId);
5722 if (chain != 0) {
5723 effect = chain->getEffectFromId_l(effectId);
5724 }
5725 return effect;
5726}
5727
Eric Laurentde070132010-07-13 04:45:46 -07005728// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5729// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005730status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005731{
5732 // check for existing effect chain with the requested audio session
5733 int sessionId = effect->sessionId();
5734 sp<EffectChain> chain = getEffectChain_l(sessionId);
5735 bool chainCreated = false;
5736
5737 if (chain == 0) {
5738 // create a new chain for this session
5739 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5740 chain = new EffectChain(this, sessionId);
5741 addEffectChain_l(chain);
5742 chain->setStrategy(getStrategyForSession_l(sessionId));
5743 chainCreated = true;
5744 }
5745 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5746
5747 if (chain->getEffectFromId_l(effect->id()) != 0) {
5748 LOGW("addEffect_l() %p effect %s already present in chain %p",
5749 this, effect->desc().name, chain.get());
5750 return BAD_VALUE;
5751 }
5752
5753 status_t status = chain->addEffect_l(effect);
5754 if (status != NO_ERROR) {
5755 if (chainCreated) {
5756 removeEffectChain_l(chain);
5757 }
5758 return status;
5759 }
5760
5761 effect->setDevice(mDevice);
5762 effect->setMode(mAudioFlinger->getMode());
5763 return NO_ERROR;
5764}
5765
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005766void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005767
5768 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005770 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5771 detachAuxEffect_l(effect->id());
5772 }
5773
5774 sp<EffectChain> chain = effect->chain().promote();
5775 if (chain != 0) {
5776 // remove effect chain if removing last effect
5777 if (chain->removeEffect_l(effect) == 0) {
5778 removeEffectChain_l(chain);
5779 }
5780 } else {
5781 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5782 }
5783}
5784
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005785void AudioFlinger::ThreadBase::lockEffectChains_l(
5786 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5787{
5788 effectChains = mEffectChains;
5789 for (size_t i = 0; i < mEffectChains.size(); i++) {
5790 mEffectChains[i]->lock();
5791 }
5792}
5793
5794void AudioFlinger::ThreadBase::unlockEffectChains(
5795 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5796{
5797 for (size_t i = 0; i < effectChains.size(); i++) {
5798 effectChains[i]->unlock();
5799 }
5800}
5801
5802sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5803{
5804 Mutex::Autolock _l(mLock);
5805 return getEffectChain_l(sessionId);
5806}
5807
5808sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5809{
5810 sp<EffectChain> chain;
5811
5812 size_t size = mEffectChains.size();
5813 for (size_t i = 0; i < size; i++) {
5814 if (mEffectChains[i]->sessionId() == sessionId) {
5815 chain = mEffectChains[i];
5816 break;
5817 }
5818 }
5819 return chain;
5820}
5821
5822void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5823{
5824 Mutex::Autolock _l(mLock);
5825 size_t size = mEffectChains.size();
5826 for (size_t i = 0; i < size; i++) {
5827 mEffectChains[i]->setMode_l(mode);
5828 }
5829}
5830
5831void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005832 const wp<EffectHandle>& handle,
5833 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005834
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005836 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005837 // delete the effect module if removing last handle on it
5838 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005839 if (!effect->isPinned() || unpiniflast) {
5840 removeEffect_l(effect);
5841 AudioSystem::unregisterEffect(effect->id());
5842 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 }
5844}
5845
5846status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5847{
5848 int session = chain->sessionId();
5849 int16_t *buffer = mMixBuffer;
5850 bool ownsBuffer = false;
5851
5852 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5853 if (session > 0) {
5854 // Only one effect chain can be present in direct output thread and it uses
5855 // the mix buffer as input
5856 if (mType != DIRECT) {
5857 size_t numSamples = mFrameCount * mChannelCount;
5858 buffer = new int16_t[numSamples];
5859 memset(buffer, 0, numSamples * sizeof(int16_t));
5860 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5861 ownsBuffer = true;
5862 }
5863
5864 // Attach all tracks with same session ID to this chain.
5865 for (size_t i = 0; i < mTracks.size(); ++i) {
5866 sp<Track> track = mTracks[i];
5867 if (session == track->sessionId()) {
5868 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5869 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005870 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871 }
5872 }
5873
5874 // indicate all active tracks in the chain
5875 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5876 sp<Track> track = mActiveTracks[i].promote();
5877 if (track == 0) continue;
5878 if (session == track->sessionId()) {
5879 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005880 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 }
5882 }
5883 }
5884
5885 chain->setInBuffer(buffer, ownsBuffer);
5886 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005887 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005888 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005889 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5890 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005892 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5893 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005894 // Effect chain for other sessions are inserted at beginning of effect
5895 // chains list to be processed before output mix effects. Relative order between other
5896 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 size_t size = mEffectChains.size();
5898 size_t i = 0;
5899 for (i = 0; i < size; i++) {
5900 if (mEffectChains[i]->sessionId() < session) break;
5901 }
5902 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005903 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904
5905 return NO_ERROR;
5906}
5907
5908size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5909{
5910 int session = chain->sessionId();
5911
5912 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5913
5914 for (size_t i = 0; i < mEffectChains.size(); i++) {
5915 if (chain == mEffectChains[i]) {
5916 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005917 // detach all active tracks from the chain
5918 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5919 sp<Track> track = mActiveTracks[i].promote();
5920 if (track == 0) continue;
5921 if (session == track->sessionId()) {
5922 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5923 chain.get(), session);
5924 chain->decActiveTrackCnt();
5925 }
5926 }
5927
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 // detach all tracks with same session ID from this chain
5929 for (size_t i = 0; i < mTracks.size(); ++i) {
5930 sp<Track> track = mTracks[i];
5931 if (session == track->sessionId()) {
5932 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005933 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005934 }
5935 }
Eric Laurentde070132010-07-13 04:45:46 -07005936 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 }
5938 }
5939 return mEffectChains.size();
5940}
5941
Eric Laurentde070132010-07-13 04:45:46 -07005942status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5943 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944{
5945 Mutex::Autolock _l(mLock);
5946 return attachAuxEffect_l(track, EffectId);
5947}
5948
Eric Laurentde070132010-07-13 04:45:46 -07005949status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5950 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951{
5952 status_t status = NO_ERROR;
5953
5954 if (EffectId == 0) {
5955 track->setAuxBuffer(0, NULL);
5956 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005957 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5958 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959 if (effect != 0) {
5960 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5961 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5962 } else {
5963 status = INVALID_OPERATION;
5964 }
5965 } else {
5966 status = BAD_VALUE;
5967 }
5968 }
5969 return status;
5970}
5971
5972void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5973{
5974 for (size_t i = 0; i < mTracks.size(); ++i) {
5975 sp<Track> track = mTracks[i];
5976 if (track->auxEffectId() == effectId) {
5977 attachAuxEffect_l(track, 0);
5978 }
5979 }
5980}
5981
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005982status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5983{
5984 // only one chain per input thread
5985 if (mEffectChains.size() != 0) {
5986 return INVALID_OPERATION;
5987 }
5988 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5989
5990 chain->setInBuffer(NULL);
5991 chain->setOutBuffer(NULL);
5992
Eric Laurent59255e42011-07-27 19:49:51 -07005993 checkSuspendOnAddEffectChain_l(chain);
5994
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005995 mEffectChains.add(chain);
5996
5997 return NO_ERROR;
5998}
5999
6000size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6001{
6002 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6003 LOGW_IF(mEffectChains.size() != 1,
6004 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6005 chain.get(), mEffectChains.size(), this);
6006 if (mEffectChains.size() == 1) {
6007 mEffectChains.removeAt(0);
6008 }
6009 return 0;
6010}
6011
Mathias Agopian65ab4712010-07-14 17:59:35 -07006012// ----------------------------------------------------------------------------
6013// EffectModule implementation
6014// ----------------------------------------------------------------------------
6015
6016#undef LOG_TAG
6017#define LOG_TAG "AudioFlinger::EffectModule"
6018
6019AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6020 const wp<AudioFlinger::EffectChain>& chain,
6021 effect_descriptor_t *desc,
6022 int id,
6023 int sessionId)
6024 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006025 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026{
6027 LOGV("Constructor %p", this);
6028 int lStatus;
6029 sp<ThreadBase> thread = mThread.promote();
6030 if (thread == 0) {
6031 return;
6032 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033
6034 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6035
6036 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006037 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038
6039 if (mStatus != NO_ERROR) {
6040 return;
6041 }
6042 lStatus = init();
6043 if (lStatus < 0) {
6044 mStatus = lStatus;
6045 goto Error;
6046 }
6047
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006048 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6049 mPinned = true;
6050 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006051 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6052 return;
6053Error:
6054 EffectRelease(mEffectInterface);
6055 mEffectInterface = NULL;
6056 LOGV("Constructor Error %d", mStatus);
6057}
6058
6059AudioFlinger::EffectModule::~EffectModule()
6060{
6061 LOGV("Destructor %p", this);
6062 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006063 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6064 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6065 sp<ThreadBase> thread = mThread.promote();
6066 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006067 audio_stream_t *stream = thread->stream();
6068 if (stream != NULL) {
6069 stream->remove_audio_effect(stream, mEffectInterface);
6070 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006071 }
6072 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006073 // release effect engine
6074 EffectRelease(mEffectInterface);
6075 }
6076}
6077
6078status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6079{
6080 status_t status;
6081
6082 Mutex::Autolock _l(mLock);
6083 // First handle in mHandles has highest priority and controls the effect module
6084 int priority = handle->priority();
6085 size_t size = mHandles.size();
6086 sp<EffectHandle> h;
6087 size_t i;
6088 for (i = 0; i < size; i++) {
6089 h = mHandles[i].promote();
6090 if (h == 0) continue;
6091 if (h->priority() <= priority) break;
6092 }
6093 // if inserted in first place, move effect control from previous owner to this handle
6094 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006095 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006096 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006097 enabled = h->enabled();
6098 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099 }
Eric Laurent59255e42011-07-27 19:49:51 -07006100 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006101 status = NO_ERROR;
6102 } else {
6103 status = ALREADY_EXISTS;
6104 }
Eric Laurent59255e42011-07-27 19:49:51 -07006105 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 mHandles.insertAt(handle, i);
6107 return status;
6108}
6109
6110size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6111{
6112 Mutex::Autolock _l(mLock);
6113 size_t size = mHandles.size();
6114 size_t i;
6115 for (i = 0; i < size; i++) {
6116 if (mHandles[i] == handle) break;
6117 }
6118 if (i == size) {
6119 return size;
6120 }
Eric Laurent59255e42011-07-27 19:49:51 -07006121 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6122
6123 bool enabled = false;
6124 EffectHandle *hdl = handle.unsafe_get();
6125 if (hdl) {
6126 LOGV("removeHandle() unsafe_get OK");
6127 enabled = hdl->enabled();
6128 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 mHandles.removeAt(i);
6130 size = mHandles.size();
6131 // if removed from first place, move effect control from this handle to next in line
6132 if (i == 0 && size != 0) {
6133 sp<EffectHandle> h = mHandles[0].promote();
6134 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006135 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 }
6137 }
6138
Eric Laurentec437d82011-07-26 20:54:46 -07006139 // Prevent calls to process() and other functions on effect interface from now on.
6140 // The effect engine will be released by the destructor when the last strong reference on
6141 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006142 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006143 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006144 }
6145
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 return size;
6147}
6148
Eric Laurent59255e42011-07-27 19:49:51 -07006149sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6150{
6151 Mutex::Autolock _l(mLock);
6152 sp<EffectHandle> handle;
6153 if (mHandles.size() != 0) {
6154 handle = mHandles[0].promote();
6155 }
6156 return handle;
6157}
6158
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006159void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160{
Eric Laurent59255e42011-07-27 19:49:51 -07006161 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006162 // keep a strong reference on this EffectModule to avoid calling the
6163 // destructor before we exit
6164 sp<EffectModule> keep(this);
6165 {
6166 sp<ThreadBase> thread = mThread.promote();
6167 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006168 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 }
6170 }
6171}
6172
6173void AudioFlinger::EffectModule::updateState() {
6174 Mutex::Autolock _l(mLock);
6175
6176 switch (mState) {
6177 case RESTART:
6178 reset_l();
6179 // FALL THROUGH
6180
6181 case STARTING:
6182 // clear auxiliary effect input buffer for next accumulation
6183 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6184 memset(mConfig.inputCfg.buffer.raw,
6185 0,
6186 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6187 }
6188 start_l();
6189 mState = ACTIVE;
6190 break;
6191 case STOPPING:
6192 stop_l();
6193 mDisableWaitCnt = mMaxDisableWaitCnt;
6194 mState = STOPPED;
6195 break;
6196 case STOPPED:
6197 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6198 // turn off sequence.
6199 if (--mDisableWaitCnt == 0) {
6200 reset_l();
6201 mState = IDLE;
6202 }
6203 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006204 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 break;
6206 }
6207}
6208
6209void AudioFlinger::EffectModule::process()
6210{
6211 Mutex::Autolock _l(mLock);
6212
Eric Laurentec437d82011-07-26 20:54:46 -07006213 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 mConfig.inputCfg.buffer.raw == NULL ||
6215 mConfig.outputCfg.buffer.raw == NULL) {
6216 return;
6217 }
6218
Eric Laurent8f45bd72010-08-31 13:50:07 -07006219 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006220 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6221 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6222 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6223 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006224 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006225 }
6226
6227 // do the actual processing in the effect engine
6228 int ret = (*mEffectInterface)->process(mEffectInterface,
6229 &mConfig.inputCfg.buffer,
6230 &mConfig.outputCfg.buffer);
6231
6232 // force transition to IDLE state when engine is ready
6233 if (mState == STOPPED && ret == -ENODATA) {
6234 mDisableWaitCnt = 1;
6235 }
6236
6237 // clear auxiliary effect input buffer for next accumulation
6238 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006239 memset(mConfig.inputCfg.buffer.raw, 0,
6240 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 }
6242 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006243 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6244 // If an insert effect is idle and input buffer is different from output buffer,
6245 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006246 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006247 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006248 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6249 int16_t *in = mConfig.inputCfg.buffer.s16;
6250 int16_t *out = mConfig.outputCfg.buffer.s16;
6251 for (size_t i = 0; i < frameCnt; i++) {
6252 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 }
6255 }
6256}
6257
6258void AudioFlinger::EffectModule::reset_l()
6259{
6260 if (mEffectInterface == NULL) {
6261 return;
6262 }
6263 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6264}
6265
6266status_t AudioFlinger::EffectModule::configure()
6267{
6268 uint32_t channels;
6269 if (mEffectInterface == NULL) {
6270 return NO_INIT;
6271 }
6272
6273 sp<ThreadBase> thread = mThread.promote();
6274 if (thread == 0) {
6275 return DEAD_OBJECT;
6276 }
6277
6278 // TODO: handle configuration of effects replacing track process
6279 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006280 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006282 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006283 }
6284
6285 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006286 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 } else {
6288 mConfig.inputCfg.channels = channels;
6289 }
6290 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006291 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6292 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 mConfig.inputCfg.samplingRate = thread->sampleRate();
6294 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6295 mConfig.inputCfg.bufferProvider.cookie = NULL;
6296 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6297 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6298 mConfig.outputCfg.bufferProvider.cookie = NULL;
6299 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6300 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6301 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6302 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006303 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006304 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 // - in other sessions:
6306 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6307 // other effect: overwrites output buffer: input buffer == output buffer
6308 // Auxiliary effect:
6309 // accumulates in output buffer: input buffer != output buffer
6310 // Therefore: accumulate <=> input buffer != output buffer
6311 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6312 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6313 } else {
6314 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6315 }
6316 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6317 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6318 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6319 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6320
Eric Laurentde070132010-07-13 04:45:46 -07006321 LOGV("configure() %p thread %p buffer %p framecount %d",
6322 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6323
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006325 uint32_t size = sizeof(int);
6326 status_t status = (*mEffectInterface)->command(mEffectInterface,
6327 EFFECT_CMD_CONFIGURE,
6328 sizeof(effect_config_t),
6329 &mConfig,
6330 &size,
6331 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006332 if (status == 0) {
6333 status = cmdStatus;
6334 }
6335
6336 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6337 (1000 * mConfig.outputCfg.buffer.frameCount);
6338
6339 return status;
6340}
6341
6342status_t AudioFlinger::EffectModule::init()
6343{
6344 Mutex::Autolock _l(mLock);
6345 if (mEffectInterface == NULL) {
6346 return NO_INIT;
6347 }
6348 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006349 uint32_t size = sizeof(status_t);
6350 status_t status = (*mEffectInterface)->command(mEffectInterface,
6351 EFFECT_CMD_INIT,
6352 0,
6353 NULL,
6354 &size,
6355 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 if (status == 0) {
6357 status = cmdStatus;
6358 }
6359 return status;
6360}
6361
Eric Laurentec35a142011-10-05 17:42:25 -07006362status_t AudioFlinger::EffectModule::start()
6363{
6364 Mutex::Autolock _l(mLock);
6365 return start_l();
6366}
6367
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368status_t AudioFlinger::EffectModule::start_l()
6369{
6370 if (mEffectInterface == NULL) {
6371 return NO_INIT;
6372 }
6373 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006374 uint32_t size = sizeof(status_t);
6375 status_t status = (*mEffectInterface)->command(mEffectInterface,
6376 EFFECT_CMD_ENABLE,
6377 0,
6378 NULL,
6379 &size,
6380 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 if (status == 0) {
6382 status = cmdStatus;
6383 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006384 if (status == 0 &&
6385 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6386 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6387 sp<ThreadBase> thread = mThread.promote();
6388 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006389 audio_stream_t *stream = thread->stream();
6390 if (stream != NULL) {
6391 stream->add_audio_effect(stream, mEffectInterface);
6392 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006393 }
6394 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006395 return status;
6396}
6397
Eric Laurentec437d82011-07-26 20:54:46 -07006398status_t AudioFlinger::EffectModule::stop()
6399{
6400 Mutex::Autolock _l(mLock);
6401 return stop_l();
6402}
6403
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404status_t AudioFlinger::EffectModule::stop_l()
6405{
6406 if (mEffectInterface == NULL) {
6407 return NO_INIT;
6408 }
6409 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006410 uint32_t size = sizeof(status_t);
6411 status_t status = (*mEffectInterface)->command(mEffectInterface,
6412 EFFECT_CMD_DISABLE,
6413 0,
6414 NULL,
6415 &size,
6416 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 if (status == 0) {
6418 status = cmdStatus;
6419 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006420 if (status == 0 &&
6421 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6422 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6423 sp<ThreadBase> thread = mThread.promote();
6424 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006425 audio_stream_t *stream = thread->stream();
6426 if (stream != NULL) {
6427 stream->remove_audio_effect(stream, mEffectInterface);
6428 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006429 }
6430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431 return status;
6432}
6433
Eric Laurent25f43952010-07-28 05:40:18 -07006434status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6435 uint32_t cmdSize,
6436 void *pCmdData,
6437 uint32_t *replySize,
6438 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439{
6440 Mutex::Autolock _l(mLock);
6441// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6442
Eric Laurentec437d82011-07-26 20:54:46 -07006443 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006444 return NO_INIT;
6445 }
Eric Laurent25f43952010-07-28 05:40:18 -07006446 status_t status = (*mEffectInterface)->command(mEffectInterface,
6447 cmdCode,
6448 cmdSize,
6449 pCmdData,
6450 replySize,
6451 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006453 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 for (size_t i = 1; i < mHandles.size(); i++) {
6455 sp<EffectHandle> h = mHandles[i].promote();
6456 if (h != 0) {
6457 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6458 }
6459 }
6460 }
6461 return status;
6462}
6463
6464status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6465{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006466
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 Mutex::Autolock _l(mLock);
6468 LOGV("setEnabled %p enabled %d", this, enabled);
6469
6470 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006471 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6472 if (enabled && status != NO_ERROR) {
6473 return status;
6474 }
6475
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 switch (mState) {
6477 // going from disabled to enabled
6478 case IDLE:
6479 mState = STARTING;
6480 break;
6481 case STOPPED:
6482 mState = RESTART;
6483 break;
6484 case STOPPING:
6485 mState = ACTIVE;
6486 break;
6487
6488 // going from enabled to disabled
6489 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006490 mState = STOPPED;
6491 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 case STARTING:
6493 mState = IDLE;
6494 break;
6495 case ACTIVE:
6496 mState = STOPPING;
6497 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006498 case DESTROYED:
6499 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 }
6501 for (size_t i = 1; i < mHandles.size(); i++) {
6502 sp<EffectHandle> h = mHandles[i].promote();
6503 if (h != 0) {
6504 h->setEnabled(enabled);
6505 }
6506 }
6507 }
6508 return NO_ERROR;
6509}
6510
6511bool AudioFlinger::EffectModule::isEnabled()
6512{
6513 switch (mState) {
6514 case RESTART:
6515 case STARTING:
6516 case ACTIVE:
6517 return true;
6518 case IDLE:
6519 case STOPPING:
6520 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006521 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 default:
6523 return false;
6524 }
6525}
6526
Eric Laurent8f45bd72010-08-31 13:50:07 -07006527bool AudioFlinger::EffectModule::isProcessEnabled()
6528{
6529 switch (mState) {
6530 case RESTART:
6531 case ACTIVE:
6532 case STOPPING:
6533 case STOPPED:
6534 return true;
6535 case IDLE:
6536 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006537 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006538 default:
6539 return false;
6540 }
6541}
6542
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6544{
6545 Mutex::Autolock _l(mLock);
6546 status_t status = NO_ERROR;
6547
6548 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6549 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006550 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006551 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6552 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 status_t cmdStatus;
6554 uint32_t volume[2];
6555 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006556 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 volume[0] = *left;
6558 volume[1] = *right;
6559 if (controller) {
6560 pVolume = volume;
6561 }
Eric Laurent25f43952010-07-28 05:40:18 -07006562 status = (*mEffectInterface)->command(mEffectInterface,
6563 EFFECT_CMD_SET_VOLUME,
6564 size,
6565 volume,
6566 &size,
6567 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6569 *left = volume[0];
6570 *right = volume[1];
6571 }
6572 }
6573 return status;
6574}
6575
6576status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6577{
6578 Mutex::Autolock _l(mLock);
6579 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006580 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6581 // audio pre processing modules on RecordThread can receive both output and
6582 // input device indication in the same call
6583 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6584 if (dev) {
6585 status_t cmdStatus;
6586 uint32_t size = sizeof(status_t);
6587
6588 status = (*mEffectInterface)->command(mEffectInterface,
6589 EFFECT_CMD_SET_DEVICE,
6590 sizeof(uint32_t),
6591 &dev,
6592 &size,
6593 &cmdStatus);
6594 if (status == NO_ERROR) {
6595 status = cmdStatus;
6596 }
6597 }
6598 dev = device & AUDIO_DEVICE_IN_ALL;
6599 if (dev) {
6600 status_t cmdStatus;
6601 uint32_t size = sizeof(status_t);
6602
6603 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6604 EFFECT_CMD_SET_INPUT_DEVICE,
6605 sizeof(uint32_t),
6606 &dev,
6607 &size,
6608 &cmdStatus);
6609 if (status2 == NO_ERROR) {
6610 status2 = cmdStatus;
6611 }
6612 if (status == NO_ERROR) {
6613 status = status2;
6614 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006615 }
6616 }
6617 return status;
6618}
6619
6620status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6621{
6622 Mutex::Autolock _l(mLock);
6623 status_t status = NO_ERROR;
6624 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006626 uint32_t size = sizeof(status_t);
6627 status = (*mEffectInterface)->command(mEffectInterface,
6628 EFFECT_CMD_SET_AUDIO_MODE,
6629 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006630 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006631 &size,
6632 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006633 if (status == NO_ERROR) {
6634 status = cmdStatus;
6635 }
6636 }
6637 return status;
6638}
6639
Eric Laurent59255e42011-07-27 19:49:51 -07006640void AudioFlinger::EffectModule::setSuspended(bool suspended)
6641{
6642 Mutex::Autolock _l(mLock);
6643 mSuspended = suspended;
6644}
6645bool AudioFlinger::EffectModule::suspended()
6646{
6647 Mutex::Autolock _l(mLock);
6648 return mSuspended;
6649}
6650
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6652{
6653 const size_t SIZE = 256;
6654 char buffer[SIZE];
6655 String8 result;
6656
6657 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6658 result.append(buffer);
6659
6660 bool locked = tryLock(mLock);
6661 // failed to lock - AudioFlinger is probably deadlocked
6662 if (!locked) {
6663 result.append("\t\tCould not lock Fx mutex:\n");
6664 }
6665
6666 result.append("\t\tSession Status State Engine:\n");
6667 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6668 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6669 result.append(buffer);
6670
6671 result.append("\t\tDescriptor:\n");
6672 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6673 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6674 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6675 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6676 result.append(buffer);
6677 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6678 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6679 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6680 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6681 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006682 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006683 mDescriptor.apiVersion,
6684 mDescriptor.flags);
6685 result.append(buffer);
6686 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6687 mDescriptor.name);
6688 result.append(buffer);
6689 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6690 mDescriptor.implementor);
6691 result.append(buffer);
6692
6693 result.append("\t\t- Input configuration:\n");
6694 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6695 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6696 (uint32_t)mConfig.inputCfg.buffer.raw,
6697 mConfig.inputCfg.buffer.frameCount,
6698 mConfig.inputCfg.samplingRate,
6699 mConfig.inputCfg.channels,
6700 mConfig.inputCfg.format);
6701 result.append(buffer);
6702
6703 result.append("\t\t- Output configuration:\n");
6704 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6705 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6706 (uint32_t)mConfig.outputCfg.buffer.raw,
6707 mConfig.outputCfg.buffer.frameCount,
6708 mConfig.outputCfg.samplingRate,
6709 mConfig.outputCfg.channels,
6710 mConfig.outputCfg.format);
6711 result.append(buffer);
6712
6713 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6714 result.append(buffer);
6715 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6716 for (size_t i = 0; i < mHandles.size(); ++i) {
6717 sp<EffectHandle> handle = mHandles[i].promote();
6718 if (handle != 0) {
6719 handle->dump(buffer, SIZE);
6720 result.append(buffer);
6721 }
6722 }
6723
6724 result.append("\n");
6725
6726 write(fd, result.string(), result.length());
6727
6728 if (locked) {
6729 mLock.unlock();
6730 }
6731
6732 return NO_ERROR;
6733}
6734
6735// ----------------------------------------------------------------------------
6736// EffectHandle implementation
6737// ----------------------------------------------------------------------------
6738
6739#undef LOG_TAG
6740#define LOG_TAG "AudioFlinger::EffectHandle"
6741
6742AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6743 const sp<AudioFlinger::Client>& client,
6744 const sp<IEffectClient>& effectClient,
6745 int32_t priority)
6746 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006747 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006748 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006749{
6750 LOGV("constructor %p", this);
6751
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006752 if (client == 0) {
6753 return;
6754 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6756 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6757 if (mCblkMemory != 0) {
6758 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6759
6760 if (mCblk) {
6761 new(mCblk) effect_param_cblk_t();
6762 mBuffer = (uint8_t *)mCblk + bufOffset;
6763 }
6764 } else {
6765 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6766 return;
6767 }
6768}
6769
6770AudioFlinger::EffectHandle::~EffectHandle()
6771{
6772 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006773 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07006774 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775}
6776
6777status_t AudioFlinger::EffectHandle::enable()
6778{
Eric Laurent59255e42011-07-27 19:49:51 -07006779 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 if (!mHasControl) return INVALID_OPERATION;
6781 if (mEffect == 0) return DEAD_OBJECT;
6782
Eric Laurentdb7c0792011-08-10 10:37:50 -07006783 if (mEnabled) {
6784 return NO_ERROR;
6785 }
6786
Eric Laurent59255e42011-07-27 19:49:51 -07006787 mEnabled = true;
6788
6789 sp<ThreadBase> thread = mEffect->thread().promote();
6790 if (thread != 0) {
6791 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6792 }
6793
6794 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6795 if (mEffect->suspended()) {
6796 return NO_ERROR;
6797 }
6798
Eric Laurentdb7c0792011-08-10 10:37:50 -07006799 status_t status = mEffect->setEnabled(true);
6800 if (status != NO_ERROR) {
6801 if (thread != 0) {
6802 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6803 }
6804 mEnabled = false;
6805 }
6806 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006807}
6808
6809status_t AudioFlinger::EffectHandle::disable()
6810{
Eric Laurent59255e42011-07-27 19:49:51 -07006811 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006813 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814
Eric Laurentdb7c0792011-08-10 10:37:50 -07006815 if (!mEnabled) {
6816 return NO_ERROR;
6817 }
Eric Laurent59255e42011-07-27 19:49:51 -07006818 mEnabled = false;
6819
6820 if (mEffect->suspended()) {
6821 return NO_ERROR;
6822 }
6823
6824 status_t status = mEffect->setEnabled(false);
6825
6826 sp<ThreadBase> thread = mEffect->thread().promote();
6827 if (thread != 0) {
6828 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6829 }
6830
6831 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832}
6833
6834void AudioFlinger::EffectHandle::disconnect()
6835{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006836 disconnect(true);
6837}
6838
6839void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6840{
6841 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 if (mEffect == 0) {
6843 return;
6844 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006845 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006846
Eric Laurentdb7c0792011-08-10 10:37:50 -07006847 if (mEnabled) {
6848 sp<ThreadBase> thread = mEffect->thread().promote();
6849 if (thread != 0) {
6850 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6851 }
Eric Laurent59255e42011-07-27 19:49:51 -07006852 }
6853
Mathias Agopian65ab4712010-07-14 17:59:35 -07006854 // release sp on module => module destructor can be called now
6855 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006857 if (mCblk) {
6858 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6859 }
6860 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6862 mClient.clear();
6863 }
6864}
6865
Eric Laurent25f43952010-07-28 05:40:18 -07006866status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6867 uint32_t cmdSize,
6868 void *pCmdData,
6869 uint32_t *replySize,
6870 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871{
Eric Laurent25f43952010-07-28 05:40:18 -07006872// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6873// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006874
6875 // only get parameter command is permitted for applications not controlling the effect
6876 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6877 return INVALID_OPERATION;
6878 }
6879 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006880 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006881
6882 // handle commands that are not forwarded transparently to effect engine
6883 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6884 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6885 // no risk to block the whole media server process or mixer threads is we are stuck here
6886 Mutex::Autolock _l(mCblk->lock);
6887 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6888 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6889 mCblk->serverIndex = 0;
6890 mCblk->clientIndex = 0;
6891 return BAD_VALUE;
6892 }
6893 status_t status = NO_ERROR;
6894 while (mCblk->serverIndex < mCblk->clientIndex) {
6895 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006896 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006897 int *p = (int *)(mBuffer + mCblk->serverIndex);
6898 int size = *p++;
6899 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6900 LOGW("command(): invalid parameter block size");
6901 break;
6902 }
6903 effect_param_t *param = (effect_param_t *)p;
6904 if (param->psize == 0 || param->vsize == 0) {
6905 LOGW("command(): null parameter or value size");
6906 mCblk->serverIndex += size;
6907 continue;
6908 }
Eric Laurent25f43952010-07-28 05:40:18 -07006909 uint32_t psize = sizeof(effect_param_t) +
6910 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6911 param->vsize;
6912 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6913 psize,
6914 p,
6915 &rsize,
6916 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006917 // stop at first error encountered
6918 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006919 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006920 *(int *)pReplyData = reply;
6921 break;
6922 } else if (reply != NO_ERROR) {
6923 *(int *)pReplyData = reply;
6924 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925 }
6926 mCblk->serverIndex += size;
6927 }
6928 mCblk->serverIndex = 0;
6929 mCblk->clientIndex = 0;
6930 return status;
6931 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006932 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933 return enable();
6934 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006935 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936 return disable();
6937 }
6938
6939 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6940}
6941
6942sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6943 return mCblkMemory;
6944}
6945
Eric Laurent59255e42011-07-27 19:49:51 -07006946void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947{
6948 LOGV("setControl %p control %d", this, hasControl);
6949
6950 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006951 mEnabled = enabled;
6952
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 if (signal && mEffectClient != 0) {
6954 mEffectClient->controlStatusChanged(hasControl);
6955 }
6956}
6957
Eric Laurent25f43952010-07-28 05:40:18 -07006958void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6959 uint32_t cmdSize,
6960 void *pCmdData,
6961 uint32_t replySize,
6962 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963{
6964 if (mEffectClient != 0) {
6965 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6966 }
6967}
6968
6969
6970
6971void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6972{
6973 if (mEffectClient != 0) {
6974 mEffectClient->enableStatusChanged(enabled);
6975 }
6976}
6977
6978status_t AudioFlinger::EffectHandle::onTransact(
6979 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6980{
6981 return BnEffect::onTransact(code, data, reply, flags);
6982}
6983
6984
6985void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6986{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006987 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006988
6989 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6990 (mClient == NULL) ? getpid() : mClient->pid(),
6991 mPriority,
6992 mHasControl,
6993 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006994 mCblk ? mCblk->clientIndex : 0,
6995 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996 );
6997
6998 if (locked) {
6999 mCblk->lock.unlock();
7000 }
7001}
7002
7003#undef LOG_TAG
7004#define LOG_TAG "AudioFlinger::EffectChain"
7005
7006AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7007 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07007008 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
7009 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7010 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007011{
Dima Zavinfce7a472011-04-19 22:30:36 -07007012 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007013}
7014
7015AudioFlinger::EffectChain::~EffectChain()
7016{
7017 if (mOwnInBuffer) {
7018 delete mInBuffer;
7019 }
7020
7021}
7022
Eric Laurent59255e42011-07-27 19:49:51 -07007023// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007024sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
7026 sp<EffectModule> effect;
7027 size_t size = mEffects.size();
7028
7029 for (size_t i = 0; i < size; i++) {
7030 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7031 effect = mEffects[i];
7032 break;
7033 }
7034 }
7035 return effect;
7036}
7037
Eric Laurent59255e42011-07-27 19:49:51 -07007038// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007039sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007040{
7041 sp<EffectModule> effect;
7042 size_t size = mEffects.size();
7043
7044 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007045 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7046 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047 effect = mEffects[i];
7048 break;
7049 }
7050 }
7051 return effect;
7052}
7053
Eric Laurent59255e42011-07-27 19:49:51 -07007054// getEffectFromType_l() must be called with ThreadBase::mLock held
7055sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7056 const effect_uuid_t *type)
7057{
7058 sp<EffectModule> effect;
7059 size_t size = mEffects.size();
7060
7061 for (size_t i = 0; i < size; i++) {
7062 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7063 effect = mEffects[i];
7064 break;
7065 }
7066 }
7067 return effect;
7068}
7069
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070// Must be called with EffectChain::mLock locked
7071void AudioFlinger::EffectChain::process_l()
7072{
Eric Laurentdac69112010-09-28 14:09:57 -07007073 sp<ThreadBase> thread = mThread.promote();
7074 if (thread == 0) {
7075 LOGW("process_l(): cannot promote mixer thread");
7076 return;
7077 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007078 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7079 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07007080 bool tracksOnSession = false;
7081 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07007082 tracksOnSession = (trackCnt() != 0);
7083 }
7084
7085 // if no track is active, input buffer must be cleared here as the mixer process
7086 // will not do it
7087 if (tracksOnSession &&
7088 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007089 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07007090 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07007091 }
7092
Mathias Agopian65ab4712010-07-14 17:59:35 -07007093 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07007094 // do not process effect if no track is present in same audio session
7095 if (isGlobalSession || tracksOnSession) {
7096 for (size_t i = 0; i < size; i++) {
7097 mEffects[i]->process();
7098 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099 }
7100 for (size_t i = 0; i < size; i++) {
7101 mEffects[i]->updateState();
7102 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103}
7104
Eric Laurentcab11242010-07-15 12:50:15 -07007105// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007106status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107{
7108 effect_descriptor_t desc = effect->desc();
7109 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7110
7111 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007112 effect->setChain(this);
7113 sp<ThreadBase> thread = mThread.promote();
7114 if (thread == 0) {
7115 return NO_INIT;
7116 }
7117 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007118
7119 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7120 // Auxiliary effects are inserted at the beginning of mEffects vector as
7121 // they are processed first and accumulated in chain input buffer
7122 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007123
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 // the input buffer for auxiliary effect contains mono samples in
7125 // 32 bit format. This is to avoid saturation in AudoMixer
7126 // accumulation stage. Saturation is done in EffectModule::process() before
7127 // calling the process in effect engine
7128 size_t numSamples = thread->frameCount();
7129 int32_t *buffer = new int32_t[numSamples];
7130 memset(buffer, 0, numSamples * sizeof(int32_t));
7131 effect->setInBuffer((int16_t *)buffer);
7132 // auxiliary effects output samples to chain input buffer for further processing
7133 // by insert effects
7134 effect->setOutBuffer(mInBuffer);
7135 } else {
7136 // Insert effects are inserted at the end of mEffects vector as they are processed
7137 // after track and auxiliary effects.
7138 // Insert effect order as a function of indicated preference:
7139 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7140 // another effect is present
7141 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7142 // last effect claiming first position
7143 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7144 // first effect claiming last position
7145 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7146 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7147 // already present
7148
7149 int size = (int)mEffects.size();
7150 int idx_insert = size;
7151 int idx_insert_first = -1;
7152 int idx_insert_last = -1;
7153
7154 for (int i = 0; i < size; i++) {
7155 effect_descriptor_t d = mEffects[i]->desc();
7156 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7157 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7158 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7159 // check invalid effect chaining combinations
7160 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7161 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007162 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 return INVALID_OPERATION;
7164 }
7165 // remember position of first insert effect and by default
7166 // select this as insert position for new effect
7167 if (idx_insert == size) {
7168 idx_insert = i;
7169 }
7170 // remember position of last insert effect claiming
7171 // first position
7172 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7173 idx_insert_first = i;
7174 }
7175 // remember position of first insert effect claiming
7176 // last position
7177 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7178 idx_insert_last == -1) {
7179 idx_insert_last = i;
7180 }
7181 }
7182 }
7183
7184 // modify idx_insert from first position if needed
7185 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7186 if (idx_insert_last != -1) {
7187 idx_insert = idx_insert_last;
7188 } else {
7189 idx_insert = size;
7190 }
7191 } else {
7192 if (idx_insert_first != -1) {
7193 idx_insert = idx_insert_first + 1;
7194 }
7195 }
7196
7197 // always read samples from chain input buffer
7198 effect->setInBuffer(mInBuffer);
7199
7200 // if last effect in the chain, output samples to chain
7201 // output buffer, otherwise to chain input buffer
7202 if (idx_insert == size) {
7203 if (idx_insert != 0) {
7204 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7205 mEffects[idx_insert-1]->configure();
7206 }
7207 effect->setOutBuffer(mOutBuffer);
7208 } else {
7209 effect->setOutBuffer(mInBuffer);
7210 }
7211 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212
Eric Laurentcab11242010-07-15 12:50:15 -07007213 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214 }
7215 effect->configure();
7216 return NO_ERROR;
7217}
7218
Eric Laurentcab11242010-07-15 12:50:15 -07007219// removeEffect_l() must be called with PlaybackThread::mLock held
7220size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007221{
7222 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007223 int size = (int)mEffects.size();
7224 int i;
7225 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7226
7227 for (i = 0; i < size; i++) {
7228 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007229 // calling stop here will remove pre-processing effect from the audio HAL.
7230 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7231 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007232 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7233 mEffects[i]->state() == EffectModule::STOPPING) {
7234 mEffects[i]->stop();
7235 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007236 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7237 delete[] effect->inBuffer();
7238 } else {
7239 if (i == size - 1 && i != 0) {
7240 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7241 mEffects[i - 1]->configure();
7242 }
7243 }
7244 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007245 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246 break;
7247 }
7248 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007249
7250 return mEffects.size();
7251}
7252
Eric Laurentcab11242010-07-15 12:50:15 -07007253// setDevice_l() must be called with PlaybackThread::mLock held
7254void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255{
7256 size_t size = mEffects.size();
7257 for (size_t i = 0; i < size; i++) {
7258 mEffects[i]->setDevice(device);
7259 }
7260}
7261
Eric Laurentcab11242010-07-15 12:50:15 -07007262// setMode_l() must be called with PlaybackThread::mLock held
7263void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007264{
7265 size_t size = mEffects.size();
7266 for (size_t i = 0; i < size; i++) {
7267 mEffects[i]->setMode(mode);
7268 }
7269}
7270
Eric Laurentcab11242010-07-15 12:50:15 -07007271// setVolume_l() must be called with PlaybackThread::mLock held
7272bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273{
7274 uint32_t newLeft = *left;
7275 uint32_t newRight = *right;
7276 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007277 int ctrlIdx = -1;
7278 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279
Eric Laurentcab11242010-07-15 12:50:15 -07007280 // first update volume controller
7281 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007282 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007283 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7284 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007285 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007286 break;
7287 }
7288 }
7289
7290 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007291 if (hasControl) {
7292 *left = mNewLeftVolume;
7293 *right = mNewRightVolume;
7294 }
7295 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007296 }
7297
7298 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007299 mLeftVolume = newLeft;
7300 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007301
7302 // second get volume update from volume controller
7303 if (ctrlIdx >= 0) {
7304 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007305 mNewLeftVolume = newLeft;
7306 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 }
7308 // then indicate volume to all other effects in chain.
7309 // Pass altered volume to effects before volume controller
7310 // and requested volume to effects after controller
7311 uint32_t lVol = newLeft;
7312 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007313
Mathias Agopian65ab4712010-07-14 17:59:35 -07007314 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007315 if ((int)i == ctrlIdx) continue;
7316 // this also works for ctrlIdx == -1 when there is no volume controller
7317 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 lVol = *left;
7319 rVol = *right;
7320 }
7321 mEffects[i]->setVolume(&lVol, &rVol, false);
7322 }
7323 *left = newLeft;
7324 *right = newRight;
7325
7326 return hasControl;
7327}
7328
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7330{
7331 const size_t SIZE = 256;
7332 char buffer[SIZE];
7333 String8 result;
7334
7335 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7336 result.append(buffer);
7337
7338 bool locked = tryLock(mLock);
7339 // failed to lock - AudioFlinger is probably deadlocked
7340 if (!locked) {
7341 result.append("\tCould not lock mutex:\n");
7342 }
7343
Eric Laurentcab11242010-07-15 12:50:15 -07007344 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7345 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007346 mEffects.size(),
7347 (uint32_t)mInBuffer,
7348 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007349 mActiveTrackCnt);
7350 result.append(buffer);
7351 write(fd, result.string(), result.size());
7352
7353 for (size_t i = 0; i < mEffects.size(); ++i) {
7354 sp<EffectModule> effect = mEffects[i];
7355 if (effect != 0) {
7356 effect->dump(fd, args);
7357 }
7358 }
7359
7360 if (locked) {
7361 mLock.unlock();
7362 }
7363
7364 return NO_ERROR;
7365}
7366
Eric Laurent59255e42011-07-27 19:49:51 -07007367// must be called with ThreadBase::mLock held
7368void AudioFlinger::EffectChain::setEffectSuspended_l(
7369 const effect_uuid_t *type, bool suspend)
7370{
7371 sp<SuspendedEffectDesc> desc;
7372 // use effect type UUID timelow as key as there is no real risk of identical
7373 // timeLow fields among effect type UUIDs.
7374 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7375 if (suspend) {
7376 if (index >= 0) {
7377 desc = mSuspendedEffects.valueAt(index);
7378 } else {
7379 desc = new SuspendedEffectDesc();
7380 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7381 mSuspendedEffects.add(type->timeLow, desc);
7382 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7383 }
7384 if (desc->mRefCount++ == 0) {
7385 sp<EffectModule> effect = getEffectIfEnabled(type);
7386 if (effect != 0) {
7387 desc->mEffect = effect;
7388 effect->setSuspended(true);
7389 effect->setEnabled(false);
7390 }
7391 }
7392 } else {
7393 if (index < 0) {
7394 return;
7395 }
7396 desc = mSuspendedEffects.valueAt(index);
7397 if (desc->mRefCount <= 0) {
7398 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7399 desc->mRefCount = 1;
7400 }
7401 if (--desc->mRefCount == 0) {
7402 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7403 if (desc->mEffect != 0) {
7404 sp<EffectModule> effect = desc->mEffect.promote();
7405 if (effect != 0) {
7406 effect->setSuspended(false);
7407 sp<EffectHandle> handle = effect->controlHandle();
7408 if (handle != 0) {
7409 effect->setEnabled(handle->enabled());
7410 }
7411 }
7412 desc->mEffect.clear();
7413 }
7414 mSuspendedEffects.removeItemsAt(index);
7415 }
7416 }
7417}
7418
7419// must be called with ThreadBase::mLock held
7420void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7421{
7422 sp<SuspendedEffectDesc> desc;
7423
7424 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7425 if (suspend) {
7426 if (index >= 0) {
7427 desc = mSuspendedEffects.valueAt(index);
7428 } else {
7429 desc = new SuspendedEffectDesc();
7430 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7431 LOGV("setEffectSuspendedAll_l() add entry for 0");
7432 }
7433 if (desc->mRefCount++ == 0) {
7434 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7435 for (size_t i = 0; i < effects.size(); i++) {
7436 setEffectSuspended_l(&effects[i]->desc().type, true);
7437 }
7438 }
7439 } else {
7440 if (index < 0) {
7441 return;
7442 }
7443 desc = mSuspendedEffects.valueAt(index);
7444 if (desc->mRefCount <= 0) {
7445 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7446 desc->mRefCount = 1;
7447 }
7448 if (--desc->mRefCount == 0) {
7449 Vector<const effect_uuid_t *> types;
7450 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7451 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7452 continue;
7453 }
7454 types.add(&mSuspendedEffects.valueAt(i)->mType);
7455 }
7456 for (size_t i = 0; i < types.size(); i++) {
7457 setEffectSuspended_l(types[i], false);
7458 }
7459 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7460 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7461 }
7462 }
7463}
7464
Eric Laurent6bffdb82011-09-23 08:40:41 -07007465
7466// The volume effect is used for automated tests only
7467#ifndef OPENSL_ES_H_
7468static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7469 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7470const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7471#endif //OPENSL_ES_H_
7472
Eric Laurentdb7c0792011-08-10 10:37:50 -07007473bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7474{
7475 // auxiliary effects and visualizer are never suspended on output mix
7476 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7477 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007478 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7479 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007480 return false;
7481 }
7482 return true;
7483}
7484
Eric Laurent59255e42011-07-27 19:49:51 -07007485Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7486{
7487 Vector< sp<EffectModule> > effects;
7488 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007489 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007490 continue;
7491 }
7492 effects.add(mEffects[i]);
7493 }
7494 return effects;
7495}
7496
7497sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7498 const effect_uuid_t *type)
7499{
7500 sp<EffectModule> effect;
7501 effect = getEffectFromType_l(type);
7502 if (effect != 0 && !effect->isEnabled()) {
7503 effect.clear();
7504 }
7505 return effect;
7506}
7507
7508void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7509 bool enabled)
7510{
7511 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7512 if (enabled) {
7513 if (index < 0) {
7514 // if the effect is not suspend check if all effects are suspended
7515 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7516 if (index < 0) {
7517 return;
7518 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007519 if (!isEffectEligibleForSuspend(effect->desc())) {
7520 return;
7521 }
Eric Laurent59255e42011-07-27 19:49:51 -07007522 setEffectSuspended_l(&effect->desc().type, enabled);
7523 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007524 if (index < 0) {
7525 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7526 return;
7527 }
Eric Laurent59255e42011-07-27 19:49:51 -07007528 }
7529 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7530 effect->desc().type.timeLow);
7531 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7532 // if effect is requested to suspended but was not yet enabled, supend it now.
7533 if (desc->mEffect == 0) {
7534 desc->mEffect = effect;
7535 effect->setEnabled(false);
7536 effect->setSuspended(true);
7537 }
7538 } else {
7539 if (index < 0) {
7540 return;
7541 }
7542 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7543 effect->desc().type.timeLow);
7544 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7545 desc->mEffect.clear();
7546 effect->setSuspended(false);
7547 }
7548}
7549
Mathias Agopian65ab4712010-07-14 17:59:35 -07007550#undef LOG_TAG
7551#define LOG_TAG "AudioFlinger"
7552
7553// ----------------------------------------------------------------------------
7554
7555status_t AudioFlinger::onTransact(
7556 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7557{
7558 return BnAudioFlinger::onTransact(code, data, reply, flags);
7559}
7560
Mathias Agopian65ab4712010-07-14 17:59:35 -07007561}; // namespace android