blob: a58f64c3a9892f981a71f2146af8cbc41b220ca3 [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();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988}
989
990void AudioFlinger::ThreadBase::exit()
991{
992 // keep a strong ref on ourself so that we wont get
993 // destroyed in the middle of requestExitAndWait()
994 sp <ThreadBase> strongMe = this;
995
996 LOGV("ThreadBase::exit");
997 {
998 AutoMutex lock(&mLock);
999 mExiting = true;
1000 requestExit();
1001 mWaitWorkCV.signal();
1002 }
1003 requestExitAndWait();
1004}
1005
1006uint32_t AudioFlinger::ThreadBase::sampleRate() const
1007{
1008 return mSampleRate;
1009}
1010
1011int AudioFlinger::ThreadBase::channelCount() const
1012{
1013 return (int)mChannelCount;
1014}
1015
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001016uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001017{
1018 return mFormat;
1019}
1020
1021size_t AudioFlinger::ThreadBase::frameCount() const
1022{
1023 return mFrameCount;
1024}
1025
1026status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1027{
1028 status_t status;
1029
1030 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1031 Mutex::Autolock _l(mLock);
1032
1033 mNewParameters.add(keyValuePairs);
1034 mWaitWorkCV.signal();
1035 // wait condition with timeout in case the thread loop has exited
1036 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001037 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001038 status = mParamStatus;
1039 mWaitWorkCV.signal();
1040 } else {
1041 status = TIMED_OUT;
1042 }
1043 return status;
1044}
1045
1046void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1047{
1048 Mutex::Autolock _l(mLock);
1049 sendConfigEvent_l(event, param);
1050}
1051
1052// sendConfigEvent_l() must be called with ThreadBase::mLock held
1053void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1054{
1055 ConfigEvent *configEvent = new ConfigEvent();
1056 configEvent->mEvent = event;
1057 configEvent->mParam = param;
1058 mConfigEvents.add(configEvent);
1059 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1060 mWaitWorkCV.signal();
1061}
1062
1063void AudioFlinger::ThreadBase::processConfigEvents()
1064{
1065 mLock.lock();
1066 while(!mConfigEvents.isEmpty()) {
1067 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1068 ConfigEvent *configEvent = mConfigEvents[0];
1069 mConfigEvents.removeAt(0);
1070 // release mLock before locking AudioFlinger mLock: lock order is always
1071 // AudioFlinger then ThreadBase to avoid cross deadlock
1072 mLock.unlock();
1073 mAudioFlinger->mLock.lock();
1074 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1075 mAudioFlinger->mLock.unlock();
1076 delete configEvent;
1077 mLock.lock();
1078 }
1079 mLock.unlock();
1080}
1081
1082status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1083{
1084 const size_t SIZE = 256;
1085 char buffer[SIZE];
1086 String8 result;
1087
1088 bool locked = tryLock(mLock);
1089 if (!locked) {
1090 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1091 write(fd, buffer, strlen(buffer));
1092 }
1093
1094 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1095 result.append(buffer);
1096 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1097 result.append(buffer);
1098 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1101 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001102 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1103 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001104 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1105 result.append(buffer);
1106 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1107 result.append(buffer);
1108
1109 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1110 result.append(buffer);
1111 result.append(" Index Command");
1112 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1113 snprintf(buffer, SIZE, "\n %02d ", i);
1114 result.append(buffer);
1115 result.append(mNewParameters[i]);
1116 }
1117
1118 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1119 result.append(buffer);
1120 snprintf(buffer, SIZE, " Index event param\n");
1121 result.append(buffer);
1122 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1123 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1124 result.append(buffer);
1125 }
1126 result.append("\n");
1127
1128 write(fd, result.string(), result.size());
1129
1130 if (locked) {
1131 mLock.unlock();
1132 }
1133 return NO_ERROR;
1134}
1135
Eric Laurent1d2bff02011-07-24 17:49:51 -07001136status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1137{
1138 const size_t SIZE = 256;
1139 char buffer[SIZE];
1140 String8 result;
1141
1142 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1143 write(fd, buffer, strlen(buffer));
1144
1145 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1146 sp<EffectChain> chain = mEffectChains[i];
1147 if (chain != 0) {
1148 chain->dump(fd, args);
1149 }
1150 }
1151 return NO_ERROR;
1152}
1153
Eric Laurentfeb0db62011-07-22 09:04:31 -07001154void AudioFlinger::ThreadBase::acquireWakeLock()
1155{
1156 Mutex::Autolock _l(mLock);
1157 acquireWakeLock_l();
1158}
1159
1160void AudioFlinger::ThreadBase::acquireWakeLock_l()
1161{
1162 if (mPowerManager == 0) {
1163 // use checkService() to avoid blocking if power service is not up yet
1164 sp<IBinder> binder =
1165 defaultServiceManager()->checkService(String16("power"));
1166 if (binder == 0) {
1167 LOGW("Thread %s cannot connect to the power manager service", mName);
1168 } else {
1169 mPowerManager = interface_cast<IPowerManager>(binder);
1170 binder->linkToDeath(mDeathRecipient);
1171 }
1172 }
1173 if (mPowerManager != 0) {
1174 sp<IBinder> binder = new BBinder();
1175 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1176 binder,
1177 String16(mName));
1178 if (status == NO_ERROR) {
1179 mWakeLockToken = binder;
1180 }
1181 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1182 }
1183}
1184
1185void AudioFlinger::ThreadBase::releaseWakeLock()
1186{
1187 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001188 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001189}
1190
1191void AudioFlinger::ThreadBase::releaseWakeLock_l()
1192{
1193 if (mWakeLockToken != 0) {
1194 LOGV("releaseWakeLock_l() %s", mName);
1195 if (mPowerManager != 0) {
1196 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1197 }
1198 mWakeLockToken.clear();
1199 }
1200}
1201
1202void AudioFlinger::ThreadBase::clearPowerManager()
1203{
1204 Mutex::Autolock _l(mLock);
1205 releaseWakeLock_l();
1206 mPowerManager.clear();
1207}
1208
1209void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1210{
1211 sp<ThreadBase> thread = mThread.promote();
1212 if (thread != 0) {
1213 thread->clearPowerManager();
1214 }
1215 LOGW("power manager service died !!!");
1216}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001217
Eric Laurent59255e42011-07-27 19:49:51 -07001218void AudioFlinger::ThreadBase::setEffectSuspended(
1219 const effect_uuid_t *type, bool suspend, int sessionId)
1220{
1221 Mutex::Autolock _l(mLock);
1222 setEffectSuspended_l(type, suspend, sessionId);
1223}
1224
1225void AudioFlinger::ThreadBase::setEffectSuspended_l(
1226 const effect_uuid_t *type, bool suspend, int sessionId)
1227{
1228 sp<EffectChain> chain;
1229 chain = getEffectChain_l(sessionId);
1230 if (chain != 0) {
1231 if (type != NULL) {
1232 chain->setEffectSuspended_l(type, suspend);
1233 } else {
1234 chain->setEffectSuspendedAll_l(suspend);
1235 }
1236 }
1237
1238 updateSuspendedSessions_l(type, suspend, sessionId);
1239}
1240
1241void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1242{
1243 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1244 if (index < 0) {
1245 return;
1246 }
1247
1248 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1249 mSuspendedSessions.editValueAt(index);
1250
1251 for (size_t i = 0; i < sessionEffects.size(); i++) {
1252 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1253 for (int j = 0; j < desc->mRefCount; j++) {
1254 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1255 chain->setEffectSuspendedAll_l(true);
1256 } else {
1257 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1258 desc->mType.timeLow);
1259 chain->setEffectSuspended_l(&desc->mType, true);
1260 }
1261 }
1262 }
1263}
1264
Eric Laurent59255e42011-07-27 19:49:51 -07001265void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1266 bool suspend,
1267 int sessionId)
1268{
1269 int index = mSuspendedSessions.indexOfKey(sessionId);
1270
1271 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1272
1273 if (suspend) {
1274 if (index >= 0) {
1275 sessionEffects = mSuspendedSessions.editValueAt(index);
1276 } else {
1277 mSuspendedSessions.add(sessionId, sessionEffects);
1278 }
1279 } else {
1280 if (index < 0) {
1281 return;
1282 }
1283 sessionEffects = mSuspendedSessions.editValueAt(index);
1284 }
1285
1286
1287 int key = EffectChain::kKeyForSuspendAll;
1288 if (type != NULL) {
1289 key = type->timeLow;
1290 }
1291 index = sessionEffects.indexOfKey(key);
1292
1293 sp <SuspendedSessionDesc> desc;
1294 if (suspend) {
1295 if (index >= 0) {
1296 desc = sessionEffects.valueAt(index);
1297 } else {
1298 desc = new SuspendedSessionDesc();
1299 if (type != NULL) {
1300 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1301 }
1302 sessionEffects.add(key, desc);
1303 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1304 }
1305 desc->mRefCount++;
1306 } else {
1307 if (index < 0) {
1308 return;
1309 }
1310 desc = sessionEffects.valueAt(index);
1311 if (--desc->mRefCount == 0) {
1312 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1313 sessionEffects.removeItemsAt(index);
1314 if (sessionEffects.isEmpty()) {
1315 LOGV("updateSuspendedSessions_l() restore removing session %d",
1316 sessionId);
1317 mSuspendedSessions.removeItem(sessionId);
1318 }
1319 }
1320 }
1321 if (!sessionEffects.isEmpty()) {
1322 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1323 }
1324}
1325
1326void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1327 bool enabled,
1328 int sessionId)
1329{
1330 Mutex::Autolock _l(mLock);
1331
Eric Laurentdb7c0792011-08-10 10:37:50 -07001332 if (mType != RECORD) {
1333 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1334 // another session. This gives the priority to well behaved effect control panels
1335 // and applications not using global effects.
1336 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1337 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1338 }
1339 }
Eric Laurent59255e42011-07-27 19:49:51 -07001340
1341 sp<EffectChain> chain = getEffectChain_l(sessionId);
1342 if (chain != 0) {
1343 chain->checkSuspendOnEffectEnabled(effect, enabled);
1344 }
1345}
1346
Mathias Agopian65ab4712010-07-14 17:59:35 -07001347// ----------------------------------------------------------------------------
1348
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001349AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1350 AudioStreamOut* output,
1351 int id,
1352 uint32_t device)
1353 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001354 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001355 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001356{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001357 snprintf(mName, kNameLength, "AudioOut_%d", id);
1358
Mathias Agopian65ab4712010-07-14 17:59:35 -07001359 readOutputParameters();
1360
1361 mMasterVolume = mAudioFlinger->masterVolume();
1362 mMasterMute = mAudioFlinger->masterMute();
1363
Dima Zavinfce7a472011-04-19 22:30:36 -07001364 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1366 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001367 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368 }
1369}
1370
1371AudioFlinger::PlaybackThread::~PlaybackThread()
1372{
1373 delete [] mMixBuffer;
1374}
1375
1376status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1377{
1378 dumpInternals(fd, args);
1379 dumpTracks(fd, args);
1380 dumpEffectChains(fd, args);
1381 return NO_ERROR;
1382}
1383
1384status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1385{
1386 const size_t SIZE = 256;
1387 char buffer[SIZE];
1388 String8 result;
1389
1390 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1391 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001392 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 -07001393 for (size_t i = 0; i < mTracks.size(); ++i) {
1394 sp<Track> track = mTracks[i];
1395 if (track != 0) {
1396 track->dump(buffer, SIZE);
1397 result.append(buffer);
1398 }
1399 }
1400
1401 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1402 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001403 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 -07001404 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1405 wp<Track> wTrack = mActiveTracks[i];
1406 if (wTrack != 0) {
1407 sp<Track> track = wTrack.promote();
1408 if (track != 0) {
1409 track->dump(buffer, SIZE);
1410 result.append(buffer);
1411 }
1412 }
1413 }
1414 write(fd, result.string(), result.size());
1415 return NO_ERROR;
1416}
1417
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1419{
1420 const size_t SIZE = 256;
1421 char buffer[SIZE];
1422 String8 result;
1423
1424 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1425 result.append(buffer);
1426 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1427 result.append(buffer);
1428 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1429 result.append(buffer);
1430 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1431 result.append(buffer);
1432 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1433 result.append(buffer);
1434 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1435 result.append(buffer);
1436 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1437 result.append(buffer);
1438 write(fd, result.string(), result.size());
1439
1440 dumpBase(fd, args);
1441
1442 return NO_ERROR;
1443}
1444
1445// Thread virtuals
1446status_t AudioFlinger::PlaybackThread::readyToRun()
1447{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001448 status_t status = initCheck();
1449 if (status == NO_ERROR) {
1450 LOGI("AudioFlinger's thread %p ready to run", this);
1451 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001454 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001455}
1456
1457void AudioFlinger::PlaybackThread::onFirstRef()
1458{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001459 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460}
1461
1462// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1463sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1464 const sp<AudioFlinger::Client>& client,
1465 int streamType,
1466 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001467 uint32_t format,
1468 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 int frameCount,
1470 const sp<IMemory>& sharedBuffer,
1471 int sessionId,
1472 status_t *status)
1473{
1474 sp<Track> track;
1475 status_t lStatus;
1476
1477 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001478 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1479 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1480 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1481 "for output %p with format %d",
1482 sampleRate, format, channelMask, mOutput, mFormat);
1483 lStatus = BAD_VALUE;
1484 goto Exit;
1485 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486 }
1487 } else {
1488 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1489 if (sampleRate > mSampleRate*2) {
1490 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1491 lStatus = BAD_VALUE;
1492 goto Exit;
1493 }
1494 }
1495
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001496 lStatus = initCheck();
1497 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 goto Exit;
1500 }
1501
1502 { // scope for mLock
1503 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001504
1505 // all tracks in same audio session must share the same routing strategy otherwise
1506 // conflicts will happen when tracks are moved from one output to another by audio policy
1507 // manager
1508 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001509 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001510 for (size_t i = 0; i < mTracks.size(); ++i) {
1511 sp<Track> t = mTracks[i];
1512 if (t != 0) {
1513 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001514 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001515 lStatus = BAD_VALUE;
1516 goto Exit;
1517 }
1518 }
1519 }
1520
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001522 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 if (track->getCblk() == NULL || track->name() < 0) {
1524 lStatus = NO_MEMORY;
1525 goto Exit;
1526 }
1527 mTracks.add(track);
1528
1529 sp<EffectChain> chain = getEffectChain_l(sessionId);
1530 if (chain != 0) {
1531 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1532 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001533 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001534 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001535 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001536
1537 // invalidate track immediately if the stream type was moved to another thread since
1538 // createTrack() was called by the client process.
1539 if (!mStreamTypes[streamType].valid) {
1540 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1541 this, streamType);
1542 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1543 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 }
1545 lStatus = NO_ERROR;
1546
1547Exit:
1548 if(status) {
1549 *status = lStatus;
1550 }
1551 return track;
1552}
1553
1554uint32_t AudioFlinger::PlaybackThread::latency() const
1555{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001556 Mutex::Autolock _l(mLock);
1557 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001558 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001559 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 return 0;
1561 }
1562}
1563
1564status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1565{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 mMasterVolume = value;
1567 return NO_ERROR;
1568}
1569
1570status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1571{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001572 mMasterMute = muted;
1573 return NO_ERROR;
1574}
1575
1576float AudioFlinger::PlaybackThread::masterVolume() const
1577{
1578 return mMasterVolume;
1579}
1580
1581bool AudioFlinger::PlaybackThread::masterMute() const
1582{
1583 return mMasterMute;
1584}
1585
1586status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1587{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 mStreamTypes[stream].volume = value;
1589 return NO_ERROR;
1590}
1591
1592status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1593{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001594 mStreamTypes[stream].mute = muted;
1595 return NO_ERROR;
1596}
1597
1598float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1599{
1600 return mStreamTypes[stream].volume;
1601}
1602
1603bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1604{
1605 return mStreamTypes[stream].mute;
1606}
1607
Mathias Agopian65ab4712010-07-14 17:59:35 -07001608// addTrack_l() must be called with ThreadBase::mLock held
1609status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1610{
1611 status_t status = ALREADY_EXISTS;
1612
1613 // set retry count for buffer fill
1614 track->mRetryCount = kMaxTrackStartupRetries;
1615 if (mActiveTracks.indexOf(track) < 0) {
1616 // the track is newly added, make sure it fills up all its
1617 // buffers before playing. This is to ensure the client will
1618 // effectively get the latency it requested.
1619 track->mFillingUpStatus = Track::FS_FILLING;
1620 track->mResetDone = false;
1621 mActiveTracks.add(track);
1622 if (track->mainBuffer() != mMixBuffer) {
1623 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1624 if (chain != 0) {
1625 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001626 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001627 }
1628 }
1629
1630 status = NO_ERROR;
1631 }
1632
1633 LOGV("mWaitWorkCV.broadcast");
1634 mWaitWorkCV.broadcast();
1635
1636 return status;
1637}
1638
1639// destroyTrack_l() must be called with ThreadBase::mLock held
1640void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1641{
1642 track->mState = TrackBase::TERMINATED;
1643 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001644 removeTrack_l(track);
1645 }
1646}
1647
1648void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1649{
1650 mTracks.remove(track);
1651 deleteTrackName_l(track->name());
1652 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1653 if (chain != 0) {
1654 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 }
1656}
1657
1658String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1659{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001660 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001661 char *s;
1662
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001663 Mutex::Autolock _l(mLock);
1664 if (initCheck() != NO_ERROR) {
1665 return out_s8;
1666 }
1667
Dima Zavin799a70e2011-04-18 16:57:27 -07001668 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001669 out_s8 = String8(s);
1670 free(s);
1671 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001672}
1673
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001674// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1676 AudioSystem::OutputDescriptor desc;
1677 void *param2 = 0;
1678
1679 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1680
1681 switch (event) {
1682 case AudioSystem::OUTPUT_OPENED:
1683 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001684 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685 desc.samplingRate = mSampleRate;
1686 desc.format = mFormat;
1687 desc.frameCount = mFrameCount;
1688 desc.latency = latency();
1689 param2 = &desc;
1690 break;
1691
1692 case AudioSystem::STREAM_CONFIG_CHANGED:
1693 param2 = &param;
1694 case AudioSystem::OUTPUT_CLOSED:
1695 default:
1696 break;
1697 }
1698 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1699}
1700
1701void AudioFlinger::PlaybackThread::readOutputParameters()
1702{
Dima Zavin799a70e2011-04-18 16:57:27 -07001703 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001704 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1705 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001706 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1707 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1708 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709
1710 // FIXME - Current mixer implementation only supports stereo output: Always
1711 // Allocate a stereo buffer even if HW output is mono.
1712 if (mMixBuffer != NULL) delete[] mMixBuffer;
1713 mMixBuffer = new int16_t[mFrameCount * 2];
1714 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1715
Eric Laurentde070132010-07-13 04:45:46 -07001716 // force reconfiguration of effect chains and engines to take new buffer size and audio
1717 // parameters into account
1718 // Note that mLock is not held when readOutputParameters() is called from the constructor
1719 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1720 // matter.
1721 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1722 Vector< sp<EffectChain> > effectChains = mEffectChains;
1723 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001724 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726}
1727
1728status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1729{
1730 if (halFrames == 0 || dspFrames == 0) {
1731 return BAD_VALUE;
1732 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001733 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001734 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001735 return INVALID_OPERATION;
1736 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001737 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738
Dima Zavin799a70e2011-04-18 16:57:27 -07001739 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740}
1741
Eric Laurent39e94f82010-07-28 01:32:47 -07001742uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743{
1744 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001745 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001746 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001747 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001748 }
1749
1750 for (size_t i = 0; i < mTracks.size(); ++i) {
1751 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001752 if (sessionId == track->sessionId() &&
1753 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001754 result |= TRACK_SESSION;
1755 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 }
1757 }
1758
Eric Laurent39e94f82010-07-28 01:32:47 -07001759 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001760}
1761
Eric Laurentde070132010-07-13 04:45:46 -07001762uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1763{
Dima Zavinfce7a472011-04-19 22:30:36 -07001764 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001765 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001766 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1767 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001768 }
1769 for (size_t i = 0; i < mTracks.size(); i++) {
1770 sp<Track> track = mTracks[i];
1771 if (sessionId == track->sessionId() &&
1772 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001773 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001774 }
1775 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001776 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001777}
1778
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001780AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1781{
1782 Mutex::Autolock _l(mLock);
1783 return mOutput;
1784}
1785
1786AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1787{
1788 Mutex::Autolock _l(mLock);
1789 AudioStreamOut *output = mOutput;
1790 mOutput = NULL;
1791 return output;
1792}
1793
1794// this method must always be called either with ThreadBase mLock held or inside the thread loop
1795audio_stream_t* AudioFlinger::PlaybackThread::stream()
1796{
1797 if (mOutput == NULL) {
1798 return NULL;
1799 }
1800 return &mOutput->stream->common;
1801}
1802
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803// ----------------------------------------------------------------------------
1804
Dima Zavin799a70e2011-04-18 16:57:27 -07001805AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806 : PlaybackThread(audioFlinger, output, id, device),
1807 mAudioMixer(0)
1808{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001809 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1811
1812 // FIXME - Current mixer implementation only supports stereo output
1813 if (mChannelCount == 1) {
1814 LOGE("Invalid audio hardware channel count");
1815 }
1816}
1817
1818AudioFlinger::MixerThread::~MixerThread()
1819{
1820 delete mAudioMixer;
1821}
1822
1823bool AudioFlinger::MixerThread::threadLoop()
1824{
1825 Vector< sp<Track> > tracksToRemove;
1826 uint32_t mixerStatus = MIXER_IDLE;
1827 nsecs_t standbyTime = systemTime();
1828 size_t mixBufferSize = mFrameCount * mFrameSize;
1829 // FIXME: Relaxed timing because of a certain device that can't meet latency
1830 // Should be reduced to 2x after the vendor fixes the driver issue
1831 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1832 nsecs_t lastWarning = 0;
1833 bool longStandbyExit = false;
1834 uint32_t activeSleepTime = activeSleepTimeUs();
1835 uint32_t idleSleepTime = idleSleepTimeUs();
1836 uint32_t sleepTime = idleSleepTime;
1837 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001838#ifdef DEBUG_CPU_USAGE
1839 ThreadCpuUsage cpu;
1840 const CentralTendencyStatistics& stats = cpu.statistics();
1841#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842
Eric Laurentfeb0db62011-07-22 09:04:31 -07001843 acquireWakeLock();
1844
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 while (!exitPending())
1846 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001847#ifdef DEBUG_CPU_USAGE
1848 cpu.sampleAndEnable();
1849 unsigned n = stats.n();
1850 // cpu.elapsed() is expensive, so don't call it every loop
1851 if ((n & 127) == 1) {
1852 long long elapsed = cpu.elapsed();
1853 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1854 double perLoop = elapsed / (double) n;
1855 double perLoop100 = perLoop * 0.01;
1856 double mean = stats.mean();
1857 double stddev = stats.stddev();
1858 double minimum = stats.minimum();
1859 double maximum = stats.maximum();
1860 cpu.resetStatistics();
1861 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",
1862 elapsed * .000000001, n, perLoop * .000001,
1863 mean * .001,
1864 stddev * .001,
1865 minimum * .001,
1866 maximum * .001,
1867 mean / perLoop100,
1868 stddev / perLoop100,
1869 minimum / perLoop100,
1870 maximum / perLoop100);
1871 }
1872 }
1873#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001874 processConfigEvents();
1875
1876 mixerStatus = MIXER_IDLE;
1877 { // scope for mLock
1878
1879 Mutex::Autolock _l(mLock);
1880
1881 if (checkForNewParameters_l()) {
1882 mixBufferSize = mFrameCount * mFrameSize;
1883 // FIXME: Relaxed timing because of a certain device that can't meet latency
1884 // Should be reduced to 2x after the vendor fixes the driver issue
1885 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1886 activeSleepTime = activeSleepTimeUs();
1887 idleSleepTime = idleSleepTimeUs();
1888 }
1889
1890 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1891
1892 // put audio hardware into standby after short delay
1893 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1894 mSuspended) {
1895 if (!mStandby) {
1896 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001897 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 mStandby = true;
1899 mBytesWritten = 0;
1900 }
1901
1902 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1903 // we're about to wait, flush the binder command buffer
1904 IPCThreadState::self()->flushCommands();
1905
1906 if (exitPending()) break;
1907
Eric Laurentfeb0db62011-07-22 09:04:31 -07001908 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001909 // wait until we have something to do...
1910 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1911 mWaitWorkCV.wait(mLock);
1912 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001913 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001914
1915 if (mMasterMute == false) {
1916 char value[PROPERTY_VALUE_MAX];
1917 property_get("ro.audio.silent", value, "0");
1918 if (atoi(value)) {
1919 LOGD("Silence is golden");
1920 setMasterMute(true);
1921 }
1922 }
1923
1924 standbyTime = systemTime() + kStandbyTimeInNsecs;
1925 sleepTime = idleSleepTime;
1926 continue;
1927 }
1928 }
1929
1930 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1931
1932 // prevent any changes in effect chain list and in each effect chain
1933 // during mixing and effect process as the audio buffers could be deleted
1934 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001935 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 }
1937
1938 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1939 // mix buffers...
1940 mAudioMixer->process();
1941 sleepTime = 0;
1942 standbyTime = systemTime() + kStandbyTimeInNsecs;
1943 //TODO: delay standby when effects have a tail
1944 } else {
1945 // If no tracks are ready, sleep once for the duration of an output
1946 // buffer size, then write 0s to the output
1947 if (sleepTime == 0) {
1948 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1949 sleepTime = activeSleepTime;
1950 } else {
1951 sleepTime = idleSleepTime;
1952 }
1953 } else if (mBytesWritten != 0 ||
1954 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1955 memset (mMixBuffer, 0, mixBufferSize);
1956 sleepTime = 0;
1957 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1958 }
1959 // TODO add standby time extension fct of effect tail
1960 }
1961
1962 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001963 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001964 }
1965 // sleepTime == 0 means we must write to audio hardware
1966 if (sleepTime == 0) {
1967 for (size_t i = 0; i < effectChains.size(); i ++) {
1968 effectChains[i]->process_l();
1969 }
1970 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001971 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 mLastWriteTime = systemTime();
1973 mInWrite = true;
1974 mBytesWritten += mixBufferSize;
1975
Dima Zavin799a70e2011-04-18 16:57:27 -07001976 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001977 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1978 mNumWrites++;
1979 mInWrite = false;
1980 nsecs_t now = systemTime();
1981 nsecs_t delta = now - mLastWriteTime;
1982 if (delta > maxPeriod) {
1983 mNumDelayedWrites++;
1984 if ((now - lastWarning) > kWarningThrottle) {
1985 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1986 ns2ms(delta), mNumDelayedWrites, this);
1987 lastWarning = now;
1988 }
1989 if (mStandby) {
1990 longStandbyExit = true;
1991 }
1992 }
1993 mStandby = false;
1994 } else {
1995 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001996 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001997 usleep(sleepTime);
1998 }
1999
2000 // finally let go of all our tracks, without the lock held
2001 // since we can't guarantee the destructors won't acquire that
2002 // same lock.
2003 tracksToRemove.clear();
2004
2005 // Effect chains will be actually deleted here if they were removed from
2006 // mEffectChains list during mixing or effects processing
2007 effectChains.clear();
2008 }
2009
2010 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002011 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002012 }
2013
Eric Laurentfeb0db62011-07-22 09:04:31 -07002014 releaseWakeLock();
2015
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 LOGV("MixerThread %p exiting", this);
2017 return false;
2018}
2019
2020// prepareTracks_l() must be called with ThreadBase::mLock held
2021uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2022{
2023
2024 uint32_t mixerStatus = MIXER_IDLE;
2025 // find out which tracks need to be processed
2026 size_t count = activeTracks.size();
2027 size_t mixedTracks = 0;
2028 size_t tracksWithEffect = 0;
2029
2030 float masterVolume = mMasterVolume;
2031 bool masterMute = mMasterMute;
2032
Eric Laurent571d49c2010-08-11 05:20:11 -07002033 if (masterMute) {
2034 masterVolume = 0;
2035 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002037 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002039 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002040 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041 masterVolume = (float)((v + (1 << 23)) >> 24);
2042 chain.clear();
2043 }
2044
2045 for (size_t i=0 ; i<count ; i++) {
2046 sp<Track> t = activeTracks[i].promote();
2047 if (t == 0) continue;
2048
2049 Track* const track = t.get();
2050 audio_track_cblk_t* cblk = track->cblk();
2051
2052 // The first time a track is added we wait
2053 // for all its buffers to be filled before processing it
2054 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07002055 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056 !track->isPaused() && !track->isTerminated())
2057 {
2058 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2059
2060 mixedTracks++;
2061
2062 // track->mainBuffer() != mMixBuffer means there is an effect chain
2063 // connected to the track
2064 chain.clear();
2065 if (track->mainBuffer() != mMixBuffer) {
2066 chain = getEffectChain_l(track->sessionId());
2067 // Delegate volume control to effect in track effect chain if needed
2068 if (chain != 0) {
2069 tracksWithEffect++;
2070 } else {
2071 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2072 track->name(), track->sessionId());
2073 }
2074 }
2075
2076
2077 int param = AudioMixer::VOLUME;
2078 if (track->mFillingUpStatus == Track::FS_FILLED) {
2079 // no ramp for the first volume setting
2080 track->mFillingUpStatus = Track::FS_ACTIVE;
2081 if (track->mState == TrackBase::RESUMING) {
2082 track->mState = TrackBase::ACTIVE;
2083 param = AudioMixer::RAMP_VOLUME;
2084 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002085 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086 } else if (cblk->server != 0) {
2087 // If the track is stopped before the first frame was mixed,
2088 // do not apply ramp
2089 param = AudioMixer::RAMP_VOLUME;
2090 }
2091
2092 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002093 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002094 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002096 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 if (track->isPausing()) {
2098 track->setPaused();
2099 }
2100 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002101
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 // read original volumes with volume control
2103 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002105 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2106 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002107
Eric Laurente0aed6d2010-09-10 17:44:44 -07002108 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002110 // Delegate volume control to effect in track effect chain if needed
2111 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2112 // Do not ramp volume if volume is controlled by effect
2113 param = AudioMixer::VOLUME;
2114 track->mHasVolumeController = true;
2115 } else {
2116 // force no volume ramp when volume controller was just disabled or removed
2117 // from effect chain to avoid volume spike
2118 if (track->mHasVolumeController) {
2119 param = AudioMixer::VOLUME;
2120 }
2121 track->mHasVolumeController = false;
2122 }
2123
2124 // Convert volumes from 8.24 to 4.12 format
2125 int16_t left, right, aux;
2126 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2127 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2128 left = int16_t(v_clamped);
2129 v_clamped = (vr + (1 << 11)) >> 12;
2130 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2131 right = int16_t(v_clamped);
2132
2133 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2134 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 // XXX: these things DON'T need to be done each time
2137 mAudioMixer->setBufferProvider(track);
2138 mAudioMixer->enable(AudioMixer::MIXING);
2139
2140 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2141 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2142 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2143 mAudioMixer->setParameter(
2144 AudioMixer::TRACK,
2145 AudioMixer::FORMAT, (void *)track->format());
2146 mAudioMixer->setParameter(
2147 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002148 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 mAudioMixer->setParameter(
2150 AudioMixer::RESAMPLE,
2151 AudioMixer::SAMPLE_RATE,
2152 (void *)(cblk->sampleRate));
2153 mAudioMixer->setParameter(
2154 AudioMixer::TRACK,
2155 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2156 mAudioMixer->setParameter(
2157 AudioMixer::TRACK,
2158 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2159
2160 // reset retry count
2161 track->mRetryCount = kMaxTrackRetries;
2162 mixerStatus = MIXER_TRACKS_READY;
2163 } else {
2164 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2165 if (track->isStopped()) {
2166 track->reset();
2167 }
2168 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2169 // We have consumed all the buffers of this track.
2170 // Remove it from the list of active tracks.
2171 tracksToRemove->add(track);
2172 } else {
2173 // No buffers for this track. Give it a few chances to
2174 // fill a buffer, then remove it from active list.
2175 if (--(track->mRetryCount) <= 0) {
2176 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2177 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002178 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002179 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 } else if (mixerStatus != MIXER_TRACKS_READY) {
2181 mixerStatus = MIXER_TRACKS_ENABLED;
2182 }
2183 }
2184 mAudioMixer->disable(AudioMixer::MIXING);
2185 }
2186 }
2187
2188 // remove all the tracks that need to be...
2189 count = tracksToRemove->size();
2190 if (UNLIKELY(count)) {
2191 for (size_t i=0 ; i<count ; i++) {
2192 const sp<Track>& track = tracksToRemove->itemAt(i);
2193 mActiveTracks.remove(track);
2194 if (track->mainBuffer() != mMixBuffer) {
2195 chain = getEffectChain_l(track->sessionId());
2196 if (chain != 0) {
2197 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002198 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 }
2200 }
2201 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002202 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
2204 }
2205 }
2206
2207 // mix buffer must be cleared if all tracks are connected to an
2208 // effect chain as in this case the mixer will not write to
2209 // mix buffer and track effects will accumulate into it
2210 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2211 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2212 }
2213
2214 return mixerStatus;
2215}
2216
2217void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2218{
Eric Laurentde070132010-07-13 04:45:46 -07002219 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2220 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002222
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 size_t size = mTracks.size();
2224 for (size_t i = 0; i < size; i++) {
2225 sp<Track> t = mTracks[i];
2226 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002227 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 }
2230 }
2231}
2232
Eric Laurent9f6530f2011-08-30 10:18:54 -07002233void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2234{
2235 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2236 this, streamType, valid);
2237 Mutex::Autolock _l(mLock);
2238
2239 mStreamTypes[streamType].valid = valid;
2240}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241
2242// getTrackName_l() must be called with ThreadBase::mLock held
2243int AudioFlinger::MixerThread::getTrackName_l()
2244{
2245 return mAudioMixer->getTrackName();
2246}
2247
2248// deleteTrackName_l() must be called with ThreadBase::mLock held
2249void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2250{
2251 LOGV("remove track (%d) and delete from mixer", name);
2252 mAudioMixer->deleteTrackName(name);
2253}
2254
2255// checkForNewParameters_l() must be called with ThreadBase::mLock held
2256bool AudioFlinger::MixerThread::checkForNewParameters_l()
2257{
2258 bool reconfig = false;
2259
2260 while (!mNewParameters.isEmpty()) {
2261 status_t status = NO_ERROR;
2262 String8 keyValuePair = mNewParameters[0];
2263 AudioParameter param = AudioParameter(keyValuePair);
2264 int value;
2265
2266 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2267 reconfig = true;
2268 }
2269 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002270 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002271 status = BAD_VALUE;
2272 } else {
2273 reconfig = true;
2274 }
2275 }
2276 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002277 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 status = BAD_VALUE;
2279 } else {
2280 reconfig = true;
2281 }
2282 }
2283 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2284 // do not accept frame count changes if tracks are open as the track buffer
2285 // size depends on frame count and correct behavior would not be garantied
2286 // if frame count is changed after track creation
2287 if (!mTracks.isEmpty()) {
2288 status = INVALID_OPERATION;
2289 } else {
2290 reconfig = true;
2291 }
2292 }
2293 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002294 // when changing the audio output device, call addBatteryData to notify
2295 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002296 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002297 uint32_t params = 0;
2298 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002299 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002300 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2301 }
2302
2303 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002304 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002305 // check if any other device (except speaker) is on
2306 if (value & deviceWithoutSpeaker ) {
2307 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2308 }
2309
2310 if (params != 0) {
2311 addBatteryData(params);
2312 }
2313 }
2314
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 // forward device change to effects that have requested to be
2316 // aware of attached audio device.
2317 mDevice = (uint32_t)value;
2318 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002319 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002320 }
2321 }
2322
2323 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002324 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002325 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002326 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002327 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002328 mStandby = true;
2329 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002330 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002331 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 }
2333 if (status == NO_ERROR && reconfig) {
2334 delete mAudioMixer;
2335 readOutputParameters();
2336 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2337 for (size_t i = 0; i < mTracks.size() ; i++) {
2338 int name = getTrackName_l();
2339 if (name < 0) break;
2340 mTracks[i]->mName = name;
2341 // limit track sample rate to 2 x new output sample rate
2342 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2343 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2344 }
2345 }
2346 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2347 }
2348 }
2349
2350 mNewParameters.removeAt(0);
2351
2352 mParamStatus = status;
2353 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002354 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2355 // already timed out waiting for the status and will never signal the condition.
2356 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
2358 return reconfig;
2359}
2360
2361status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2362{
2363 const size_t SIZE = 256;
2364 char buffer[SIZE];
2365 String8 result;
2366
2367 PlaybackThread::dumpInternals(fd, args);
2368
2369 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2370 result.append(buffer);
2371 write(fd, result.string(), result.size());
2372 return NO_ERROR;
2373}
2374
2375uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2376{
Dima Zavin799a70e2011-04-18 16:57:27 -07002377 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378}
2379
2380uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2381{
Eric Laurent60e18242010-07-29 06:50:24 -07002382 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002383}
2384
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002385uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2386{
2387 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2388}
2389
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002391AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 : PlaybackThread(audioFlinger, output, id, device)
2393{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002394 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395}
2396
2397AudioFlinger::DirectOutputThread::~DirectOutputThread()
2398{
2399}
2400
2401
2402static inline int16_t clamp16(int32_t sample)
2403{
2404 if ((sample>>15) ^ (sample>>31))
2405 sample = 0x7FFF ^ (sample>>31);
2406 return sample;
2407}
2408
2409static inline
2410int32_t mul(int16_t in, int16_t v)
2411{
2412#if defined(__arm__) && !defined(__thumb__)
2413 int32_t out;
2414 asm( "smulbb %[out], %[in], %[v] \n"
2415 : [out]"=r"(out)
2416 : [in]"%r"(in), [v]"r"(v)
2417 : );
2418 return out;
2419#else
2420 return in * int32_t(v);
2421#endif
2422}
2423
2424void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2425{
2426 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002427 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 return;
2429 }
2430
2431 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002432 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002433 size_t count = mFrameCount * mChannelCount;
2434 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2435 int16_t *dst = mMixBuffer + count-1;
2436 while(count--) {
2437 *dst-- = (int16_t)(*src--^0x80) << 8;
2438 }
2439 }
2440
2441 size_t frameCount = mFrameCount;
2442 int16_t *out = mMixBuffer;
2443 if (ramp) {
2444 if (mChannelCount == 1) {
2445 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2446 int32_t vlInc = d / (int32_t)frameCount;
2447 int32_t vl = ((int32_t)mLeftVolShort << 16);
2448 do {
2449 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2450 out++;
2451 vl += vlInc;
2452 } while (--frameCount);
2453
2454 } else {
2455 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2456 int32_t vlInc = d / (int32_t)frameCount;
2457 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2458 int32_t vrInc = d / (int32_t)frameCount;
2459 int32_t vl = ((int32_t)mLeftVolShort << 16);
2460 int32_t vr = ((int32_t)mRightVolShort << 16);
2461 do {
2462 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2463 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2464 out += 2;
2465 vl += vlInc;
2466 vr += vrInc;
2467 } while (--frameCount);
2468 }
2469 } else {
2470 if (mChannelCount == 1) {
2471 do {
2472 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2473 out++;
2474 } while (--frameCount);
2475 } else {
2476 do {
2477 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2478 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2479 out += 2;
2480 } while (--frameCount);
2481 }
2482 }
2483
2484 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002485 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 size_t count = mFrameCount * mChannelCount;
2487 int16_t *src = mMixBuffer;
2488 uint8_t *dst = (uint8_t *)mMixBuffer;
2489 while(count--) {
2490 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2491 }
2492 }
2493
2494 mLeftVolShort = leftVol;
2495 mRightVolShort = rightVol;
2496}
2497
2498bool AudioFlinger::DirectOutputThread::threadLoop()
2499{
2500 uint32_t mixerStatus = MIXER_IDLE;
2501 sp<Track> trackToRemove;
2502 sp<Track> activeTrack;
2503 nsecs_t standbyTime = systemTime();
2504 int8_t *curBuf;
2505 size_t mixBufferSize = mFrameCount*mFrameSize;
2506 uint32_t activeSleepTime = activeSleepTimeUs();
2507 uint32_t idleSleepTime = idleSleepTimeUs();
2508 uint32_t sleepTime = idleSleepTime;
2509 // use shorter standby delay as on normal output to release
2510 // hardware resources as soon as possible
2511 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2512
Eric Laurentfeb0db62011-07-22 09:04:31 -07002513 acquireWakeLock();
2514
Mathias Agopian65ab4712010-07-14 17:59:35 -07002515 while (!exitPending())
2516 {
2517 bool rampVolume;
2518 uint16_t leftVol;
2519 uint16_t rightVol;
2520 Vector< sp<EffectChain> > effectChains;
2521
2522 processConfigEvents();
2523
2524 mixerStatus = MIXER_IDLE;
2525
2526 { // scope for the mLock
2527
2528 Mutex::Autolock _l(mLock);
2529
2530 if (checkForNewParameters_l()) {
2531 mixBufferSize = mFrameCount*mFrameSize;
2532 activeSleepTime = activeSleepTimeUs();
2533 idleSleepTime = idleSleepTimeUs();
2534 standbyDelay = microseconds(activeSleepTime*2);
2535 }
2536
2537 // put audio hardware into standby after short delay
2538 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2539 mSuspended) {
2540 // wait until we have something to do...
2541 if (!mStandby) {
2542 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002543 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002544 mStandby = true;
2545 mBytesWritten = 0;
2546 }
2547
2548 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2549 // we're about to wait, flush the binder command buffer
2550 IPCThreadState::self()->flushCommands();
2551
2552 if (exitPending()) break;
2553
Eric Laurentfeb0db62011-07-22 09:04:31 -07002554 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2556 mWaitWorkCV.wait(mLock);
2557 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002558 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559
2560 if (mMasterMute == false) {
2561 char value[PROPERTY_VALUE_MAX];
2562 property_get("ro.audio.silent", value, "0");
2563 if (atoi(value)) {
2564 LOGD("Silence is golden");
2565 setMasterMute(true);
2566 }
2567 }
2568
2569 standbyTime = systemTime() + standbyDelay;
2570 sleepTime = idleSleepTime;
2571 continue;
2572 }
2573 }
2574
2575 effectChains = mEffectChains;
2576
2577 // find out which tracks need to be processed
2578 if (mActiveTracks.size() != 0) {
2579 sp<Track> t = mActiveTracks[0].promote();
2580 if (t == 0) continue;
2581
2582 Track* const track = t.get();
2583 audio_track_cblk_t* cblk = track->cblk();
2584
2585 // The first time a track is added we wait
2586 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002587 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 !track->isPaused() && !track->isTerminated())
2589 {
2590 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2591
2592 if (track->mFillingUpStatus == Track::FS_FILLED) {
2593 track->mFillingUpStatus = Track::FS_ACTIVE;
2594 mLeftVolFloat = mRightVolFloat = 0;
2595 mLeftVolShort = mRightVolShort = 0;
2596 if (track->mState == TrackBase::RESUMING) {
2597 track->mState = TrackBase::ACTIVE;
2598 rampVolume = true;
2599 }
2600 } else if (cblk->server != 0) {
2601 // If the track is stopped before the first frame was mixed,
2602 // do not apply ramp
2603 rampVolume = true;
2604 }
2605 // compute volume for this track
2606 float left, right;
2607 if (track->isMuted() || mMasterMute || track->isPausing() ||
2608 mStreamTypes[track->type()].mute) {
2609 left = right = 0;
2610 if (track->isPausing()) {
2611 track->setPaused();
2612 }
2613 } else {
2614 float typeVolume = mStreamTypes[track->type()].volume;
2615 float v = mMasterVolume * typeVolume;
2616 float v_clamped = v * cblk->volume[0];
2617 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2618 left = v_clamped/MAX_GAIN;
2619 v_clamped = v * cblk->volume[1];
2620 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2621 right = v_clamped/MAX_GAIN;
2622 }
2623
2624 if (left != mLeftVolFloat || right != mRightVolFloat) {
2625 mLeftVolFloat = left;
2626 mRightVolFloat = right;
2627
2628 // If audio HAL implements volume control,
2629 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002630 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002631 left = 1.0f;
2632 right = 1.0f;
2633 }
2634
2635 // Convert volumes from float to 8.24
2636 uint32_t vl = (uint32_t)(left * (1 << 24));
2637 uint32_t vr = (uint32_t)(right * (1 << 24));
2638
2639 // Delegate volume control to effect in track effect chain if needed
2640 // only one effect chain can be present on DirectOutputThread, so if
2641 // there is one, the track is connected to it
2642 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002643 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002644 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002645 rampVolume = false;
2646 }
2647 }
2648
2649 // Convert volumes from 8.24 to 4.12 format
2650 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2651 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2652 leftVol = (uint16_t)v_clamped;
2653 v_clamped = (vr + (1 << 11)) >> 12;
2654 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2655 rightVol = (uint16_t)v_clamped;
2656 } else {
2657 leftVol = mLeftVolShort;
2658 rightVol = mRightVolShort;
2659 rampVolume = false;
2660 }
2661
2662 // reset retry count
2663 track->mRetryCount = kMaxTrackRetriesDirect;
2664 activeTrack = t;
2665 mixerStatus = MIXER_TRACKS_READY;
2666 } else {
2667 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2668 if (track->isStopped()) {
2669 track->reset();
2670 }
2671 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2672 // We have consumed all the buffers of this track.
2673 // Remove it from the list of active tracks.
2674 trackToRemove = track;
2675 } else {
2676 // No buffers for this track. Give it a few chances to
2677 // fill a buffer, then remove it from active list.
2678 if (--(track->mRetryCount) <= 0) {
2679 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2680 trackToRemove = track;
2681 } else {
2682 mixerStatus = MIXER_TRACKS_ENABLED;
2683 }
2684 }
2685 }
2686 }
2687
2688 // remove all the tracks that need to be...
2689 if (UNLIKELY(trackToRemove != 0)) {
2690 mActiveTracks.remove(trackToRemove);
2691 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002692 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2693 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002694 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695 }
2696 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002697 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002698 }
2699 }
2700
Eric Laurentde070132010-07-13 04:45:46 -07002701 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 }
2703
2704 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2705 AudioBufferProvider::Buffer buffer;
2706 size_t frameCount = mFrameCount;
2707 curBuf = (int8_t *)mMixBuffer;
2708 // output audio to hardware
2709 while (frameCount) {
2710 buffer.frameCount = frameCount;
2711 activeTrack->getNextBuffer(&buffer);
2712 if (UNLIKELY(buffer.raw == 0)) {
2713 memset(curBuf, 0, frameCount * mFrameSize);
2714 break;
2715 }
2716 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2717 frameCount -= buffer.frameCount;
2718 curBuf += buffer.frameCount * mFrameSize;
2719 activeTrack->releaseBuffer(&buffer);
2720 }
2721 sleepTime = 0;
2722 standbyTime = systemTime() + standbyDelay;
2723 } else {
2724 if (sleepTime == 0) {
2725 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2726 sleepTime = activeSleepTime;
2727 } else {
2728 sleepTime = idleSleepTime;
2729 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002730 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2732 sleepTime = 0;
2733 }
2734 }
2735
2736 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002737 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002738 }
2739 // sleepTime == 0 means we must write to audio hardware
2740 if (sleepTime == 0) {
2741 if (mixerStatus == MIXER_TRACKS_READY) {
2742 applyVolume(leftVol, rightVol, rampVolume);
2743 }
2744 for (size_t i = 0; i < effectChains.size(); i ++) {
2745 effectChains[i]->process_l();
2746 }
Eric Laurentde070132010-07-13 04:45:46 -07002747 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002748
2749 mLastWriteTime = systemTime();
2750 mInWrite = true;
2751 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002752 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2754 mNumWrites++;
2755 mInWrite = false;
2756 mStandby = false;
2757 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002758 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002759 usleep(sleepTime);
2760 }
2761
2762 // finally let go of removed track, without the lock held
2763 // since we can't guarantee the destructors won't acquire that
2764 // same lock.
2765 trackToRemove.clear();
2766 activeTrack.clear();
2767
2768 // Effect chains will be actually deleted here if they were removed from
2769 // mEffectChains list during mixing or effects processing
2770 effectChains.clear();
2771 }
2772
2773 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002774 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 }
2776
Eric Laurentfeb0db62011-07-22 09:04:31 -07002777 releaseWakeLock();
2778
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 LOGV("DirectOutputThread %p exiting", this);
2780 return false;
2781}
2782
2783// getTrackName_l() must be called with ThreadBase::mLock held
2784int AudioFlinger::DirectOutputThread::getTrackName_l()
2785{
2786 return 0;
2787}
2788
2789// deleteTrackName_l() must be called with ThreadBase::mLock held
2790void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2791{
2792}
2793
2794// checkForNewParameters_l() must be called with ThreadBase::mLock held
2795bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2796{
2797 bool reconfig = false;
2798
2799 while (!mNewParameters.isEmpty()) {
2800 status_t status = NO_ERROR;
2801 String8 keyValuePair = mNewParameters[0];
2802 AudioParameter param = AudioParameter(keyValuePair);
2803 int value;
2804
2805 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2806 // do not accept frame count changes if tracks are open as the track buffer
2807 // size depends on frame count and correct behavior would not be garantied
2808 // if frame count is changed after track creation
2809 if (!mTracks.isEmpty()) {
2810 status = INVALID_OPERATION;
2811 } else {
2812 reconfig = true;
2813 }
2814 }
2815 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002816 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002817 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002819 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 mStandby = true;
2821 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002822 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002823 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 }
2825 if (status == NO_ERROR && reconfig) {
2826 readOutputParameters();
2827 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2828 }
2829 }
2830
2831 mNewParameters.removeAt(0);
2832
2833 mParamStatus = status;
2834 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002835 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2836 // already timed out waiting for the status and will never signal the condition.
2837 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 }
2839 return reconfig;
2840}
2841
2842uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2843{
2844 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002845 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002846 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 } else {
2848 time = 10000;
2849 }
2850 return time;
2851}
2852
2853uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2854{
2855 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002856 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002857 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002858 } else {
2859 time = 10000;
2860 }
2861 return time;
2862}
2863
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002864uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2865{
2866 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002867 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002868 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2869 } else {
2870 time = 10000;
2871 }
2872 return time;
2873}
2874
2875
Mathias Agopian65ab4712010-07-14 17:59:35 -07002876// ----------------------------------------------------------------------------
2877
2878AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2879 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2880{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002881 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002882 addOutputTrack(mainThread);
2883}
2884
2885AudioFlinger::DuplicatingThread::~DuplicatingThread()
2886{
2887 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2888 mOutputTracks[i]->destroy();
2889 }
2890 mOutputTracks.clear();
2891}
2892
2893bool AudioFlinger::DuplicatingThread::threadLoop()
2894{
2895 Vector< sp<Track> > tracksToRemove;
2896 uint32_t mixerStatus = MIXER_IDLE;
2897 nsecs_t standbyTime = systemTime();
2898 size_t mixBufferSize = mFrameCount*mFrameSize;
2899 SortedVector< sp<OutputTrack> > outputTracks;
2900 uint32_t writeFrames = 0;
2901 uint32_t activeSleepTime = activeSleepTimeUs();
2902 uint32_t idleSleepTime = idleSleepTimeUs();
2903 uint32_t sleepTime = idleSleepTime;
2904 Vector< sp<EffectChain> > effectChains;
2905
Eric Laurentfeb0db62011-07-22 09:04:31 -07002906 acquireWakeLock();
2907
Mathias Agopian65ab4712010-07-14 17:59:35 -07002908 while (!exitPending())
2909 {
2910 processConfigEvents();
2911
2912 mixerStatus = MIXER_IDLE;
2913 { // scope for the mLock
2914
2915 Mutex::Autolock _l(mLock);
2916
2917 if (checkForNewParameters_l()) {
2918 mixBufferSize = mFrameCount*mFrameSize;
2919 updateWaitTime();
2920 activeSleepTime = activeSleepTimeUs();
2921 idleSleepTime = idleSleepTimeUs();
2922 }
2923
2924 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2925
2926 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2927 outputTracks.add(mOutputTracks[i]);
2928 }
2929
2930 // put audio hardware into standby after short delay
2931 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2932 mSuspended) {
2933 if (!mStandby) {
2934 for (size_t i = 0; i < outputTracks.size(); i++) {
2935 outputTracks[i]->stop();
2936 }
2937 mStandby = true;
2938 mBytesWritten = 0;
2939 }
2940
2941 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2942 // we're about to wait, flush the binder command buffer
2943 IPCThreadState::self()->flushCommands();
2944 outputTracks.clear();
2945
2946 if (exitPending()) break;
2947
Eric Laurentfeb0db62011-07-22 09:04:31 -07002948 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002949 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2950 mWaitWorkCV.wait(mLock);
2951 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002952 acquireWakeLock_l();
2953
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 if (mMasterMute == false) {
2955 char value[PROPERTY_VALUE_MAX];
2956 property_get("ro.audio.silent", value, "0");
2957 if (atoi(value)) {
2958 LOGD("Silence is golden");
2959 setMasterMute(true);
2960 }
2961 }
2962
2963 standbyTime = systemTime() + kStandbyTimeInNsecs;
2964 sleepTime = idleSleepTime;
2965 continue;
2966 }
2967 }
2968
2969 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2970
2971 // prevent any changes in effect chain list and in each effect chain
2972 // during mixing and effect process as the audio buffers could be deleted
2973 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002974 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002975 }
2976
2977 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2978 // mix buffers...
2979 if (outputsReady(outputTracks)) {
2980 mAudioMixer->process();
2981 } else {
2982 memset(mMixBuffer, 0, mixBufferSize);
2983 }
2984 sleepTime = 0;
2985 writeFrames = mFrameCount;
2986 } else {
2987 if (sleepTime == 0) {
2988 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2989 sleepTime = activeSleepTime;
2990 } else {
2991 sleepTime = idleSleepTime;
2992 }
2993 } else if (mBytesWritten != 0) {
2994 // flush remaining overflow buffers in output tracks
2995 for (size_t i = 0; i < outputTracks.size(); i++) {
2996 if (outputTracks[i]->isActive()) {
2997 sleepTime = 0;
2998 writeFrames = 0;
2999 memset(mMixBuffer, 0, mixBufferSize);
3000 break;
3001 }
3002 }
3003 }
3004 }
3005
3006 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003007 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003008 }
3009 // sleepTime == 0 means we must write to audio hardware
3010 if (sleepTime == 0) {
3011 for (size_t i = 0; i < effectChains.size(); i ++) {
3012 effectChains[i]->process_l();
3013 }
3014 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003015 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016
3017 standbyTime = systemTime() + kStandbyTimeInNsecs;
3018 for (size_t i = 0; i < outputTracks.size(); i++) {
3019 outputTracks[i]->write(mMixBuffer, writeFrames);
3020 }
3021 mStandby = false;
3022 mBytesWritten += mixBufferSize;
3023 } else {
3024 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003025 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 usleep(sleepTime);
3027 }
3028
3029 // finally let go of all our tracks, without the lock held
3030 // since we can't guarantee the destructors won't acquire that
3031 // same lock.
3032 tracksToRemove.clear();
3033 outputTracks.clear();
3034
3035 // Effect chains will be actually deleted here if they were removed from
3036 // mEffectChains list during mixing or effects processing
3037 effectChains.clear();
3038 }
3039
Eric Laurentfeb0db62011-07-22 09:04:31 -07003040 releaseWakeLock();
3041
Mathias Agopian65ab4712010-07-14 17:59:35 -07003042 return false;
3043}
3044
3045void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3046{
3047 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3048 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3049 this,
3050 mSampleRate,
3051 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003052 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 frameCount);
3054 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003055 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 mOutputTracks.add(outputTrack);
3057 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3058 updateWaitTime();
3059 }
3060}
3061
3062void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3063{
3064 Mutex::Autolock _l(mLock);
3065 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3066 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3067 mOutputTracks[i]->destroy();
3068 mOutputTracks.removeAt(i);
3069 updateWaitTime();
3070 return;
3071 }
3072 }
3073 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3074}
3075
3076void AudioFlinger::DuplicatingThread::updateWaitTime()
3077{
3078 mWaitTimeMs = UINT_MAX;
3079 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3080 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3081 if (strong != NULL) {
3082 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3083 if (waitTimeMs < mWaitTimeMs) {
3084 mWaitTimeMs = waitTimeMs;
3085 }
3086 }
3087 }
3088}
3089
3090
3091bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3092{
3093 for (size_t i = 0; i < outputTracks.size(); i++) {
3094 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3095 if (thread == 0) {
3096 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3097 return false;
3098 }
3099 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3100 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3101 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3102 return false;
3103 }
3104 }
3105 return true;
3106}
3107
3108uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3109{
3110 return (mWaitTimeMs * 1000) / 2;
3111}
3112
3113// ----------------------------------------------------------------------------
3114
3115// TrackBase constructor must be called with AudioFlinger::mLock held
3116AudioFlinger::ThreadBase::TrackBase::TrackBase(
3117 const wp<ThreadBase>& thread,
3118 const sp<Client>& client,
3119 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003120 uint32_t format,
3121 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003122 int frameCount,
3123 uint32_t flags,
3124 const sp<IMemory>& sharedBuffer,
3125 int sessionId)
3126 : RefBase(),
3127 mThread(thread),
3128 mClient(client),
3129 mCblk(0),
3130 mFrameCount(0),
3131 mState(IDLE),
3132 mClientTid(-1),
3133 mFormat(format),
3134 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3135 mSessionId(sessionId)
3136{
3137 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3138
3139 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3140 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003141 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003142 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3143 if (sharedBuffer == 0) {
3144 size += bufferSize;
3145 }
3146
3147 if (client != NULL) {
3148 mCblkMemory = client->heap()->allocate(size);
3149 if (mCblkMemory != 0) {
3150 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3151 if (mCblk) { // construct the shared structure in-place.
3152 new(mCblk) audio_track_cblk_t();
3153 // clear all buffers
3154 mCblk->frameCount = frameCount;
3155 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003156 mChannelCount = channelCount;
3157 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 if (sharedBuffer == 0) {
3159 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3160 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3161 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003162 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003163 mCblk->flags = CBLK_UNDERRUN_ON;
3164 } else {
3165 mBuffer = sharedBuffer->pointer();
3166 }
3167 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3168 }
3169 } else {
3170 LOGE("not enough memory for AudioTrack size=%u", size);
3171 client->heap()->dump("AudioTrack");
3172 return;
3173 }
3174 } else {
3175 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3176 if (mCblk) { // construct the shared structure in-place.
3177 new(mCblk) audio_track_cblk_t();
3178 // clear all buffers
3179 mCblk->frameCount = frameCount;
3180 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003181 mChannelCount = channelCount;
3182 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003183 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3184 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3185 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003186 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 mCblk->flags = CBLK_UNDERRUN_ON;
3188 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3189 }
3190 }
3191}
3192
3193AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3194{
3195 if (mCblk) {
3196 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3197 if (mClient == NULL) {
3198 delete mCblk;
3199 }
3200 }
3201 mCblkMemory.clear(); // and free the shared memory
3202 if (mClient != NULL) {
3203 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3204 mClient.clear();
3205 }
3206}
3207
3208void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3209{
3210 buffer->raw = 0;
3211 mFrameCount = buffer->frameCount;
3212 step();
3213 buffer->frameCount = 0;
3214}
3215
3216bool AudioFlinger::ThreadBase::TrackBase::step() {
3217 bool result;
3218 audio_track_cblk_t* cblk = this->cblk();
3219
3220 result = cblk->stepServer(mFrameCount);
3221 if (!result) {
3222 LOGV("stepServer failed acquiring cblk mutex");
3223 mFlags |= STEPSERVER_FAILED;
3224 }
3225 return result;
3226}
3227
3228void AudioFlinger::ThreadBase::TrackBase::reset() {
3229 audio_track_cblk_t* cblk = this->cblk();
3230
3231 cblk->user = 0;
3232 cblk->server = 0;
3233 cblk->userBase = 0;
3234 cblk->serverBase = 0;
3235 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3236 LOGV("TrackBase::reset");
3237}
3238
3239sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3240{
3241 return mCblkMemory;
3242}
3243
3244int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3245 return (int)mCblk->sampleRate;
3246}
3247
3248int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003249 return (const int)mChannelCount;
3250}
3251
3252uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3253 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254}
3255
3256void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3257 audio_track_cblk_t* cblk = this->cblk();
3258 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3259 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3260
3261 // Check validity of returned pointer in case the track control block would have been corrupted.
3262 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3263 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3264 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 -07003265 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003266 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003267 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003268 return 0;
3269 }
3270
3271 return bufferStart;
3272}
3273
3274// ----------------------------------------------------------------------------
3275
3276// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3277AudioFlinger::PlaybackThread::Track::Track(
3278 const wp<ThreadBase>& thread,
3279 const sp<Client>& client,
3280 int streamType,
3281 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003282 uint32_t format,
3283 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003284 int frameCount,
3285 const sp<IMemory>& sharedBuffer,
3286 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003287 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003288 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3289 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290{
3291 if (mCblk != NULL) {
3292 sp<ThreadBase> baseThread = thread.promote();
3293 if (baseThread != 0) {
3294 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3295 mName = playbackThread->getTrackName_l();
3296 mMainBuffer = playbackThread->mixBuffer();
3297 }
3298 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3299 if (mName < 0) {
3300 LOGE("no more track names available");
3301 }
3302 mVolume[0] = 1.0f;
3303 mVolume[1] = 1.0f;
3304 mStreamType = streamType;
3305 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3306 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003307 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 }
3309}
3310
3311AudioFlinger::PlaybackThread::Track::~Track()
3312{
3313 LOGV("PlaybackThread::Track destructor");
3314 sp<ThreadBase> thread = mThread.promote();
3315 if (thread != 0) {
3316 Mutex::Autolock _l(thread->mLock);
3317 mState = TERMINATED;
3318 }
3319}
3320
3321void AudioFlinger::PlaybackThread::Track::destroy()
3322{
3323 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3324 // by removing it from mTracks vector, so there is a risk that this Tracks's
3325 // desctructor is called. As the destructor needs to lock mLock,
3326 // we must acquire a strong reference on this Track before locking mLock
3327 // here so that the destructor is called only when exiting this function.
3328 // On the other hand, as long as Track::destroy() is only called by
3329 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3330 // this Track with its member mTrack.
3331 sp<Track> keep(this);
3332 { // scope for mLock
3333 sp<ThreadBase> thread = mThread.promote();
3334 if (thread != 0) {
3335 if (!isOutputTrack()) {
3336 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003337 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003338 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003339 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003340
3341 // to track the speaker usage
3342 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 }
3344 AudioSystem::releaseOutput(thread->id());
3345 }
3346 Mutex::Autolock _l(thread->mLock);
3347 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3348 playbackThread->destroyTrack_l(this);
3349 }
3350 }
3351}
3352
3353void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3354{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003355 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 -07003356 mName - AudioMixer::TRACK0,
3357 (mClient == NULL) ? getpid() : mClient->pid(),
3358 mStreamType,
3359 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003360 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 mSessionId,
3362 mFrameCount,
3363 mState,
3364 mMute,
3365 mFillingUpStatus,
3366 mCblk->sampleRate,
3367 mCblk->volume[0],
3368 mCblk->volume[1],
3369 mCblk->server,
3370 mCblk->user,
3371 (int)mMainBuffer,
3372 (int)mAuxBuffer);
3373}
3374
3375status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3376{
3377 audio_track_cblk_t* cblk = this->cblk();
3378 uint32_t framesReady;
3379 uint32_t framesReq = buffer->frameCount;
3380
3381 // Check if last stepServer failed, try to step now
3382 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3383 if (!step()) goto getNextBuffer_exit;
3384 LOGV("stepServer recovered");
3385 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3386 }
3387
3388 framesReady = cblk->framesReady();
3389
3390 if (LIKELY(framesReady)) {
3391 uint32_t s = cblk->server;
3392 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3393
3394 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3395 if (framesReq > framesReady) {
3396 framesReq = framesReady;
3397 }
3398 if (s + framesReq > bufferEnd) {
3399 framesReq = bufferEnd - s;
3400 }
3401
3402 buffer->raw = getBuffer(s, framesReq);
3403 if (buffer->raw == 0) goto getNextBuffer_exit;
3404
3405 buffer->frameCount = framesReq;
3406 return NO_ERROR;
3407 }
3408
3409getNextBuffer_exit:
3410 buffer->raw = 0;
3411 buffer->frameCount = 0;
3412 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3413 return NOT_ENOUGH_DATA;
3414}
3415
3416bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003417 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003418
3419 if (mCblk->framesReady() >= mCblk->frameCount ||
3420 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3421 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003422 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 return true;
3424 }
3425 return false;
3426}
3427
3428status_t AudioFlinger::PlaybackThread::Track::start()
3429{
3430 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003431 LOGV("start(%d), calling thread %d session %d",
3432 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 sp<ThreadBase> thread = mThread.promote();
3434 if (thread != 0) {
3435 Mutex::Autolock _l(thread->mLock);
3436 int state = mState;
3437 // here the track could be either new, or restarted
3438 // in both cases "unstop" the track
3439 if (mState == PAUSED) {
3440 mState = TrackBase::RESUMING;
3441 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3442 } else {
3443 mState = TrackBase::ACTIVE;
3444 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3445 }
3446
3447 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3448 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003449 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003450 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003451 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003453
3454 // to track the speaker usage
3455 if (status == NO_ERROR) {
3456 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003458 }
3459 if (status == NO_ERROR) {
3460 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3461 playbackThread->addTrack_l(this);
3462 } else {
3463 mState = state;
3464 }
3465 } else {
3466 status = BAD_VALUE;
3467 }
3468 return status;
3469}
3470
3471void AudioFlinger::PlaybackThread::Track::stop()
3472{
3473 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3474 sp<ThreadBase> thread = mThread.promote();
3475 if (thread != 0) {
3476 Mutex::Autolock _l(thread->mLock);
3477 int state = mState;
3478 if (mState > STOPPED) {
3479 mState = STOPPED;
3480 // If the track is not active (PAUSED and buffers full), flush buffers
3481 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3482 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3483 reset();
3484 }
3485 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3486 }
3487 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3488 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003489 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003490 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003491 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003493
3494 // to track the speaker usage
3495 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 }
3497 }
3498}
3499
3500void AudioFlinger::PlaybackThread::Track::pause()
3501{
3502 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3503 sp<ThreadBase> thread = mThread.promote();
3504 if (thread != 0) {
3505 Mutex::Autolock _l(thread->mLock);
3506 if (mState == ACTIVE || mState == RESUMING) {
3507 mState = PAUSING;
3508 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3509 if (!isOutputTrack()) {
3510 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003511 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003512 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003513 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003515
3516 // to track the speaker usage
3517 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518 }
3519 }
3520 }
3521}
3522
3523void AudioFlinger::PlaybackThread::Track::flush()
3524{
3525 LOGV("flush(%d)", mName);
3526 sp<ThreadBase> thread = mThread.promote();
3527 if (thread != 0) {
3528 Mutex::Autolock _l(thread->mLock);
3529 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3530 return;
3531 }
3532 // No point remaining in PAUSED state after a flush => go to
3533 // STOPPED state
3534 mState = STOPPED;
3535
Eric Laurent38ccae22011-03-28 18:37:07 -07003536 // do not reset the track if it is still in the process of being stopped or paused.
3537 // this will be done by prepareTracks_l() when the track is stopped.
3538 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3539 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3540 reset();
3541 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003542 }
3543}
3544
3545void AudioFlinger::PlaybackThread::Track::reset()
3546{
3547 // Do not reset twice to avoid discarding data written just after a flush and before
3548 // the audioflinger thread detects the track is stopped.
3549 if (!mResetDone) {
3550 TrackBase::reset();
3551 // Force underrun condition to avoid false underrun callback until first data is
3552 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003553 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3554 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555 mFillingUpStatus = FS_FILLING;
3556 mResetDone = true;
3557 }
3558}
3559
3560void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3561{
3562 mMute = muted;
3563}
3564
3565void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3566{
3567 mVolume[0] = left;
3568 mVolume[1] = right;
3569}
3570
3571status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3572{
3573 status_t status = DEAD_OBJECT;
3574 sp<ThreadBase> thread = mThread.promote();
3575 if (thread != 0) {
3576 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3577 status = playbackThread->attachAuxEffect(this, EffectId);
3578 }
3579 return status;
3580}
3581
3582void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3583{
3584 mAuxEffectId = EffectId;
3585 mAuxBuffer = buffer;
3586}
3587
3588// ----------------------------------------------------------------------------
3589
3590// RecordTrack constructor must be called with AudioFlinger::mLock held
3591AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3592 const wp<ThreadBase>& thread,
3593 const sp<Client>& client,
3594 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003595 uint32_t format,
3596 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 int frameCount,
3598 uint32_t flags,
3599 int sessionId)
3600 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003601 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003602 mOverflow(false)
3603{
3604 if (mCblk != NULL) {
3605 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003606 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003607 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003608 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003609 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 } else {
3611 mCblk->frameSize = sizeof(int8_t);
3612 }
3613 }
3614}
3615
3616AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3617{
3618 sp<ThreadBase> thread = mThread.promote();
3619 if (thread != 0) {
3620 AudioSystem::releaseInput(thread->id());
3621 }
3622}
3623
3624status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3625{
3626 audio_track_cblk_t* cblk = this->cblk();
3627 uint32_t framesAvail;
3628 uint32_t framesReq = buffer->frameCount;
3629
3630 // Check if last stepServer failed, try to step now
3631 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3632 if (!step()) goto getNextBuffer_exit;
3633 LOGV("stepServer recovered");
3634 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3635 }
3636
3637 framesAvail = cblk->framesAvailable_l();
3638
3639 if (LIKELY(framesAvail)) {
3640 uint32_t s = cblk->server;
3641 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3642
3643 if (framesReq > framesAvail) {
3644 framesReq = framesAvail;
3645 }
3646 if (s + framesReq > bufferEnd) {
3647 framesReq = bufferEnd - s;
3648 }
3649
3650 buffer->raw = getBuffer(s, framesReq);
3651 if (buffer->raw == 0) goto getNextBuffer_exit;
3652
3653 buffer->frameCount = framesReq;
3654 return NO_ERROR;
3655 }
3656
3657getNextBuffer_exit:
3658 buffer->raw = 0;
3659 buffer->frameCount = 0;
3660 return NOT_ENOUGH_DATA;
3661}
3662
3663status_t AudioFlinger::RecordThread::RecordTrack::start()
3664{
3665 sp<ThreadBase> thread = mThread.promote();
3666 if (thread != 0) {
3667 RecordThread *recordThread = (RecordThread *)thread.get();
3668 return recordThread->start(this);
3669 } else {
3670 return BAD_VALUE;
3671 }
3672}
3673
3674void AudioFlinger::RecordThread::RecordTrack::stop()
3675{
3676 sp<ThreadBase> thread = mThread.promote();
3677 if (thread != 0) {
3678 RecordThread *recordThread = (RecordThread *)thread.get();
3679 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003680 TrackBase::reset();
3681 // Force overerrun condition to avoid false overrun callback until first data is
3682 // read from buffer
3683 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003684 }
3685}
3686
3687void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3688{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003689 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003690 (mClient == NULL) ? getpid() : mClient->pid(),
3691 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003692 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 mSessionId,
3694 mFrameCount,
3695 mState,
3696 mCblk->sampleRate,
3697 mCblk->server,
3698 mCblk->user);
3699}
3700
3701
3702// ----------------------------------------------------------------------------
3703
3704AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3705 const wp<ThreadBase>& thread,
3706 DuplicatingThread *sourceThread,
3707 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003708 uint32_t format,
3709 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003710 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003711 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712 mActive(false), mSourceThread(sourceThread)
3713{
3714
3715 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3716 if (mCblk != NULL) {
3717 mCblk->flags |= CBLK_DIRECTION_OUT;
3718 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3719 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3720 mOutBuffer.frameCount = 0;
3721 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003722 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3723 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3724 mCblk, mBuffer, mCblk->buffers,
3725 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726 } else {
3727 LOGW("Error creating output track on thread %p", playbackThread);
3728 }
3729}
3730
3731AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3732{
3733 clearBufferQueue();
3734}
3735
3736status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3737{
3738 status_t status = Track::start();
3739 if (status != NO_ERROR) {
3740 return status;
3741 }
3742
3743 mActive = true;
3744 mRetryCount = 127;
3745 return status;
3746}
3747
3748void AudioFlinger::PlaybackThread::OutputTrack::stop()
3749{
3750 Track::stop();
3751 clearBufferQueue();
3752 mOutBuffer.frameCount = 0;
3753 mActive = false;
3754}
3755
3756bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3757{
3758 Buffer *pInBuffer;
3759 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003760 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 bool outputBufferFull = false;
3762 inBuffer.frameCount = frames;
3763 inBuffer.i16 = data;
3764
3765 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3766
3767 if (!mActive && frames != 0) {
3768 start();
3769 sp<ThreadBase> thread = mThread.promote();
3770 if (thread != 0) {
3771 MixerThread *mixerThread = (MixerThread *)thread.get();
3772 if (mCblk->frameCount > frames){
3773 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3774 uint32_t startFrames = (mCblk->frameCount - frames);
3775 pInBuffer = new Buffer;
3776 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3777 pInBuffer->frameCount = startFrames;
3778 pInBuffer->i16 = pInBuffer->mBuffer;
3779 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3780 mBufferQueue.add(pInBuffer);
3781 } else {
3782 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3783 }
3784 }
3785 }
3786 }
3787
3788 while (waitTimeLeftMs) {
3789 // First write pending buffers, then new data
3790 if (mBufferQueue.size()) {
3791 pInBuffer = mBufferQueue.itemAt(0);
3792 } else {
3793 pInBuffer = &inBuffer;
3794 }
3795
3796 if (pInBuffer->frameCount == 0) {
3797 break;
3798 }
3799
3800 if (mOutBuffer.frameCount == 0) {
3801 mOutBuffer.frameCount = pInBuffer->frameCount;
3802 nsecs_t startTime = systemTime();
3803 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3804 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3805 outputBufferFull = true;
3806 break;
3807 }
3808 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3809 if (waitTimeLeftMs >= waitTimeMs) {
3810 waitTimeLeftMs -= waitTimeMs;
3811 } else {
3812 waitTimeLeftMs = 0;
3813 }
3814 }
3815
3816 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3817 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3818 mCblk->stepUser(outFrames);
3819 pInBuffer->frameCount -= outFrames;
3820 pInBuffer->i16 += outFrames * channelCount;
3821 mOutBuffer.frameCount -= outFrames;
3822 mOutBuffer.i16 += outFrames * channelCount;
3823
3824 if (pInBuffer->frameCount == 0) {
3825 if (mBufferQueue.size()) {
3826 mBufferQueue.removeAt(0);
3827 delete [] pInBuffer->mBuffer;
3828 delete pInBuffer;
3829 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3830 } else {
3831 break;
3832 }
3833 }
3834 }
3835
3836 // If we could not write all frames, allocate a buffer and queue it for next time.
3837 if (inBuffer.frameCount) {
3838 sp<ThreadBase> thread = mThread.promote();
3839 if (thread != 0 && !thread->standby()) {
3840 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3841 pInBuffer = new Buffer;
3842 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3843 pInBuffer->frameCount = inBuffer.frameCount;
3844 pInBuffer->i16 = pInBuffer->mBuffer;
3845 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3846 mBufferQueue.add(pInBuffer);
3847 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3848 } else {
3849 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3850 }
3851 }
3852 }
3853
3854 // Calling write() with a 0 length buffer, means that no more data will be written:
3855 // If no more buffers are pending, fill output track buffer to make sure it is started
3856 // by output mixer.
3857 if (frames == 0 && mBufferQueue.size() == 0) {
3858 if (mCblk->user < mCblk->frameCount) {
3859 frames = mCblk->frameCount - mCblk->user;
3860 pInBuffer = new Buffer;
3861 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3862 pInBuffer->frameCount = frames;
3863 pInBuffer->i16 = pInBuffer->mBuffer;
3864 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3865 mBufferQueue.add(pInBuffer);
3866 } else if (mActive) {
3867 stop();
3868 }
3869 }
3870
3871 return outputBufferFull;
3872}
3873
3874status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3875{
3876 int active;
3877 status_t result;
3878 audio_track_cblk_t* cblk = mCblk;
3879 uint32_t framesReq = buffer->frameCount;
3880
3881// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3882 buffer->frameCount = 0;
3883
3884 uint32_t framesAvail = cblk->framesAvailable();
3885
3886
3887 if (framesAvail == 0) {
3888 Mutex::Autolock _l(cblk->lock);
3889 goto start_loop_here;
3890 while (framesAvail == 0) {
3891 active = mActive;
3892 if (UNLIKELY(!active)) {
3893 LOGV("Not active and NO_MORE_BUFFERS");
3894 return AudioTrack::NO_MORE_BUFFERS;
3895 }
3896 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3897 if (result != NO_ERROR) {
3898 return AudioTrack::NO_MORE_BUFFERS;
3899 }
3900 // read the server count again
3901 start_loop_here:
3902 framesAvail = cblk->framesAvailable_l();
3903 }
3904 }
3905
3906// if (framesAvail < framesReq) {
3907// return AudioTrack::NO_MORE_BUFFERS;
3908// }
3909
3910 if (framesReq > framesAvail) {
3911 framesReq = framesAvail;
3912 }
3913
3914 uint32_t u = cblk->user;
3915 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3916
3917 if (u + framesReq > bufferEnd) {
3918 framesReq = bufferEnd - u;
3919 }
3920
3921 buffer->frameCount = framesReq;
3922 buffer->raw = (void *)cblk->buffer(u);
3923 return NO_ERROR;
3924}
3925
3926
3927void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3928{
3929 size_t size = mBufferQueue.size();
3930 Buffer *pBuffer;
3931
3932 for (size_t i = 0; i < size; i++) {
3933 pBuffer = mBufferQueue.itemAt(i);
3934 delete [] pBuffer->mBuffer;
3935 delete pBuffer;
3936 }
3937 mBufferQueue.clear();
3938}
3939
3940// ----------------------------------------------------------------------------
3941
3942AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3943 : RefBase(),
3944 mAudioFlinger(audioFlinger),
3945 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3946 mPid(pid)
3947{
3948 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3949}
3950
3951// Client destructor must be called with AudioFlinger::mLock held
3952AudioFlinger::Client::~Client()
3953{
3954 mAudioFlinger->removeClient_l(mPid);
3955}
3956
3957const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3958{
3959 return mMemoryDealer;
3960}
3961
3962// ----------------------------------------------------------------------------
3963
3964AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3965 const sp<IAudioFlingerClient>& client,
3966 pid_t pid)
3967 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3968{
3969}
3970
3971AudioFlinger::NotificationClient::~NotificationClient()
3972{
3973 mClient.clear();
3974}
3975
3976void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3977{
3978 sp<NotificationClient> keep(this);
3979 {
3980 mAudioFlinger->removeNotificationClient(mPid);
3981 }
3982}
3983
3984// ----------------------------------------------------------------------------
3985
3986AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3987 : BnAudioTrack(),
3988 mTrack(track)
3989{
3990}
3991
3992AudioFlinger::TrackHandle::~TrackHandle() {
3993 // just stop the track on deletion, associated resources
3994 // will be freed from the main thread once all pending buffers have
3995 // been played. Unless it's not in the active track list, in which
3996 // case we free everything now...
3997 mTrack->destroy();
3998}
3999
4000status_t AudioFlinger::TrackHandle::start() {
4001 return mTrack->start();
4002}
4003
4004void AudioFlinger::TrackHandle::stop() {
4005 mTrack->stop();
4006}
4007
4008void AudioFlinger::TrackHandle::flush() {
4009 mTrack->flush();
4010}
4011
4012void AudioFlinger::TrackHandle::mute(bool e) {
4013 mTrack->mute(e);
4014}
4015
4016void AudioFlinger::TrackHandle::pause() {
4017 mTrack->pause();
4018}
4019
4020void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4021 mTrack->setVolume(left, right);
4022}
4023
4024sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4025 return mTrack->getCblk();
4026}
4027
4028status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4029{
4030 return mTrack->attachAuxEffect(EffectId);
4031}
4032
4033status_t AudioFlinger::TrackHandle::onTransact(
4034 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4035{
4036 return BnAudioTrack::onTransact(code, data, reply, flags);
4037}
4038
4039// ----------------------------------------------------------------------------
4040
4041sp<IAudioRecord> AudioFlinger::openRecord(
4042 pid_t pid,
4043 int input,
4044 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004045 uint32_t format,
4046 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047 int frameCount,
4048 uint32_t flags,
4049 int *sessionId,
4050 status_t *status)
4051{
4052 sp<RecordThread::RecordTrack> recordTrack;
4053 sp<RecordHandle> recordHandle;
4054 sp<Client> client;
4055 wp<Client> wclient;
4056 status_t lStatus;
4057 RecordThread *thread;
4058 size_t inFrameCount;
4059 int lSessionId;
4060
4061 // check calling permissions
4062 if (!recordingAllowed()) {
4063 lStatus = PERMISSION_DENIED;
4064 goto Exit;
4065 }
4066
4067 // add client to list
4068 { // scope for mLock
4069 Mutex::Autolock _l(mLock);
4070 thread = checkRecordThread_l(input);
4071 if (thread == NULL) {
4072 lStatus = BAD_VALUE;
4073 goto Exit;
4074 }
4075
4076 wclient = mClients.valueFor(pid);
4077 if (wclient != NULL) {
4078 client = wclient.promote();
4079 } else {
4080 client = new Client(this, pid);
4081 mClients.add(pid, client);
4082 }
4083
4084 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004085 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 lSessionId = *sessionId;
4087 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004088 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 if (sessionId != NULL) {
4090 *sessionId = lSessionId;
4091 }
4092 }
4093 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004094 recordTrack = thread->createRecordTrack_l(client,
4095 sampleRate,
4096 format,
4097 channelMask,
4098 frameCount,
4099 flags,
4100 lSessionId,
4101 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004103 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4105 // destructor is called by the TrackBase destructor with mLock held
4106 client.clear();
4107 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 goto Exit;
4109 }
4110
4111 // return to handle to client
4112 recordHandle = new RecordHandle(recordTrack);
4113 lStatus = NO_ERROR;
4114
4115Exit:
4116 if (status) {
4117 *status = lStatus;
4118 }
4119 return recordHandle;
4120}
4121
4122// ----------------------------------------------------------------------------
4123
4124AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4125 : BnAudioRecord(),
4126 mRecordTrack(recordTrack)
4127{
4128}
4129
4130AudioFlinger::RecordHandle::~RecordHandle() {
4131 stop();
4132}
4133
4134status_t AudioFlinger::RecordHandle::start() {
4135 LOGV("RecordHandle::start()");
4136 return mRecordTrack->start();
4137}
4138
4139void AudioFlinger::RecordHandle::stop() {
4140 LOGV("RecordHandle::stop()");
4141 mRecordTrack->stop();
4142}
4143
4144sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4145 return mRecordTrack->getCblk();
4146}
4147
4148status_t AudioFlinger::RecordHandle::onTransact(
4149 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4150{
4151 return BnAudioRecord::onTransact(code, data, reply, flags);
4152}
4153
4154// ----------------------------------------------------------------------------
4155
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004156AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4157 AudioStreamIn *input,
4158 uint32_t sampleRate,
4159 uint32_t channels,
4160 int id,
4161 uint32_t device) :
4162 ThreadBase(audioFlinger, id, device),
4163 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004165 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004166
4167 snprintf(mName, kNameLength, "AudioIn_%d", id);
4168
Dima Zavinfce7a472011-04-19 22:30:36 -07004169 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 mReqSampleRate = sampleRate;
4171 readInputParameters();
4172}
4173
4174
4175AudioFlinger::RecordThread::~RecordThread()
4176{
4177 delete[] mRsmpInBuffer;
4178 if (mResampler != 0) {
4179 delete mResampler;
4180 delete[] mRsmpOutBuffer;
4181 }
4182}
4183
4184void AudioFlinger::RecordThread::onFirstRef()
4185{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004186 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187}
4188
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004189status_t AudioFlinger::RecordThread::readyToRun()
4190{
4191 status_t status = initCheck();
4192 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4193 return status;
4194}
4195
Mathias Agopian65ab4712010-07-14 17:59:35 -07004196bool AudioFlinger::RecordThread::threadLoop()
4197{
4198 AudioBufferProvider::Buffer buffer;
4199 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004200 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004201
Eric Laurent44d98482010-09-30 16:12:31 -07004202 nsecs_t lastWarning = 0;
4203
Eric Laurentfeb0db62011-07-22 09:04:31 -07004204 acquireWakeLock();
4205
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 // start recording
4207 while (!exitPending()) {
4208
4209 processConfigEvents();
4210
4211 { // scope for mLock
4212 Mutex::Autolock _l(mLock);
4213 checkForNewParameters_l();
4214 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4215 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004216 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004217 mStandby = true;
4218 }
4219
4220 if (exitPending()) break;
4221
Eric Laurentfeb0db62011-07-22 09:04:31 -07004222 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223 LOGV("RecordThread: loop stopping");
4224 // go to sleep
4225 mWaitWorkCV.wait(mLock);
4226 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004227 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 continue;
4229 }
4230 if (mActiveTrack != 0) {
4231 if (mActiveTrack->mState == TrackBase::PAUSING) {
4232 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004233 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 mStandby = true;
4235 }
4236 mActiveTrack.clear();
4237 mStartStopCond.broadcast();
4238 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4239 if (mReqChannelCount != mActiveTrack->channelCount()) {
4240 mActiveTrack.clear();
4241 mStartStopCond.broadcast();
4242 } else if (mBytesRead != 0) {
4243 // record start succeeds only if first read from audio input
4244 // succeeds
4245 if (mBytesRead > 0) {
4246 mActiveTrack->mState = TrackBase::ACTIVE;
4247 } else {
4248 mActiveTrack.clear();
4249 }
4250 mStartStopCond.broadcast();
4251 }
4252 mStandby = false;
4253 }
4254 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004255 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004256 }
4257
4258 if (mActiveTrack != 0) {
4259 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4260 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004261 unlockEffectChains(effectChains);
4262 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263 continue;
4264 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004265 for (size_t i = 0; i < effectChains.size(); i ++) {
4266 effectChains[i]->process_l();
4267 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004268
Mathias Agopian65ab4712010-07-14 17:59:35 -07004269 buffer.frameCount = mFrameCount;
4270 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4271 size_t framesOut = buffer.frameCount;
4272 if (mResampler == 0) {
4273 // no resampling
4274 while (framesOut) {
4275 size_t framesIn = mFrameCount - mRsmpInIndex;
4276 if (framesIn) {
4277 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4278 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4279 if (framesIn > framesOut)
4280 framesIn = framesOut;
4281 mRsmpInIndex += framesIn;
4282 framesOut -= framesIn;
4283 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004284 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 memcpy(dst, src, framesIn * mFrameSize);
4286 } else {
4287 int16_t *src16 = (int16_t *)src;
4288 int16_t *dst16 = (int16_t *)dst;
4289 if (mChannelCount == 1) {
4290 while (framesIn--) {
4291 *dst16++ = *src16;
4292 *dst16++ = *src16++;
4293 }
4294 } else {
4295 while (framesIn--) {
4296 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4297 src16 += 2;
4298 }
4299 }
4300 }
4301 }
4302 if (framesOut && mFrameCount == mRsmpInIndex) {
4303 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004304 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004305 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 framesOut = 0;
4307 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004308 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004309 mRsmpInIndex = 0;
4310 }
4311 if (mBytesRead < 0) {
4312 LOGE("Error reading audio input");
4313 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4314 // Force input into standby so that it tries to
4315 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004316 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004317 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318 }
4319 mRsmpInIndex = mFrameCount;
4320 framesOut = 0;
4321 buffer.frameCount = 0;
4322 }
4323 }
4324 }
4325 } else {
4326 // resampling
4327
4328 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4329 // alter output frame count as if we were expecting stereo samples
4330 if (mChannelCount == 1 && mReqChannelCount == 1) {
4331 framesOut >>= 1;
4332 }
4333 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4334 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4335 // are 32 bit aligned which should be always true.
4336 if (mChannelCount == 2 && mReqChannelCount == 1) {
4337 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4338 // the resampler always outputs stereo samples: do post stereo to mono conversion
4339 int16_t *src = (int16_t *)mRsmpOutBuffer;
4340 int16_t *dst = buffer.i16;
4341 while (framesOut--) {
4342 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4343 src += 2;
4344 }
4345 } else {
4346 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4347 }
4348
4349 }
4350 mActiveTrack->releaseBuffer(&buffer);
4351 mActiveTrack->overflow();
4352 }
4353 // client isn't retrieving buffers fast enough
4354 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004355 if (!mActiveTrack->setOverflow()) {
4356 nsecs_t now = systemTime();
4357 if ((now - lastWarning) > kWarningThrottle) {
4358 LOGW("RecordThread: buffer overflow");
4359 lastWarning = now;
4360 }
4361 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004362 // Release the processor for a while before asking for a new buffer.
4363 // This will give the application more chance to read from the buffer and
4364 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004365 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 }
4367 }
Eric Laurentec437d82011-07-26 20:54:46 -07004368 // enable changes in effect chain
4369 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004370 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 }
4372
4373 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004374 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 }
4376 mActiveTrack.clear();
4377
4378 mStartStopCond.broadcast();
4379
Eric Laurentfeb0db62011-07-22 09:04:31 -07004380 releaseWakeLock();
4381
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 LOGV("RecordThread %p exiting", this);
4383 return false;
4384}
4385
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004386
4387sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4388 const sp<AudioFlinger::Client>& client,
4389 uint32_t sampleRate,
4390 int format,
4391 int channelMask,
4392 int frameCount,
4393 uint32_t flags,
4394 int sessionId,
4395 status_t *status)
4396{
4397 sp<RecordTrack> track;
4398 status_t lStatus;
4399
4400 lStatus = initCheck();
4401 if (lStatus != NO_ERROR) {
4402 LOGE("Audio driver not initialized.");
4403 goto Exit;
4404 }
4405
4406 { // scope for mLock
4407 Mutex::Autolock _l(mLock);
4408
4409 track = new RecordTrack(this, client, sampleRate,
4410 format, channelMask, frameCount, flags, sessionId);
4411
4412 if (track->getCblk() == NULL) {
4413 lStatus = NO_MEMORY;
4414 goto Exit;
4415 }
4416
4417 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004418 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4419 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004420 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004421 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4422 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004423 }
4424 lStatus = NO_ERROR;
4425
4426Exit:
4427 if (status) {
4428 *status = lStatus;
4429 }
4430 return track;
4431}
4432
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4434{
4435 LOGV("RecordThread::start");
4436 sp <ThreadBase> strongMe = this;
4437 status_t status = NO_ERROR;
4438 {
4439 AutoMutex lock(&mLock);
4440 if (mActiveTrack != 0) {
4441 if (recordTrack != mActiveTrack.get()) {
4442 status = -EBUSY;
4443 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4444 mActiveTrack->mState = TrackBase::ACTIVE;
4445 }
4446 return status;
4447 }
4448
4449 recordTrack->mState = TrackBase::IDLE;
4450 mActiveTrack = recordTrack;
4451 mLock.unlock();
4452 status_t status = AudioSystem::startInput(mId);
4453 mLock.lock();
4454 if (status != NO_ERROR) {
4455 mActiveTrack.clear();
4456 return status;
4457 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 mRsmpInIndex = mFrameCount;
4459 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004460 if (mResampler != NULL) {
4461 mResampler->reset();
4462 }
4463 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004464 // signal thread to start
4465 LOGV("Signal record thread");
4466 mWaitWorkCV.signal();
4467 // do not wait for mStartStopCond if exiting
4468 if (mExiting) {
4469 mActiveTrack.clear();
4470 status = INVALID_OPERATION;
4471 goto startError;
4472 }
4473 mStartStopCond.wait(mLock);
4474 if (mActiveTrack == 0) {
4475 LOGV("Record failed to start");
4476 status = BAD_VALUE;
4477 goto startError;
4478 }
4479 LOGV("Record started OK");
4480 return status;
4481 }
4482startError:
4483 AudioSystem::stopInput(mId);
4484 return status;
4485}
4486
4487void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4488 LOGV("RecordThread::stop");
4489 sp <ThreadBase> strongMe = this;
4490 {
4491 AutoMutex lock(&mLock);
4492 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4493 mActiveTrack->mState = TrackBase::PAUSING;
4494 // do not wait for mStartStopCond if exiting
4495 if (mExiting) {
4496 return;
4497 }
4498 mStartStopCond.wait(mLock);
4499 // if we have been restarted, recordTrack == mActiveTrack.get() here
4500 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4501 mLock.unlock();
4502 AudioSystem::stopInput(mId);
4503 mLock.lock();
4504 LOGV("Record stopped OK");
4505 }
4506 }
4507 }
4508}
4509
4510status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4511{
4512 const size_t SIZE = 256;
4513 char buffer[SIZE];
4514 String8 result;
4515 pid_t pid = 0;
4516
4517 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4518 result.append(buffer);
4519
4520 if (mActiveTrack != 0) {
4521 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004522 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 mActiveTrack->dump(buffer, SIZE);
4524 result.append(buffer);
4525
4526 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4527 result.append(buffer);
4528 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4529 result.append(buffer);
4530 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4531 result.append(buffer);
4532 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4533 result.append(buffer);
4534 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4535 result.append(buffer);
4536
4537
4538 } else {
4539 result.append("No record client\n");
4540 }
4541 write(fd, result.string(), result.size());
4542
4543 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004544 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004545
4546 return NO_ERROR;
4547}
4548
4549status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4550{
4551 size_t framesReq = buffer->frameCount;
4552 size_t framesReady = mFrameCount - mRsmpInIndex;
4553 int channelCount;
4554
4555 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004556 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004557 if (mBytesRead < 0) {
4558 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4559 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4560 // Force input into standby so that it tries to
4561 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004562 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004563 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 }
4565 buffer->raw = 0;
4566 buffer->frameCount = 0;
4567 return NOT_ENOUGH_DATA;
4568 }
4569 mRsmpInIndex = 0;
4570 framesReady = mFrameCount;
4571 }
4572
4573 if (framesReq > framesReady) {
4574 framesReq = framesReady;
4575 }
4576
4577 if (mChannelCount == 1 && mReqChannelCount == 2) {
4578 channelCount = 1;
4579 } else {
4580 channelCount = 2;
4581 }
4582 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4583 buffer->frameCount = framesReq;
4584 return NO_ERROR;
4585}
4586
4587void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4588{
4589 mRsmpInIndex += buffer->frameCount;
4590 buffer->frameCount = 0;
4591}
4592
4593bool AudioFlinger::RecordThread::checkForNewParameters_l()
4594{
4595 bool reconfig = false;
4596
4597 while (!mNewParameters.isEmpty()) {
4598 status_t status = NO_ERROR;
4599 String8 keyValuePair = mNewParameters[0];
4600 AudioParameter param = AudioParameter(keyValuePair);
4601 int value;
4602 int reqFormat = mFormat;
4603 int reqSamplingRate = mReqSampleRate;
4604 int reqChannelCount = mReqChannelCount;
4605
4606 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4607 reqSamplingRate = value;
4608 reconfig = true;
4609 }
4610 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4611 reqFormat = value;
4612 reconfig = true;
4613 }
4614 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004615 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 reconfig = true;
4617 }
4618 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4619 // do not accept frame count changes if tracks are open as the track buffer
4620 // size depends on frame count and correct behavior would not be garantied
4621 // if frame count is changed after track creation
4622 if (mActiveTrack != 0) {
4623 status = INVALID_OPERATION;
4624 } else {
4625 reconfig = true;
4626 }
4627 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004628 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4629 // forward device change to effects that have requested to be
4630 // aware of attached audio device.
4631 for (size_t i = 0; i < mEffectChains.size(); i++) {
4632 mEffectChains[i]->setDevice_l(value);
4633 }
4634 // store input device and output device but do not forward output device to audio HAL.
4635 // Note that status is ignored by the caller for output device
4636 // (see AudioFlinger::setParameters()
4637 if (value & AUDIO_DEVICE_OUT_ALL) {
4638 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4639 status = BAD_VALUE;
4640 } else {
4641 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004642 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4643 if (mTrack != NULL) {
4644 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004645 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004646 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4647 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4648 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004649 }
4650 mDevice |= (uint32_t)value;
4651 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004652 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004653 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004654 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004655 mInput->stream->common.standby(&mInput->stream->common);
4656 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 }
4658 if (reconfig) {
4659 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004660 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004661 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004662 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4663 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004664 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 status = NO_ERROR;
4666 }
4667 if (status == NO_ERROR) {
4668 readInputParameters();
4669 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4670 }
4671 }
4672 }
4673
4674 mNewParameters.removeAt(0);
4675
4676 mParamStatus = status;
4677 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004678 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4679 // already timed out waiting for the status and will never signal the condition.
4680 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004681 }
4682 return reconfig;
4683}
4684
4685String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4686{
Dima Zavinfce7a472011-04-19 22:30:36 -07004687 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004688 String8 out_s8 = String8();
4689
4690 Mutex::Autolock _l(mLock);
4691 if (initCheck() != NO_ERROR) {
4692 return out_s8;
4693 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004694
Dima Zavin799a70e2011-04-18 16:57:27 -07004695 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004696 out_s8 = String8(s);
4697 free(s);
4698 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004699}
4700
4701void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4702 AudioSystem::OutputDescriptor desc;
4703 void *param2 = 0;
4704
4705 switch (event) {
4706 case AudioSystem::INPUT_OPENED:
4707 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004708 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709 desc.samplingRate = mSampleRate;
4710 desc.format = mFormat;
4711 desc.frameCount = mFrameCount;
4712 desc.latency = 0;
4713 param2 = &desc;
4714 break;
4715
4716 case AudioSystem::INPUT_CLOSED:
4717 default:
4718 break;
4719 }
4720 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4721}
4722
4723void AudioFlinger::RecordThread::readInputParameters()
4724{
4725 if (mRsmpInBuffer) delete mRsmpInBuffer;
4726 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4727 if (mResampler) delete mResampler;
4728 mResampler = 0;
4729
Dima Zavin799a70e2011-04-18 16:57:27 -07004730 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004731 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4732 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004733 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4734 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4735 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 mFrameCount = mInputBytes / mFrameSize;
4737 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4738
4739 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4740 {
4741 int channelCount;
4742 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4743 // stereo to mono post process as the resampler always outputs stereo.
4744 if (mChannelCount == 1 && mReqChannelCount == 2) {
4745 channelCount = 1;
4746 } else {
4747 channelCount = 2;
4748 }
4749 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4750 mResampler->setSampleRate(mSampleRate);
4751 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4752 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4753
4754 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4755 if (mChannelCount == 1 && mReqChannelCount == 1) {
4756 mFrameCount >>= 1;
4757 }
4758
4759 }
4760 mRsmpInIndex = mFrameCount;
4761}
4762
4763unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4764{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004765 Mutex::Autolock _l(mLock);
4766 if (initCheck() != NO_ERROR) {
4767 return 0;
4768 }
4769
Dima Zavin799a70e2011-04-18 16:57:27 -07004770 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771}
4772
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004773uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4774{
4775 Mutex::Autolock _l(mLock);
4776 uint32_t result = 0;
4777 if (getEffectChain_l(sessionId) != 0) {
4778 result = EFFECT_SESSION;
4779 }
4780
4781 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4782 result |= TRACK_SESSION;
4783 }
4784
4785 return result;
4786}
4787
Eric Laurent59bd0da2011-08-01 09:52:20 -07004788AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4789{
4790 Mutex::Autolock _l(mLock);
4791 return mTrack;
4792}
4793
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004794AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4795{
4796 Mutex::Autolock _l(mLock);
4797 return mInput;
4798}
4799
4800AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4801{
4802 Mutex::Autolock _l(mLock);
4803 AudioStreamIn *input = mInput;
4804 mInput = NULL;
4805 return input;
4806}
4807
4808// this method must always be called either with ThreadBase mLock held or inside the thread loop
4809audio_stream_t* AudioFlinger::RecordThread::stream()
4810{
4811 if (mInput == NULL) {
4812 return NULL;
4813 }
4814 return &mInput->stream->common;
4815}
4816
4817
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818// ----------------------------------------------------------------------------
4819
4820int AudioFlinger::openOutput(uint32_t *pDevices,
4821 uint32_t *pSamplingRate,
4822 uint32_t *pFormat,
4823 uint32_t *pChannels,
4824 uint32_t *pLatencyMs,
4825 uint32_t flags)
4826{
4827 status_t status;
4828 PlaybackThread *thread = NULL;
4829 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4830 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4831 uint32_t format = pFormat ? *pFormat : 0;
4832 uint32_t channels = pChannels ? *pChannels : 0;
4833 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004834 audio_stream_out_t *outStream;
4835 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004836
4837 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4838 pDevices ? *pDevices : 0,
4839 samplingRate,
4840 format,
4841 channels,
4842 flags);
4843
4844 if (pDevices == NULL || *pDevices == 0) {
4845 return 0;
4846 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004847
Mathias Agopian65ab4712010-07-14 17:59:35 -07004848 Mutex::Autolock _l(mLock);
4849
Dima Zavin799a70e2011-04-18 16:57:27 -07004850 outHwDev = findSuitableHwDev_l(*pDevices);
4851 if (outHwDev == NULL)
4852 return 0;
4853
4854 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4855 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004856 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004857 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004858 samplingRate,
4859 format,
4860 channels,
4861 status);
4862
4863 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004864 if (outStream != NULL) {
4865 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004866 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004867
Dima Zavinfce7a472011-04-19 22:30:36 -07004868 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4869 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4870 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004871 thread = new DirectOutputThread(this, output, id, *pDevices);
4872 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4873 } else {
4874 thread = new MixerThread(this, output, id, *pDevices);
4875 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004876 }
4877 mPlaybackThreads.add(id, thread);
4878
4879 if (pSamplingRate) *pSamplingRate = samplingRate;
4880 if (pFormat) *pFormat = format;
4881 if (pChannels) *pChannels = channels;
4882 if (pLatencyMs) *pLatencyMs = thread->latency();
4883
4884 // notify client processes of the new output creation
4885 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4886 return id;
4887 }
4888
4889 return 0;
4890}
4891
4892int AudioFlinger::openDuplicateOutput(int output1, int output2)
4893{
4894 Mutex::Autolock _l(mLock);
4895 MixerThread *thread1 = checkMixerThread_l(output1);
4896 MixerThread *thread2 = checkMixerThread_l(output2);
4897
4898 if (thread1 == NULL || thread2 == NULL) {
4899 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4900 return 0;
4901 }
4902
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004903 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004904 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4905 thread->addOutputTrack(thread2);
4906 mPlaybackThreads.add(id, thread);
4907 // notify client processes of the new output creation
4908 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4909 return id;
4910}
4911
4912status_t AudioFlinger::closeOutput(int output)
4913{
4914 // keep strong reference on the playback thread so that
4915 // it is not destroyed while exit() is executed
4916 sp <PlaybackThread> thread;
4917 {
4918 Mutex::Autolock _l(mLock);
4919 thread = checkPlaybackThread_l(output);
4920 if (thread == NULL) {
4921 return BAD_VALUE;
4922 }
4923
4924 LOGV("closeOutput() %d", output);
4925
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004926 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004928 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004929 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4930 dupThread->removeOutputTrack((MixerThread *)thread.get());
4931 }
4932 }
4933 }
4934 void *param2 = 0;
4935 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4936 mPlaybackThreads.removeItem(output);
4937 }
4938 thread->exit();
4939
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004940 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004941 AudioStreamOut *out = thread->clearOutput();
4942 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07004943 out->hwDev->close_output_stream(out->hwDev, out->stream);
4944 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945 }
4946 return NO_ERROR;
4947}
4948
4949status_t AudioFlinger::suspendOutput(int output)
4950{
4951 Mutex::Autolock _l(mLock);
4952 PlaybackThread *thread = checkPlaybackThread_l(output);
4953
4954 if (thread == NULL) {
4955 return BAD_VALUE;
4956 }
4957
4958 LOGV("suspendOutput() %d", output);
4959 thread->suspend();
4960
4961 return NO_ERROR;
4962}
4963
4964status_t AudioFlinger::restoreOutput(int output)
4965{
4966 Mutex::Autolock _l(mLock);
4967 PlaybackThread *thread = checkPlaybackThread_l(output);
4968
4969 if (thread == NULL) {
4970 return BAD_VALUE;
4971 }
4972
4973 LOGV("restoreOutput() %d", output);
4974
4975 thread->restore();
4976
4977 return NO_ERROR;
4978}
4979
4980int AudioFlinger::openInput(uint32_t *pDevices,
4981 uint32_t *pSamplingRate,
4982 uint32_t *pFormat,
4983 uint32_t *pChannels,
4984 uint32_t acoustics)
4985{
4986 status_t status;
4987 RecordThread *thread = NULL;
4988 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4989 uint32_t format = pFormat ? *pFormat : 0;
4990 uint32_t channels = pChannels ? *pChannels : 0;
4991 uint32_t reqSamplingRate = samplingRate;
4992 uint32_t reqFormat = format;
4993 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004994 audio_stream_in_t *inStream;
4995 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996
4997 if (pDevices == NULL || *pDevices == 0) {
4998 return 0;
4999 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005000
Mathias Agopian65ab4712010-07-14 17:59:35 -07005001 Mutex::Autolock _l(mLock);
5002
Dima Zavin799a70e2011-04-18 16:57:27 -07005003 inHwDev = findSuitableHwDev_l(*pDevices);
5004 if (inHwDev == NULL)
5005 return 0;
5006
5007 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5008 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005009 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005010 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005012 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 samplingRate,
5014 format,
5015 channels,
5016 acoustics,
5017 status);
5018
5019 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5020 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5021 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005022 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005023 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005024 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005025 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005026 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005027 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5028 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005029 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005030 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005031 }
5032
Dima Zavin799a70e2011-04-18 16:57:27 -07005033 if (inStream != NULL) {
5034 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5035
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005036 int id = nextUniqueId();
5037 // Start record thread
5038 // RecorThread require both input and output device indication to forward to audio
5039 // pre processing modules
5040 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5041 thread = new RecordThread(this,
5042 input,
5043 reqSamplingRate,
5044 reqChannels,
5045 id,
5046 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047 mRecordThreads.add(id, thread);
5048 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5049 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5050 if (pFormat) *pFormat = format;
5051 if (pChannels) *pChannels = reqChannels;
5052
Dima Zavin799a70e2011-04-18 16:57:27 -07005053 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005054
5055 // notify client processes of the new input creation
5056 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5057 return id;
5058 }
5059
5060 return 0;
5061}
5062
5063status_t AudioFlinger::closeInput(int input)
5064{
5065 // keep strong reference on the record thread so that
5066 // it is not destroyed while exit() is executed
5067 sp <RecordThread> thread;
5068 {
5069 Mutex::Autolock _l(mLock);
5070 thread = checkRecordThread_l(input);
5071 if (thread == NULL) {
5072 return BAD_VALUE;
5073 }
5074
5075 LOGV("closeInput() %d", input);
5076 void *param2 = 0;
5077 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5078 mRecordThreads.removeItem(input);
5079 }
5080 thread->exit();
5081
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005082 AudioStreamIn *in = thread->clearInput();
5083 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 in->hwDev->close_input_stream(in->hwDev, in->stream);
5085 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086
5087 return NO_ERROR;
5088}
5089
5090status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5091{
5092 Mutex::Autolock _l(mLock);
5093 MixerThread *dstThread = checkMixerThread_l(output);
5094 if (dstThread == NULL) {
5095 LOGW("setStreamOutput() bad output id %d", output);
5096 return BAD_VALUE;
5097 }
5098
5099 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5100 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5101
Eric Laurent9f6530f2011-08-30 10:18:54 -07005102 dstThread->setStreamValid(stream, true);
5103
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5105 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5106 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005107 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005109 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 }
Eric Laurentde070132010-07-13 04:45:46 -07005112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113
5114 return NO_ERROR;
5115}
5116
5117
5118int AudioFlinger::newAudioSessionId()
5119{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005120 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005121}
5122
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005123void AudioFlinger::acquireAudioSessionId(int audioSession)
5124{
5125 Mutex::Autolock _l(mLock);
5126 int caller = IPCThreadState::self()->getCallingPid();
5127 LOGV("acquiring %d from %d", audioSession, caller);
5128 int num = mAudioSessionRefs.size();
5129 for (int i = 0; i< num; i++) {
5130 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5131 if (ref->sessionid == audioSession && ref->pid == caller) {
5132 ref->cnt++;
5133 LOGV(" incremented refcount to %d", ref->cnt);
5134 return;
5135 }
5136 }
5137 AudioSessionRef *ref = new AudioSessionRef();
5138 ref->sessionid = audioSession;
5139 ref->pid = caller;
5140 ref->cnt = 1;
5141 mAudioSessionRefs.push(ref);
5142 LOGV(" added new entry for %d", ref->sessionid);
5143}
5144
5145void AudioFlinger::releaseAudioSessionId(int audioSession)
5146{
5147 Mutex::Autolock _l(mLock);
5148 int caller = IPCThreadState::self()->getCallingPid();
5149 LOGV("releasing %d from %d", audioSession, caller);
5150 int num = mAudioSessionRefs.size();
5151 for (int i = 0; i< num; i++) {
5152 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5153 if (ref->sessionid == audioSession && ref->pid == caller) {
5154 ref->cnt--;
5155 LOGV(" decremented refcount to %d", ref->cnt);
5156 if (ref->cnt == 0) {
5157 mAudioSessionRefs.removeAt(i);
5158 delete ref;
5159 purgeStaleEffects_l();
5160 }
5161 return;
5162 }
5163 }
5164 LOGW("session id %d not found for pid %d", audioSession, caller);
5165}
5166
5167void AudioFlinger::purgeStaleEffects_l() {
5168
5169 LOGV("purging stale effects");
5170
5171 Vector< sp<EffectChain> > chains;
5172
5173 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5174 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5175 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5176 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005177 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5178 chains.push(ec);
5179 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005180 }
5181 }
5182 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5183 sp<RecordThread> t = mRecordThreads.valueAt(i);
5184 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5185 sp<EffectChain> ec = t->mEffectChains[j];
5186 chains.push(ec);
5187 }
5188 }
5189
5190 for (size_t i = 0; i < chains.size(); i++) {
5191 sp<EffectChain> ec = chains[i];
5192 int sessionid = ec->sessionId();
5193 sp<ThreadBase> t = ec->mThread.promote();
5194 if (t == 0) {
5195 continue;
5196 }
5197 size_t numsessionrefs = mAudioSessionRefs.size();
5198 bool found = false;
5199 for (size_t k = 0; k < numsessionrefs; k++) {
5200 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5201 if (ref->sessionid == sessionid) {
5202 LOGV(" session %d still exists for %d with %d refs",
5203 sessionid, ref->pid, ref->cnt);
5204 found = true;
5205 break;
5206 }
5207 }
5208 if (!found) {
5209 // remove all effects from the chain
5210 while (ec->mEffects.size()) {
5211 sp<EffectModule> effect = ec->mEffects[0];
5212 effect->unPin();
5213 Mutex::Autolock _l (t->mLock);
5214 t->removeEffect_l(effect);
5215 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5216 sp<EffectHandle> handle = effect->mHandles[j].promote();
5217 if (handle != 0) {
5218 handle->mEffect.clear();
5219 }
5220 }
5221 AudioSystem::unregisterEffect(effect->id());
5222 }
5223 }
5224 }
5225 return;
5226}
5227
Mathias Agopian65ab4712010-07-14 17:59:35 -07005228// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5229AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5230{
5231 PlaybackThread *thread = NULL;
5232 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5233 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5234 }
5235 return thread;
5236}
5237
5238// checkMixerThread_l() must be called with AudioFlinger::mLock held
5239AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5240{
5241 PlaybackThread *thread = checkPlaybackThread_l(output);
5242 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005243 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005244 thread = NULL;
5245 }
5246 }
5247 return (MixerThread *)thread;
5248}
5249
5250// checkRecordThread_l() must be called with AudioFlinger::mLock held
5251AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5252{
5253 RecordThread *thread = NULL;
5254 if (mRecordThreads.indexOfKey(input) >= 0) {
5255 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5256 }
5257 return thread;
5258}
5259
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005260uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005262 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005263}
5264
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005265AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5266{
5267 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5268 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005269 AudioStreamOut *output = thread->getOutput();
5270 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005271 return thread;
5272 }
5273 }
5274 return NULL;
5275}
5276
5277uint32_t AudioFlinger::primaryOutputDevice_l()
5278{
5279 PlaybackThread *thread = primaryPlaybackThread_l();
5280
5281 if (thread == NULL) {
5282 return 0;
5283 }
5284
5285 return thread->device();
5286}
5287
5288
Mathias Agopian65ab4712010-07-14 17:59:35 -07005289// ----------------------------------------------------------------------------
5290// Effect management
5291// ----------------------------------------------------------------------------
5292
5293
Mathias Agopian65ab4712010-07-14 17:59:35 -07005294status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5295{
5296 Mutex::Autolock _l(mLock);
5297 return EffectQueryNumberEffects(numEffects);
5298}
5299
5300status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5301{
5302 Mutex::Autolock _l(mLock);
5303 return EffectQueryEffect(index, descriptor);
5304}
5305
5306status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5307{
5308 Mutex::Autolock _l(mLock);
5309 return EffectGetDescriptor(pUuid, descriptor);
5310}
5311
5312
Mathias Agopian65ab4712010-07-14 17:59:35 -07005313sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5314 effect_descriptor_t *pDesc,
5315 const sp<IEffectClient>& effectClient,
5316 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005317 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005318 int sessionId,
5319 status_t *status,
5320 int *id,
5321 int *enabled)
5322{
5323 status_t lStatus = NO_ERROR;
5324 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 effect_descriptor_t desc;
5326 sp<Client> client;
5327 wp<Client> wclient;
5328
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005329 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5330 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331
5332 if (pDesc == NULL) {
5333 lStatus = BAD_VALUE;
5334 goto Exit;
5335 }
5336
Eric Laurent84e9a102010-09-23 16:10:16 -07005337 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005338 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005339 lStatus = PERMISSION_DENIED;
5340 goto Exit;
5341 }
5342
Dima Zavinfce7a472011-04-19 22:30:36 -07005343 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005344 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005345 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005346 lStatus = PERMISSION_DENIED;
5347 goto Exit;
5348 }
5349
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005350 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005351 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005352 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005353 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005354 lStatus = BAD_VALUE;
5355 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005356 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005357 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005358 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005359 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005360 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005361 }
5362 }
5363
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 {
5365 Mutex::Autolock _l(mLock);
5366
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367
5368 if (!EffectIsNullUuid(&pDesc->uuid)) {
5369 // if uuid is specified, request effect descriptor
5370 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5371 if (lStatus < 0) {
5372 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5373 goto Exit;
5374 }
5375 } else {
5376 // if uuid is not specified, look for an available implementation
5377 // of the required type in effect factory
5378 if (EffectIsNullUuid(&pDesc->type)) {
5379 LOGW("createEffect() no effect type");
5380 lStatus = BAD_VALUE;
5381 goto Exit;
5382 }
5383 uint32_t numEffects = 0;
5384 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005385 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005386 bool found = false;
5387
5388 lStatus = EffectQueryNumberEffects(&numEffects);
5389 if (lStatus < 0) {
5390 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5391 goto Exit;
5392 }
5393 for (uint32_t i = 0; i < numEffects; i++) {
5394 lStatus = EffectQueryEffect(i, &desc);
5395 if (lStatus < 0) {
5396 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5397 continue;
5398 }
5399 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5400 // If matching type found save effect descriptor. If the session is
5401 // 0 and the effect is not auxiliary, continue enumeration in case
5402 // an auxiliary version of this effect type is available
5403 found = true;
5404 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5407 break;
5408 }
5409 }
5410 }
5411 if (!found) {
5412 lStatus = BAD_VALUE;
5413 LOGW("createEffect() effect not found");
5414 goto Exit;
5415 }
5416 // For same effect type, chose auxiliary version over insert version if
5417 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005418 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005419 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5420 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5421 }
5422 }
5423
5424 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005425 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5427 lStatus = INVALID_OPERATION;
5428 goto Exit;
5429 }
5430
Eric Laurent59255e42011-07-27 19:49:51 -07005431 // check recording permission for visualizer
5432 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5433 !recordingAllowed()) {
5434 lStatus = PERMISSION_DENIED;
5435 goto Exit;
5436 }
5437
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 // return effect descriptor
5439 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5440
5441 // If output is not specified try to find a matching audio session ID in one of the
5442 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005443 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5444 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005445 // Note: io is never 0 when creating an effect on an input
5446 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005447 // look for the thread where the specified audio session is present
5448 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5449 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005450 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005451 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005454 if (io == 0) {
5455 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5456 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5457 io = mRecordThreads.keyAt(i);
5458 break;
5459 }
5460 }
5461 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005462 // If no output thread contains the requested session ID, default to
5463 // first output. The effect chain will be moved to the correct output
5464 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005465 if (io == 0 && mPlaybackThreads.size()) {
5466 io = mPlaybackThreads.keyAt(0);
5467 }
5468 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5469 }
5470 ThreadBase *thread = checkRecordThread_l(io);
5471 if (thread == NULL) {
5472 thread = checkPlaybackThread_l(io);
5473 if (thread == NULL) {
5474 LOGE("createEffect() unknown output thread");
5475 lStatus = BAD_VALUE;
5476 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005479
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 wclient = mClients.valueFor(pid);
5481
5482 if (wclient != NULL) {
5483 client = wclient.promote();
5484 } else {
5485 client = new Client(this, pid);
5486 mClients.add(pid, client);
5487 }
5488
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005489 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005490 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5491 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 if (handle != 0 && id != NULL) {
5493 *id = handle->id();
5494 }
5495 }
5496
5497Exit:
5498 if(status) {
5499 *status = lStatus;
5500 }
5501 return handle;
5502}
5503
Eric Laurent59255e42011-07-27 19:49:51 -07005504status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005505{
5506 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005507 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005508 Mutex::Autolock _l(mLock);
5509 if (srcOutput == dstOutput) {
5510 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5511 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512 }
Eric Laurentde070132010-07-13 04:45:46 -07005513 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5514 if (srcThread == NULL) {
5515 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5516 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517 }
Eric Laurentde070132010-07-13 04:45:46 -07005518 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5519 if (dstThread == NULL) {
5520 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5521 return BAD_VALUE;
5522 }
5523
5524 Mutex::Autolock _dl(dstThread->mLock);
5525 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005526 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005527
Mathias Agopian65ab4712010-07-14 17:59:35 -07005528 return NO_ERROR;
5529}
5530
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005531// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005532status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005533 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005534 AudioFlinger::PlaybackThread *dstThread,
5535 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005536{
5537 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005538 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005539
Eric Laurent59255e42011-07-27 19:49:51 -07005540 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005541 if (chain == 0) {
5542 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005543 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005544 return INVALID_OPERATION;
5545 }
5546
Eric Laurent39e94f82010-07-28 01:32:47 -07005547 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005548 // so that a new chain is created with correct parameters when first effect is added. This is
5549 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5550 // removed.
5551 srcThread->removeEffectChain_l(chain);
5552
5553 // transfer all effects one by one so that new effect chain is created on new thread with
5554 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005555 int dstOutput = dstThread->id();
5556 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005557 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005558 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5559 while (effect != 0) {
5560 srcThread->removeEffect_l(effect);
5561 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07005562 // if the move request is not received from audio policy manager, the effect must be
5563 // re-registered with the new strategy and output
5564 if (dstChain == 0) {
5565 dstChain = effect->chain().promote();
5566 if (dstChain == 0) {
5567 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5568 srcThread->addEffect_l(effect);
5569 return NO_INIT;
5570 }
5571 strategy = dstChain->strategy();
5572 }
5573 if (reRegister) {
5574 AudioSystem::unregisterEffect(effect->id());
5575 AudioSystem::registerEffect(&effect->desc(),
5576 dstOutput,
5577 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005578 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005579 effect->id());
5580 }
Eric Laurentde070132010-07-13 04:45:46 -07005581 effect = chain->getEffectFromId_l(0);
5582 }
5583
5584 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585}
5586
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005587
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005589sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 const sp<AudioFlinger::Client>& client,
5591 const sp<IEffectClient>& effectClient,
5592 int32_t priority,
5593 int sessionId,
5594 effect_descriptor_t *desc,
5595 int *enabled,
5596 status_t *status
5597 )
5598{
5599 sp<EffectModule> effect;
5600 sp<EffectHandle> handle;
5601 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005602 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005603 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005604 bool effectCreated = false;
5605 bool effectRegistered = false;
5606
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005607 lStatus = initCheck();
5608 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610 goto Exit;
5611 }
5612
5613 // Do not allow effects with session ID 0 on direct output or duplicating threads
5614 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005615 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005616 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5617 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 lStatus = BAD_VALUE;
5619 goto Exit;
5620 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005621 // Only Pre processor effects are allowed on input threads and only on input threads
5622 if ((mType == RECORD &&
5623 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5624 (mType != RECORD &&
5625 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5626 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5627 desc->name, desc->flags, mType);
5628 lStatus = BAD_VALUE;
5629 goto Exit;
5630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631
5632 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5633
5634 { // scope for mLock
5635 Mutex::Autolock _l(mLock);
5636
5637 // check for existing effect chain with the requested audio session
5638 chain = getEffectChain_l(sessionId);
5639 if (chain == 0) {
5640 // create a new chain for this session
5641 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5642 chain = new EffectChain(this, sessionId);
5643 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005644 chain->setStrategy(getStrategyForSession_l(sessionId));
5645 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005647 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005648 }
5649
5650 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5651
5652 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005653 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005655 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 if (lStatus != NO_ERROR) {
5657 goto Exit;
5658 }
5659 effectRegistered = true;
5660 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005661 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 lStatus = effect->status();
5663 if (lStatus != NO_ERROR) {
5664 goto Exit;
5665 }
Eric Laurentcab11242010-07-15 12:50:15 -07005666 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 if (lStatus != NO_ERROR) {
5668 goto Exit;
5669 }
5670 effectCreated = true;
5671
5672 effect->setDevice(mDevice);
5673 effect->setMode(mAudioFlinger->getMode());
5674 }
5675 // create effect handle and connect it to effect module
5676 handle = new EffectHandle(effect, client, effectClient, priority);
5677 lStatus = effect->addHandle(handle);
5678 if (enabled) {
5679 *enabled = (int)effect->isEnabled();
5680 }
5681 }
5682
5683Exit:
5684 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005685 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005687 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 }
5689 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005690 AudioSystem::unregisterEffect(effect->id());
5691 }
5692 if (chainCreated) {
5693 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 }
5695 handle.clear();
5696 }
5697
5698 if(status) {
5699 *status = lStatus;
5700 }
5701 return handle;
5702}
5703
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005704sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5705{
5706 sp<EffectModule> effect;
5707
5708 sp<EffectChain> chain = getEffectChain_l(sessionId);
5709 if (chain != 0) {
5710 effect = chain->getEffectFromId_l(effectId);
5711 }
5712 return effect;
5713}
5714
Eric Laurentde070132010-07-13 04:45:46 -07005715// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5716// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005717status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005718{
5719 // check for existing effect chain with the requested audio session
5720 int sessionId = effect->sessionId();
5721 sp<EffectChain> chain = getEffectChain_l(sessionId);
5722 bool chainCreated = false;
5723
5724 if (chain == 0) {
5725 // create a new chain for this session
5726 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5727 chain = new EffectChain(this, sessionId);
5728 addEffectChain_l(chain);
5729 chain->setStrategy(getStrategyForSession_l(sessionId));
5730 chainCreated = true;
5731 }
5732 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5733
5734 if (chain->getEffectFromId_l(effect->id()) != 0) {
5735 LOGW("addEffect_l() %p effect %s already present in chain %p",
5736 this, effect->desc().name, chain.get());
5737 return BAD_VALUE;
5738 }
5739
5740 status_t status = chain->addEffect_l(effect);
5741 if (status != NO_ERROR) {
5742 if (chainCreated) {
5743 removeEffectChain_l(chain);
5744 }
5745 return status;
5746 }
5747
5748 effect->setDevice(mDevice);
5749 effect->setMode(mAudioFlinger->getMode());
5750 return NO_ERROR;
5751}
5752
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005753void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005754
5755 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005757 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5758 detachAuxEffect_l(effect->id());
5759 }
5760
5761 sp<EffectChain> chain = effect->chain().promote();
5762 if (chain != 0) {
5763 // remove effect chain if removing last effect
5764 if (chain->removeEffect_l(effect) == 0) {
5765 removeEffectChain_l(chain);
5766 }
5767 } else {
5768 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5769 }
5770}
5771
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005772void AudioFlinger::ThreadBase::lockEffectChains_l(
5773 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5774{
5775 effectChains = mEffectChains;
5776 for (size_t i = 0; i < mEffectChains.size(); i++) {
5777 mEffectChains[i]->lock();
5778 }
5779}
5780
5781void AudioFlinger::ThreadBase::unlockEffectChains(
5782 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5783{
5784 for (size_t i = 0; i < effectChains.size(); i++) {
5785 effectChains[i]->unlock();
5786 }
5787}
5788
5789sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5790{
5791 Mutex::Autolock _l(mLock);
5792 return getEffectChain_l(sessionId);
5793}
5794
5795sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5796{
5797 sp<EffectChain> chain;
5798
5799 size_t size = mEffectChains.size();
5800 for (size_t i = 0; i < size; i++) {
5801 if (mEffectChains[i]->sessionId() == sessionId) {
5802 chain = mEffectChains[i];
5803 break;
5804 }
5805 }
5806 return chain;
5807}
5808
5809void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5810{
5811 Mutex::Autolock _l(mLock);
5812 size_t size = mEffectChains.size();
5813 for (size_t i = 0; i < size; i++) {
5814 mEffectChains[i]->setMode_l(mode);
5815 }
5816}
5817
5818void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005819 const wp<EffectHandle>& handle,
5820 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005821
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005823 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005824 // delete the effect module if removing last handle on it
5825 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005826 if (!effect->isPinned() || unpiniflast) {
5827 removeEffect_l(effect);
5828 AudioSystem::unregisterEffect(effect->id());
5829 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005830 }
5831}
5832
5833status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5834{
5835 int session = chain->sessionId();
5836 int16_t *buffer = mMixBuffer;
5837 bool ownsBuffer = false;
5838
5839 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5840 if (session > 0) {
5841 // Only one effect chain can be present in direct output thread and it uses
5842 // the mix buffer as input
5843 if (mType != DIRECT) {
5844 size_t numSamples = mFrameCount * mChannelCount;
5845 buffer = new int16_t[numSamples];
5846 memset(buffer, 0, numSamples * sizeof(int16_t));
5847 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5848 ownsBuffer = true;
5849 }
5850
5851 // Attach all tracks with same session ID to this chain.
5852 for (size_t i = 0; i < mTracks.size(); ++i) {
5853 sp<Track> track = mTracks[i];
5854 if (session == track->sessionId()) {
5855 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5856 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005857 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005858 }
5859 }
5860
5861 // indicate all active tracks in the chain
5862 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5863 sp<Track> track = mActiveTracks[i].promote();
5864 if (track == 0) continue;
5865 if (session == track->sessionId()) {
5866 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005867 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005868 }
5869 }
5870 }
5871
5872 chain->setInBuffer(buffer, ownsBuffer);
5873 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005874 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005875 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005876 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5877 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005878 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005879 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5880 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005881 // Effect chain for other sessions are inserted at beginning of effect
5882 // chains list to be processed before output mix effects. Relative order between other
5883 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 size_t size = mEffectChains.size();
5885 size_t i = 0;
5886 for (i = 0; i < size; i++) {
5887 if (mEffectChains[i]->sessionId() < session) break;
5888 }
5889 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005890 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891
5892 return NO_ERROR;
5893}
5894
5895size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5896{
5897 int session = chain->sessionId();
5898
5899 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5900
5901 for (size_t i = 0; i < mEffectChains.size(); i++) {
5902 if (chain == mEffectChains[i]) {
5903 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005904 // detach all active tracks from the chain
5905 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5906 sp<Track> track = mActiveTracks[i].promote();
5907 if (track == 0) continue;
5908 if (session == track->sessionId()) {
5909 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5910 chain.get(), session);
5911 chain->decActiveTrackCnt();
5912 }
5913 }
5914
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 // detach all tracks with same session ID from this chain
5916 for (size_t i = 0; i < mTracks.size(); ++i) {
5917 sp<Track> track = mTracks[i];
5918 if (session == track->sessionId()) {
5919 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005920 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005921 }
5922 }
Eric Laurentde070132010-07-13 04:45:46 -07005923 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 }
5925 }
5926 return mEffectChains.size();
5927}
5928
Eric Laurentde070132010-07-13 04:45:46 -07005929status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5930 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005931{
5932 Mutex::Autolock _l(mLock);
5933 return attachAuxEffect_l(track, EffectId);
5934}
5935
Eric Laurentde070132010-07-13 04:45:46 -07005936status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5937 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938{
5939 status_t status = NO_ERROR;
5940
5941 if (EffectId == 0) {
5942 track->setAuxBuffer(0, NULL);
5943 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005944 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5945 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005946 if (effect != 0) {
5947 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5948 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5949 } else {
5950 status = INVALID_OPERATION;
5951 }
5952 } else {
5953 status = BAD_VALUE;
5954 }
5955 }
5956 return status;
5957}
5958
5959void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5960{
5961 for (size_t i = 0; i < mTracks.size(); ++i) {
5962 sp<Track> track = mTracks[i];
5963 if (track->auxEffectId() == effectId) {
5964 attachAuxEffect_l(track, 0);
5965 }
5966 }
5967}
5968
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005969status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5970{
5971 // only one chain per input thread
5972 if (mEffectChains.size() != 0) {
5973 return INVALID_OPERATION;
5974 }
5975 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5976
5977 chain->setInBuffer(NULL);
5978 chain->setOutBuffer(NULL);
5979
Eric Laurent59255e42011-07-27 19:49:51 -07005980 checkSuspendOnAddEffectChain_l(chain);
5981
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005982 mEffectChains.add(chain);
5983
5984 return NO_ERROR;
5985}
5986
5987size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5988{
5989 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5990 LOGW_IF(mEffectChains.size() != 1,
5991 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5992 chain.get(), mEffectChains.size(), this);
5993 if (mEffectChains.size() == 1) {
5994 mEffectChains.removeAt(0);
5995 }
5996 return 0;
5997}
5998
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999// ----------------------------------------------------------------------------
6000// EffectModule implementation
6001// ----------------------------------------------------------------------------
6002
6003#undef LOG_TAG
6004#define LOG_TAG "AudioFlinger::EffectModule"
6005
6006AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6007 const wp<AudioFlinger::EffectChain>& chain,
6008 effect_descriptor_t *desc,
6009 int id,
6010 int sessionId)
6011 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006012 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013{
6014 LOGV("Constructor %p", this);
6015 int lStatus;
6016 sp<ThreadBase> thread = mThread.promote();
6017 if (thread == 0) {
6018 return;
6019 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020
6021 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6022
6023 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006024 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006025
6026 if (mStatus != NO_ERROR) {
6027 return;
6028 }
6029 lStatus = init();
6030 if (lStatus < 0) {
6031 mStatus = lStatus;
6032 goto Error;
6033 }
6034
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006035 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6036 mPinned = true;
6037 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6039 return;
6040Error:
6041 EffectRelease(mEffectInterface);
6042 mEffectInterface = NULL;
6043 LOGV("Constructor Error %d", mStatus);
6044}
6045
6046AudioFlinger::EffectModule::~EffectModule()
6047{
6048 LOGV("Destructor %p", this);
6049 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006050 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6051 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6052 sp<ThreadBase> thread = mThread.promote();
6053 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006054 audio_stream_t *stream = thread->stream();
6055 if (stream != NULL) {
6056 stream->remove_audio_effect(stream, mEffectInterface);
6057 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006058 }
6059 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006060 // release effect engine
6061 EffectRelease(mEffectInterface);
6062 }
6063}
6064
6065status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6066{
6067 status_t status;
6068
6069 Mutex::Autolock _l(mLock);
6070 // First handle in mHandles has highest priority and controls the effect module
6071 int priority = handle->priority();
6072 size_t size = mHandles.size();
6073 sp<EffectHandle> h;
6074 size_t i;
6075 for (i = 0; i < size; i++) {
6076 h = mHandles[i].promote();
6077 if (h == 0) continue;
6078 if (h->priority() <= priority) break;
6079 }
6080 // if inserted in first place, move effect control from previous owner to this handle
6081 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006082 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006084 enabled = h->enabled();
6085 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 }
Eric Laurent59255e42011-07-27 19:49:51 -07006087 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006088 status = NO_ERROR;
6089 } else {
6090 status = ALREADY_EXISTS;
6091 }
Eric Laurent59255e42011-07-27 19:49:51 -07006092 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093 mHandles.insertAt(handle, i);
6094 return status;
6095}
6096
6097size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6098{
6099 Mutex::Autolock _l(mLock);
6100 size_t size = mHandles.size();
6101 size_t i;
6102 for (i = 0; i < size; i++) {
6103 if (mHandles[i] == handle) break;
6104 }
6105 if (i == size) {
6106 return size;
6107 }
Eric Laurent59255e42011-07-27 19:49:51 -07006108 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6109
6110 bool enabled = false;
6111 EffectHandle *hdl = handle.unsafe_get();
6112 if (hdl) {
6113 LOGV("removeHandle() unsafe_get OK");
6114 enabled = hdl->enabled();
6115 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 mHandles.removeAt(i);
6117 size = mHandles.size();
6118 // if removed from first place, move effect control from this handle to next in line
6119 if (i == 0 && size != 0) {
6120 sp<EffectHandle> h = mHandles[0].promote();
6121 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006122 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006123 }
6124 }
6125
Eric Laurentec437d82011-07-26 20:54:46 -07006126 // Prevent calls to process() and other functions on effect interface from now on.
6127 // The effect engine will be released by the destructor when the last strong reference on
6128 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006129 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006130 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006131 }
6132
Mathias Agopian65ab4712010-07-14 17:59:35 -07006133 return size;
6134}
6135
Eric Laurent59255e42011-07-27 19:49:51 -07006136sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6137{
6138 Mutex::Autolock _l(mLock);
6139 sp<EffectHandle> handle;
6140 if (mHandles.size() != 0) {
6141 handle = mHandles[0].promote();
6142 }
6143 return handle;
6144}
6145
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006146void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147{
Eric Laurent59255e42011-07-27 19:49:51 -07006148 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149 // keep a strong reference on this EffectModule to avoid calling the
6150 // destructor before we exit
6151 sp<EffectModule> keep(this);
6152 {
6153 sp<ThreadBase> thread = mThread.promote();
6154 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006155 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 }
6157 }
6158}
6159
6160void AudioFlinger::EffectModule::updateState() {
6161 Mutex::Autolock _l(mLock);
6162
6163 switch (mState) {
6164 case RESTART:
6165 reset_l();
6166 // FALL THROUGH
6167
6168 case STARTING:
6169 // clear auxiliary effect input buffer for next accumulation
6170 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6171 memset(mConfig.inputCfg.buffer.raw,
6172 0,
6173 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6174 }
6175 start_l();
6176 mState = ACTIVE;
6177 break;
6178 case STOPPING:
6179 stop_l();
6180 mDisableWaitCnt = mMaxDisableWaitCnt;
6181 mState = STOPPED;
6182 break;
6183 case STOPPED:
6184 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6185 // turn off sequence.
6186 if (--mDisableWaitCnt == 0) {
6187 reset_l();
6188 mState = IDLE;
6189 }
6190 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006191 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 break;
6193 }
6194}
6195
6196void AudioFlinger::EffectModule::process()
6197{
6198 Mutex::Autolock _l(mLock);
6199
Eric Laurentec437d82011-07-26 20:54:46 -07006200 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006201 mConfig.inputCfg.buffer.raw == NULL ||
6202 mConfig.outputCfg.buffer.raw == NULL) {
6203 return;
6204 }
6205
Eric Laurent8f45bd72010-08-31 13:50:07 -07006206 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006207 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6208 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6209 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6210 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006211 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 }
6213
6214 // do the actual processing in the effect engine
6215 int ret = (*mEffectInterface)->process(mEffectInterface,
6216 &mConfig.inputCfg.buffer,
6217 &mConfig.outputCfg.buffer);
6218
6219 // force transition to IDLE state when engine is ready
6220 if (mState == STOPPED && ret == -ENODATA) {
6221 mDisableWaitCnt = 1;
6222 }
6223
6224 // clear auxiliary effect input buffer for next accumulation
6225 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006226 memset(mConfig.inputCfg.buffer.raw, 0,
6227 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 }
6229 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006230 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6231 // If an insert effect is idle and input buffer is different from output buffer,
6232 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006234 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006235 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6236 int16_t *in = mConfig.inputCfg.buffer.s16;
6237 int16_t *out = mConfig.outputCfg.buffer.s16;
6238 for (size_t i = 0; i < frameCnt; i++) {
6239 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006241 }
6242 }
6243}
6244
6245void AudioFlinger::EffectModule::reset_l()
6246{
6247 if (mEffectInterface == NULL) {
6248 return;
6249 }
6250 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6251}
6252
6253status_t AudioFlinger::EffectModule::configure()
6254{
6255 uint32_t channels;
6256 if (mEffectInterface == NULL) {
6257 return NO_INIT;
6258 }
6259
6260 sp<ThreadBase> thread = mThread.promote();
6261 if (thread == 0) {
6262 return DEAD_OBJECT;
6263 }
6264
6265 // TODO: handle configuration of effects replacing track process
6266 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006267 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006269 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006270 }
6271
6272 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006273 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 } else {
6275 mConfig.inputCfg.channels = channels;
6276 }
6277 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006278 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6279 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 mConfig.inputCfg.samplingRate = thread->sampleRate();
6281 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6282 mConfig.inputCfg.bufferProvider.cookie = NULL;
6283 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6284 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6285 mConfig.outputCfg.bufferProvider.cookie = NULL;
6286 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6287 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6288 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6289 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006290 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006291 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 // - in other sessions:
6293 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6294 // other effect: overwrites output buffer: input buffer == output buffer
6295 // Auxiliary effect:
6296 // accumulates in output buffer: input buffer != output buffer
6297 // Therefore: accumulate <=> input buffer != output buffer
6298 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6299 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6300 } else {
6301 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6302 }
6303 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6304 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6305 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6306 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6307
Eric Laurentde070132010-07-13 04:45:46 -07006308 LOGV("configure() %p thread %p buffer %p framecount %d",
6309 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6310
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006312 uint32_t size = sizeof(int);
6313 status_t status = (*mEffectInterface)->command(mEffectInterface,
6314 EFFECT_CMD_CONFIGURE,
6315 sizeof(effect_config_t),
6316 &mConfig,
6317 &size,
6318 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006319 if (status == 0) {
6320 status = cmdStatus;
6321 }
6322
6323 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6324 (1000 * mConfig.outputCfg.buffer.frameCount);
6325
6326 return status;
6327}
6328
6329status_t AudioFlinger::EffectModule::init()
6330{
6331 Mutex::Autolock _l(mLock);
6332 if (mEffectInterface == NULL) {
6333 return NO_INIT;
6334 }
6335 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006336 uint32_t size = sizeof(status_t);
6337 status_t status = (*mEffectInterface)->command(mEffectInterface,
6338 EFFECT_CMD_INIT,
6339 0,
6340 NULL,
6341 &size,
6342 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 if (status == 0) {
6344 status = cmdStatus;
6345 }
6346 return status;
6347}
6348
6349status_t AudioFlinger::EffectModule::start_l()
6350{
6351 if (mEffectInterface == NULL) {
6352 return NO_INIT;
6353 }
6354 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006355 uint32_t size = sizeof(status_t);
6356 status_t status = (*mEffectInterface)->command(mEffectInterface,
6357 EFFECT_CMD_ENABLE,
6358 0,
6359 NULL,
6360 &size,
6361 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006362 if (status == 0) {
6363 status = cmdStatus;
6364 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006365 if (status == 0 &&
6366 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6367 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6368 sp<ThreadBase> thread = mThread.promote();
6369 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006370 audio_stream_t *stream = thread->stream();
6371 if (stream != NULL) {
6372 stream->add_audio_effect(stream, mEffectInterface);
6373 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006374 }
6375 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 return status;
6377}
6378
Eric Laurentec437d82011-07-26 20:54:46 -07006379status_t AudioFlinger::EffectModule::stop()
6380{
6381 Mutex::Autolock _l(mLock);
6382 return stop_l();
6383}
6384
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385status_t AudioFlinger::EffectModule::stop_l()
6386{
6387 if (mEffectInterface == NULL) {
6388 return NO_INIT;
6389 }
6390 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006391 uint32_t size = sizeof(status_t);
6392 status_t status = (*mEffectInterface)->command(mEffectInterface,
6393 EFFECT_CMD_DISABLE,
6394 0,
6395 NULL,
6396 &size,
6397 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 if (status == 0) {
6399 status = cmdStatus;
6400 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006401 if (status == 0 &&
6402 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6403 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6404 sp<ThreadBase> thread = mThread.promote();
6405 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006406 audio_stream_t *stream = thread->stream();
6407 if (stream != NULL) {
6408 stream->remove_audio_effect(stream, mEffectInterface);
6409 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006410 }
6411 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006412 return status;
6413}
6414
Eric Laurent25f43952010-07-28 05:40:18 -07006415status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6416 uint32_t cmdSize,
6417 void *pCmdData,
6418 uint32_t *replySize,
6419 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006420{
6421 Mutex::Autolock _l(mLock);
6422// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6423
Eric Laurentec437d82011-07-26 20:54:46 -07006424 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425 return NO_INIT;
6426 }
Eric Laurent25f43952010-07-28 05:40:18 -07006427 status_t status = (*mEffectInterface)->command(mEffectInterface,
6428 cmdCode,
6429 cmdSize,
6430 pCmdData,
6431 replySize,
6432 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006434 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 for (size_t i = 1; i < mHandles.size(); i++) {
6436 sp<EffectHandle> h = mHandles[i].promote();
6437 if (h != 0) {
6438 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6439 }
6440 }
6441 }
6442 return status;
6443}
6444
6445status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6446{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006447
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 Mutex::Autolock _l(mLock);
6449 LOGV("setEnabled %p enabled %d", this, enabled);
6450
6451 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006452 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6453 if (enabled && status != NO_ERROR) {
6454 return status;
6455 }
6456
Mathias Agopian65ab4712010-07-14 17:59:35 -07006457 switch (mState) {
6458 // going from disabled to enabled
6459 case IDLE:
6460 mState = STARTING;
6461 break;
6462 case STOPPED:
6463 mState = RESTART;
6464 break;
6465 case STOPPING:
6466 mState = ACTIVE;
6467 break;
6468
6469 // going from enabled to disabled
6470 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006471 mState = STOPPED;
6472 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006473 case STARTING:
6474 mState = IDLE;
6475 break;
6476 case ACTIVE:
6477 mState = STOPPING;
6478 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006479 case DESTROYED:
6480 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 }
6482 for (size_t i = 1; i < mHandles.size(); i++) {
6483 sp<EffectHandle> h = mHandles[i].promote();
6484 if (h != 0) {
6485 h->setEnabled(enabled);
6486 }
6487 }
6488 }
6489 return NO_ERROR;
6490}
6491
6492bool AudioFlinger::EffectModule::isEnabled()
6493{
6494 switch (mState) {
6495 case RESTART:
6496 case STARTING:
6497 case ACTIVE:
6498 return true;
6499 case IDLE:
6500 case STOPPING:
6501 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006502 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 default:
6504 return false;
6505 }
6506}
6507
Eric Laurent8f45bd72010-08-31 13:50:07 -07006508bool AudioFlinger::EffectModule::isProcessEnabled()
6509{
6510 switch (mState) {
6511 case RESTART:
6512 case ACTIVE:
6513 case STOPPING:
6514 case STOPPED:
6515 return true;
6516 case IDLE:
6517 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006518 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006519 default:
6520 return false;
6521 }
6522}
6523
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6525{
6526 Mutex::Autolock _l(mLock);
6527 status_t status = NO_ERROR;
6528
6529 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6530 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006531 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006532 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6533 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534 status_t cmdStatus;
6535 uint32_t volume[2];
6536 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006537 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 volume[0] = *left;
6539 volume[1] = *right;
6540 if (controller) {
6541 pVolume = volume;
6542 }
Eric Laurent25f43952010-07-28 05:40:18 -07006543 status = (*mEffectInterface)->command(mEffectInterface,
6544 EFFECT_CMD_SET_VOLUME,
6545 size,
6546 volume,
6547 &size,
6548 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6550 *left = volume[0];
6551 *right = volume[1];
6552 }
6553 }
6554 return status;
6555}
6556
6557status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6558{
6559 Mutex::Autolock _l(mLock);
6560 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006561 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6562 // audio pre processing modules on RecordThread can receive both output and
6563 // input device indication in the same call
6564 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6565 if (dev) {
6566 status_t cmdStatus;
6567 uint32_t size = sizeof(status_t);
6568
6569 status = (*mEffectInterface)->command(mEffectInterface,
6570 EFFECT_CMD_SET_DEVICE,
6571 sizeof(uint32_t),
6572 &dev,
6573 &size,
6574 &cmdStatus);
6575 if (status == NO_ERROR) {
6576 status = cmdStatus;
6577 }
6578 }
6579 dev = device & AUDIO_DEVICE_IN_ALL;
6580 if (dev) {
6581 status_t cmdStatus;
6582 uint32_t size = sizeof(status_t);
6583
6584 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6585 EFFECT_CMD_SET_INPUT_DEVICE,
6586 sizeof(uint32_t),
6587 &dev,
6588 &size,
6589 &cmdStatus);
6590 if (status2 == NO_ERROR) {
6591 status2 = cmdStatus;
6592 }
6593 if (status == NO_ERROR) {
6594 status = status2;
6595 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006596 }
6597 }
6598 return status;
6599}
6600
6601status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6602{
6603 Mutex::Autolock _l(mLock);
6604 status_t status = NO_ERROR;
6605 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006607 uint32_t size = sizeof(status_t);
6608 status = (*mEffectInterface)->command(mEffectInterface,
6609 EFFECT_CMD_SET_AUDIO_MODE,
6610 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006611 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006612 &size,
6613 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 if (status == NO_ERROR) {
6615 status = cmdStatus;
6616 }
6617 }
6618 return status;
6619}
6620
Eric Laurent59255e42011-07-27 19:49:51 -07006621void AudioFlinger::EffectModule::setSuspended(bool suspended)
6622{
6623 Mutex::Autolock _l(mLock);
6624 mSuspended = suspended;
6625}
6626bool AudioFlinger::EffectModule::suspended()
6627{
6628 Mutex::Autolock _l(mLock);
6629 return mSuspended;
6630}
6631
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6633{
6634 const size_t SIZE = 256;
6635 char buffer[SIZE];
6636 String8 result;
6637
6638 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6639 result.append(buffer);
6640
6641 bool locked = tryLock(mLock);
6642 // failed to lock - AudioFlinger is probably deadlocked
6643 if (!locked) {
6644 result.append("\t\tCould not lock Fx mutex:\n");
6645 }
6646
6647 result.append("\t\tSession Status State Engine:\n");
6648 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6649 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6650 result.append(buffer);
6651
6652 result.append("\t\tDescriptor:\n");
6653 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6654 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6655 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6656 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6657 result.append(buffer);
6658 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6659 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6660 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6661 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6662 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006663 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006664 mDescriptor.apiVersion,
6665 mDescriptor.flags);
6666 result.append(buffer);
6667 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6668 mDescriptor.name);
6669 result.append(buffer);
6670 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6671 mDescriptor.implementor);
6672 result.append(buffer);
6673
6674 result.append("\t\t- Input configuration:\n");
6675 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6676 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6677 (uint32_t)mConfig.inputCfg.buffer.raw,
6678 mConfig.inputCfg.buffer.frameCount,
6679 mConfig.inputCfg.samplingRate,
6680 mConfig.inputCfg.channels,
6681 mConfig.inputCfg.format);
6682 result.append(buffer);
6683
6684 result.append("\t\t- Output configuration:\n");
6685 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6686 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6687 (uint32_t)mConfig.outputCfg.buffer.raw,
6688 mConfig.outputCfg.buffer.frameCount,
6689 mConfig.outputCfg.samplingRate,
6690 mConfig.outputCfg.channels,
6691 mConfig.outputCfg.format);
6692 result.append(buffer);
6693
6694 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6695 result.append(buffer);
6696 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6697 for (size_t i = 0; i < mHandles.size(); ++i) {
6698 sp<EffectHandle> handle = mHandles[i].promote();
6699 if (handle != 0) {
6700 handle->dump(buffer, SIZE);
6701 result.append(buffer);
6702 }
6703 }
6704
6705 result.append("\n");
6706
6707 write(fd, result.string(), result.length());
6708
6709 if (locked) {
6710 mLock.unlock();
6711 }
6712
6713 return NO_ERROR;
6714}
6715
6716// ----------------------------------------------------------------------------
6717// EffectHandle implementation
6718// ----------------------------------------------------------------------------
6719
6720#undef LOG_TAG
6721#define LOG_TAG "AudioFlinger::EffectHandle"
6722
6723AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6724 const sp<AudioFlinger::Client>& client,
6725 const sp<IEffectClient>& effectClient,
6726 int32_t priority)
6727 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006728 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006729 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730{
6731 LOGV("constructor %p", this);
6732
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006733 if (client == 0) {
6734 return;
6735 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6737 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6738 if (mCblkMemory != 0) {
6739 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6740
6741 if (mCblk) {
6742 new(mCblk) effect_param_cblk_t();
6743 mBuffer = (uint8_t *)mCblk + bufOffset;
6744 }
6745 } else {
6746 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6747 return;
6748 }
6749}
6750
6751AudioFlinger::EffectHandle::~EffectHandle()
6752{
6753 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006754 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07006755 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756}
6757
6758status_t AudioFlinger::EffectHandle::enable()
6759{
Eric Laurent59255e42011-07-27 19:49:51 -07006760 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 if (!mHasControl) return INVALID_OPERATION;
6762 if (mEffect == 0) return DEAD_OBJECT;
6763
Eric Laurentdb7c0792011-08-10 10:37:50 -07006764 if (mEnabled) {
6765 return NO_ERROR;
6766 }
6767
Eric Laurent59255e42011-07-27 19:49:51 -07006768 mEnabled = true;
6769
6770 sp<ThreadBase> thread = mEffect->thread().promote();
6771 if (thread != 0) {
6772 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6773 }
6774
6775 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6776 if (mEffect->suspended()) {
6777 return NO_ERROR;
6778 }
6779
Eric Laurentdb7c0792011-08-10 10:37:50 -07006780 status_t status = mEffect->setEnabled(true);
6781 if (status != NO_ERROR) {
6782 if (thread != 0) {
6783 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6784 }
6785 mEnabled = false;
6786 }
6787 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788}
6789
6790status_t AudioFlinger::EffectHandle::disable()
6791{
Eric Laurent59255e42011-07-27 19:49:51 -07006792 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006793 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006794 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006795
Eric Laurentdb7c0792011-08-10 10:37:50 -07006796 if (!mEnabled) {
6797 return NO_ERROR;
6798 }
Eric Laurent59255e42011-07-27 19:49:51 -07006799 mEnabled = false;
6800
6801 if (mEffect->suspended()) {
6802 return NO_ERROR;
6803 }
6804
6805 status_t status = mEffect->setEnabled(false);
6806
6807 sp<ThreadBase> thread = mEffect->thread().promote();
6808 if (thread != 0) {
6809 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6810 }
6811
6812 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006813}
6814
6815void AudioFlinger::EffectHandle::disconnect()
6816{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006817 disconnect(true);
6818}
6819
6820void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6821{
6822 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006823 if (mEffect == 0) {
6824 return;
6825 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006826 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006827
Eric Laurentdb7c0792011-08-10 10:37:50 -07006828 if (mEnabled) {
6829 sp<ThreadBase> thread = mEffect->thread().promote();
6830 if (thread != 0) {
6831 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6832 }
Eric Laurent59255e42011-07-27 19:49:51 -07006833 }
6834
Mathias Agopian65ab4712010-07-14 17:59:35 -07006835 // release sp on module => module destructor can be called now
6836 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006838 if (mCblk) {
6839 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6840 }
6841 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6843 mClient.clear();
6844 }
6845}
6846
Eric Laurent25f43952010-07-28 05:40:18 -07006847status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6848 uint32_t cmdSize,
6849 void *pCmdData,
6850 uint32_t *replySize,
6851 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006852{
Eric Laurent25f43952010-07-28 05:40:18 -07006853// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6854// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006855
6856 // only get parameter command is permitted for applications not controlling the effect
6857 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6858 return INVALID_OPERATION;
6859 }
6860 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006861 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006862
6863 // handle commands that are not forwarded transparently to effect engine
6864 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6865 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6866 // no risk to block the whole media server process or mixer threads is we are stuck here
6867 Mutex::Autolock _l(mCblk->lock);
6868 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6869 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6870 mCblk->serverIndex = 0;
6871 mCblk->clientIndex = 0;
6872 return BAD_VALUE;
6873 }
6874 status_t status = NO_ERROR;
6875 while (mCblk->serverIndex < mCblk->clientIndex) {
6876 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006877 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878 int *p = (int *)(mBuffer + mCblk->serverIndex);
6879 int size = *p++;
6880 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6881 LOGW("command(): invalid parameter block size");
6882 break;
6883 }
6884 effect_param_t *param = (effect_param_t *)p;
6885 if (param->psize == 0 || param->vsize == 0) {
6886 LOGW("command(): null parameter or value size");
6887 mCblk->serverIndex += size;
6888 continue;
6889 }
Eric Laurent25f43952010-07-28 05:40:18 -07006890 uint32_t psize = sizeof(effect_param_t) +
6891 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6892 param->vsize;
6893 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6894 psize,
6895 p,
6896 &rsize,
6897 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006898 // stop at first error encountered
6899 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006901 *(int *)pReplyData = reply;
6902 break;
6903 } else if (reply != NO_ERROR) {
6904 *(int *)pReplyData = reply;
6905 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006906 }
6907 mCblk->serverIndex += size;
6908 }
6909 mCblk->serverIndex = 0;
6910 mCblk->clientIndex = 0;
6911 return status;
6912 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006913 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006914 return enable();
6915 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006916 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917 return disable();
6918 }
6919
6920 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6921}
6922
6923sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6924 return mCblkMemory;
6925}
6926
Eric Laurent59255e42011-07-27 19:49:51 -07006927void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928{
6929 LOGV("setControl %p control %d", this, hasControl);
6930
6931 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006932 mEnabled = enabled;
6933
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 if (signal && mEffectClient != 0) {
6935 mEffectClient->controlStatusChanged(hasControl);
6936 }
6937}
6938
Eric Laurent25f43952010-07-28 05:40:18 -07006939void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6940 uint32_t cmdSize,
6941 void *pCmdData,
6942 uint32_t replySize,
6943 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944{
6945 if (mEffectClient != 0) {
6946 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6947 }
6948}
6949
6950
6951
6952void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6953{
6954 if (mEffectClient != 0) {
6955 mEffectClient->enableStatusChanged(enabled);
6956 }
6957}
6958
6959status_t AudioFlinger::EffectHandle::onTransact(
6960 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6961{
6962 return BnEffect::onTransact(code, data, reply, flags);
6963}
6964
6965
6966void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6967{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006968 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006969
6970 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6971 (mClient == NULL) ? getpid() : mClient->pid(),
6972 mPriority,
6973 mHasControl,
6974 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006975 mCblk ? mCblk->clientIndex : 0,
6976 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07006977 );
6978
6979 if (locked) {
6980 mCblk->lock.unlock();
6981 }
6982}
6983
6984#undef LOG_TAG
6985#define LOG_TAG "AudioFlinger::EffectChain"
6986
6987AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6988 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006989 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6990 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6991 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992{
Dima Zavinfce7a472011-04-19 22:30:36 -07006993 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994}
6995
6996AudioFlinger::EffectChain::~EffectChain()
6997{
6998 if (mOwnInBuffer) {
6999 delete mInBuffer;
7000 }
7001
7002}
7003
Eric Laurent59255e42011-07-27 19:49:51 -07007004// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007005sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006{
7007 sp<EffectModule> effect;
7008 size_t size = mEffects.size();
7009
7010 for (size_t i = 0; i < size; i++) {
7011 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7012 effect = mEffects[i];
7013 break;
7014 }
7015 }
7016 return effect;
7017}
7018
Eric Laurent59255e42011-07-27 19:49:51 -07007019// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007020sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021{
7022 sp<EffectModule> effect;
7023 size_t size = mEffects.size();
7024
7025 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007026 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7027 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007028 effect = mEffects[i];
7029 break;
7030 }
7031 }
7032 return effect;
7033}
7034
Eric Laurent59255e42011-07-27 19:49:51 -07007035// getEffectFromType_l() must be called with ThreadBase::mLock held
7036sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7037 const effect_uuid_t *type)
7038{
7039 sp<EffectModule> effect;
7040 size_t size = mEffects.size();
7041
7042 for (size_t i = 0; i < size; i++) {
7043 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7044 effect = mEffects[i];
7045 break;
7046 }
7047 }
7048 return effect;
7049}
7050
Mathias Agopian65ab4712010-07-14 17:59:35 -07007051// Must be called with EffectChain::mLock locked
7052void AudioFlinger::EffectChain::process_l()
7053{
Eric Laurentdac69112010-09-28 14:09:57 -07007054 sp<ThreadBase> thread = mThread.promote();
7055 if (thread == 0) {
7056 LOGW("process_l(): cannot promote mixer thread");
7057 return;
7058 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007059 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7060 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07007061 bool tracksOnSession = false;
7062 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07007063 tracksOnSession = (trackCnt() != 0);
7064 }
7065
7066 // if no track is active, input buffer must be cleared here as the mixer process
7067 // will not do it
7068 if (tracksOnSession &&
7069 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007070 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07007071 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07007072 }
7073
Mathias Agopian65ab4712010-07-14 17:59:35 -07007074 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07007075 // do not process effect if no track is present in same audio session
7076 if (isGlobalSession || tracksOnSession) {
7077 for (size_t i = 0; i < size; i++) {
7078 mEffects[i]->process();
7079 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080 }
7081 for (size_t i = 0; i < size; i++) {
7082 mEffects[i]->updateState();
7083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084}
7085
Eric Laurentcab11242010-07-15 12:50:15 -07007086// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007087status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088{
7089 effect_descriptor_t desc = effect->desc();
7090 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7091
7092 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007093 effect->setChain(this);
7094 sp<ThreadBase> thread = mThread.promote();
7095 if (thread == 0) {
7096 return NO_INIT;
7097 }
7098 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099
7100 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7101 // Auxiliary effects are inserted at the beginning of mEffects vector as
7102 // they are processed first and accumulated in chain input buffer
7103 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007104
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105 // the input buffer for auxiliary effect contains mono samples in
7106 // 32 bit format. This is to avoid saturation in AudoMixer
7107 // accumulation stage. Saturation is done in EffectModule::process() before
7108 // calling the process in effect engine
7109 size_t numSamples = thread->frameCount();
7110 int32_t *buffer = new int32_t[numSamples];
7111 memset(buffer, 0, numSamples * sizeof(int32_t));
7112 effect->setInBuffer((int16_t *)buffer);
7113 // auxiliary effects output samples to chain input buffer for further processing
7114 // by insert effects
7115 effect->setOutBuffer(mInBuffer);
7116 } else {
7117 // Insert effects are inserted at the end of mEffects vector as they are processed
7118 // after track and auxiliary effects.
7119 // Insert effect order as a function of indicated preference:
7120 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7121 // another effect is present
7122 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7123 // last effect claiming first position
7124 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7125 // first effect claiming last position
7126 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7127 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7128 // already present
7129
7130 int size = (int)mEffects.size();
7131 int idx_insert = size;
7132 int idx_insert_first = -1;
7133 int idx_insert_last = -1;
7134
7135 for (int i = 0; i < size; i++) {
7136 effect_descriptor_t d = mEffects[i]->desc();
7137 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7138 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7139 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7140 // check invalid effect chaining combinations
7141 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7142 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007143 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007144 return INVALID_OPERATION;
7145 }
7146 // remember position of first insert effect and by default
7147 // select this as insert position for new effect
7148 if (idx_insert == size) {
7149 idx_insert = i;
7150 }
7151 // remember position of last insert effect claiming
7152 // first position
7153 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7154 idx_insert_first = i;
7155 }
7156 // remember position of first insert effect claiming
7157 // last position
7158 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7159 idx_insert_last == -1) {
7160 idx_insert_last = i;
7161 }
7162 }
7163 }
7164
7165 // modify idx_insert from first position if needed
7166 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7167 if (idx_insert_last != -1) {
7168 idx_insert = idx_insert_last;
7169 } else {
7170 idx_insert = size;
7171 }
7172 } else {
7173 if (idx_insert_first != -1) {
7174 idx_insert = idx_insert_first + 1;
7175 }
7176 }
7177
7178 // always read samples from chain input buffer
7179 effect->setInBuffer(mInBuffer);
7180
7181 // if last effect in the chain, output samples to chain
7182 // output buffer, otherwise to chain input buffer
7183 if (idx_insert == size) {
7184 if (idx_insert != 0) {
7185 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7186 mEffects[idx_insert-1]->configure();
7187 }
7188 effect->setOutBuffer(mOutBuffer);
7189 } else {
7190 effect->setOutBuffer(mInBuffer);
7191 }
7192 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193
Eric Laurentcab11242010-07-15 12:50:15 -07007194 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195 }
7196 effect->configure();
7197 return NO_ERROR;
7198}
7199
Eric Laurentcab11242010-07-15 12:50:15 -07007200// removeEffect_l() must be called with PlaybackThread::mLock held
7201size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007202{
7203 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007204 int size = (int)mEffects.size();
7205 int i;
7206 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7207
7208 for (i = 0; i < size; i++) {
7209 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007210 // calling stop here will remove pre-processing effect from the audio HAL.
7211 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7212 // the middle of a read from audio HAL
7213 mEffects[i]->stop();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007214 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7215 delete[] effect->inBuffer();
7216 } else {
7217 if (i == size - 1 && i != 0) {
7218 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7219 mEffects[i - 1]->configure();
7220 }
7221 }
7222 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007223 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224 break;
7225 }
7226 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007227
7228 return mEffects.size();
7229}
7230
Eric Laurentcab11242010-07-15 12:50:15 -07007231// setDevice_l() must be called with PlaybackThread::mLock held
7232void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007233{
7234 size_t size = mEffects.size();
7235 for (size_t i = 0; i < size; i++) {
7236 mEffects[i]->setDevice(device);
7237 }
7238}
7239
Eric Laurentcab11242010-07-15 12:50:15 -07007240// setMode_l() must be called with PlaybackThread::mLock held
7241void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007242{
7243 size_t size = mEffects.size();
7244 for (size_t i = 0; i < size; i++) {
7245 mEffects[i]->setMode(mode);
7246 }
7247}
7248
Eric Laurentcab11242010-07-15 12:50:15 -07007249// setVolume_l() must be called with PlaybackThread::mLock held
7250bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251{
7252 uint32_t newLeft = *left;
7253 uint32_t newRight = *right;
7254 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007255 int ctrlIdx = -1;
7256 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007257
Eric Laurentcab11242010-07-15 12:50:15 -07007258 // first update volume controller
7259 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007260 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007261 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7262 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007263 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007264 break;
7265 }
7266 }
7267
7268 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007269 if (hasControl) {
7270 *left = mNewLeftVolume;
7271 *right = mNewRightVolume;
7272 }
7273 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007274 }
7275
7276 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007277 mLeftVolume = newLeft;
7278 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007279
7280 // second get volume update from volume controller
7281 if (ctrlIdx >= 0) {
7282 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007283 mNewLeftVolume = newLeft;
7284 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007285 }
7286 // then indicate volume to all other effects in chain.
7287 // Pass altered volume to effects before volume controller
7288 // and requested volume to effects after controller
7289 uint32_t lVol = newLeft;
7290 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007291
Mathias Agopian65ab4712010-07-14 17:59:35 -07007292 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007293 if ((int)i == ctrlIdx) continue;
7294 // this also works for ctrlIdx == -1 when there is no volume controller
7295 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 lVol = *left;
7297 rVol = *right;
7298 }
7299 mEffects[i]->setVolume(&lVol, &rVol, false);
7300 }
7301 *left = newLeft;
7302 *right = newRight;
7303
7304 return hasControl;
7305}
7306
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7308{
7309 const size_t SIZE = 256;
7310 char buffer[SIZE];
7311 String8 result;
7312
7313 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7314 result.append(buffer);
7315
7316 bool locked = tryLock(mLock);
7317 // failed to lock - AudioFlinger is probably deadlocked
7318 if (!locked) {
7319 result.append("\tCould not lock mutex:\n");
7320 }
7321
Eric Laurentcab11242010-07-15 12:50:15 -07007322 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7323 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 mEffects.size(),
7325 (uint32_t)mInBuffer,
7326 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327 mActiveTrackCnt);
7328 result.append(buffer);
7329 write(fd, result.string(), result.size());
7330
7331 for (size_t i = 0; i < mEffects.size(); ++i) {
7332 sp<EffectModule> effect = mEffects[i];
7333 if (effect != 0) {
7334 effect->dump(fd, args);
7335 }
7336 }
7337
7338 if (locked) {
7339 mLock.unlock();
7340 }
7341
7342 return NO_ERROR;
7343}
7344
Eric Laurent59255e42011-07-27 19:49:51 -07007345// must be called with ThreadBase::mLock held
7346void AudioFlinger::EffectChain::setEffectSuspended_l(
7347 const effect_uuid_t *type, bool suspend)
7348{
7349 sp<SuspendedEffectDesc> desc;
7350 // use effect type UUID timelow as key as there is no real risk of identical
7351 // timeLow fields among effect type UUIDs.
7352 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7353 if (suspend) {
7354 if (index >= 0) {
7355 desc = mSuspendedEffects.valueAt(index);
7356 } else {
7357 desc = new SuspendedEffectDesc();
7358 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7359 mSuspendedEffects.add(type->timeLow, desc);
7360 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7361 }
7362 if (desc->mRefCount++ == 0) {
7363 sp<EffectModule> effect = getEffectIfEnabled(type);
7364 if (effect != 0) {
7365 desc->mEffect = effect;
7366 effect->setSuspended(true);
7367 effect->setEnabled(false);
7368 }
7369 }
7370 } else {
7371 if (index < 0) {
7372 return;
7373 }
7374 desc = mSuspendedEffects.valueAt(index);
7375 if (desc->mRefCount <= 0) {
7376 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7377 desc->mRefCount = 1;
7378 }
7379 if (--desc->mRefCount == 0) {
7380 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7381 if (desc->mEffect != 0) {
7382 sp<EffectModule> effect = desc->mEffect.promote();
7383 if (effect != 0) {
7384 effect->setSuspended(false);
7385 sp<EffectHandle> handle = effect->controlHandle();
7386 if (handle != 0) {
7387 effect->setEnabled(handle->enabled());
7388 }
7389 }
7390 desc->mEffect.clear();
7391 }
7392 mSuspendedEffects.removeItemsAt(index);
7393 }
7394 }
7395}
7396
7397// must be called with ThreadBase::mLock held
7398void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7399{
7400 sp<SuspendedEffectDesc> desc;
7401
7402 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7403 if (suspend) {
7404 if (index >= 0) {
7405 desc = mSuspendedEffects.valueAt(index);
7406 } else {
7407 desc = new SuspendedEffectDesc();
7408 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7409 LOGV("setEffectSuspendedAll_l() add entry for 0");
7410 }
7411 if (desc->mRefCount++ == 0) {
7412 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7413 for (size_t i = 0; i < effects.size(); i++) {
7414 setEffectSuspended_l(&effects[i]->desc().type, true);
7415 }
7416 }
7417 } else {
7418 if (index < 0) {
7419 return;
7420 }
7421 desc = mSuspendedEffects.valueAt(index);
7422 if (desc->mRefCount <= 0) {
7423 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7424 desc->mRefCount = 1;
7425 }
7426 if (--desc->mRefCount == 0) {
7427 Vector<const effect_uuid_t *> types;
7428 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7429 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7430 continue;
7431 }
7432 types.add(&mSuspendedEffects.valueAt(i)->mType);
7433 }
7434 for (size_t i = 0; i < types.size(); i++) {
7435 setEffectSuspended_l(types[i], false);
7436 }
7437 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7438 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7439 }
7440 }
7441}
7442
Eric Laurentdb7c0792011-08-10 10:37:50 -07007443bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7444{
7445 // auxiliary effects and visualizer are never suspended on output mix
7446 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7447 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7448 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0))) {
7449 return false;
7450 }
7451 return true;
7452}
7453
Eric Laurent59255e42011-07-27 19:49:51 -07007454Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7455{
7456 Vector< sp<EffectModule> > effects;
7457 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007458 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007459 continue;
7460 }
7461 effects.add(mEffects[i]);
7462 }
7463 return effects;
7464}
7465
7466sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7467 const effect_uuid_t *type)
7468{
7469 sp<EffectModule> effect;
7470 effect = getEffectFromType_l(type);
7471 if (effect != 0 && !effect->isEnabled()) {
7472 effect.clear();
7473 }
7474 return effect;
7475}
7476
7477void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7478 bool enabled)
7479{
7480 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7481 if (enabled) {
7482 if (index < 0) {
7483 // if the effect is not suspend check if all effects are suspended
7484 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7485 if (index < 0) {
7486 return;
7487 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007488 if (!isEffectEligibleForSuspend(effect->desc())) {
7489 return;
7490 }
Eric Laurent59255e42011-07-27 19:49:51 -07007491 setEffectSuspended_l(&effect->desc().type, enabled);
7492 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007493 if (index < 0) {
7494 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7495 return;
7496 }
Eric Laurent59255e42011-07-27 19:49:51 -07007497 }
7498 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7499 effect->desc().type.timeLow);
7500 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7501 // if effect is requested to suspended but was not yet enabled, supend it now.
7502 if (desc->mEffect == 0) {
7503 desc->mEffect = effect;
7504 effect->setEnabled(false);
7505 effect->setSuspended(true);
7506 }
7507 } else {
7508 if (index < 0) {
7509 return;
7510 }
7511 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7512 effect->desc().type.timeLow);
7513 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7514 desc->mEffect.clear();
7515 effect->setSuspended(false);
7516 }
7517}
7518
Mathias Agopian65ab4712010-07-14 17:59:35 -07007519#undef LOG_TAG
7520#define LOG_TAG "AudioFlinger"
7521
7522// ----------------------------------------------------------------------------
7523
7524status_t AudioFlinger::onTransact(
7525 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7526{
7527 return BnAudioFlinger::onTransact(code, data, reply, flags);
7528}
7529
Mathias Agopian65ab4712010-07-14 17:59:35 -07007530}; // namespace android