blob: 01f5a6f433be114305f678d584bbef19300dd07e [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
38
39#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
Mathias Agopian65ab4712010-07-14 17:59:35 -070061// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Eric Laurentde070132010-07-13 04:45:46 -070063
Mathias Agopian65ab4712010-07-14 17:59:35 -070064namespace android {
65
66static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
67static const char* kHardwareLockedString = "Hardware lock is taken\n";
68
69//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
70static const float MAX_GAIN = 4096.0f;
71static const float MAX_GAIN_INT = 0x1000;
72
73// retry counts for buffer fill timeout
74// 50 * ~20msecs = 1 second
75static const int8_t kMaxTrackRetries = 50;
76static const int8_t kMaxTrackStartupRetries = 50;
77// allow less retry attempts on direct output thread.
78// direct outputs can be a scarce resource in audio hardware and should
79// be released as quickly as possible.
80static const int8_t kMaxTrackRetriesDirect = 2;
81
82static const int kDumpLockRetries = 50;
83static const int kDumpLockSleep = 20000;
84
85static const nsecs_t kWarningThrottle = seconds(5);
86
Eric Laurent7c7f10b2011-06-17 21:29:58 -070087// RecordThread loop sleep time upon application overrun or audio HAL read error
88static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent60cd0a02011-09-13 11:40:21 -070090static const nsecs_t kSetParametersTimeout = seconds(2);
91
Mathias Agopian65ab4712010-07-14 17:59:35 -070092// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070095 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
96 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
97 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
98 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070099}
100
101static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
103 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
104 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
105 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106}
107
Gloria Wang9ee159b2011-02-24 14:51:45 -0800108// To collect the amplifier usage
109static void addBatteryData(uint32_t params) {
110 sp<IBinder> binder =
111 defaultServiceManager()->getService(String16("media.player"));
112 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
113 if (service.get() == NULL) {
114 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
115 return;
116 }
117
118 service->addBatteryData(params);
119}
120
Dima Zavin799a70e2011-04-18 16:57:27 -0700121static int load_audio_interface(const char *if_name, const hw_module_t **mod,
122 audio_hw_device_t **dev)
123{
124 int rc;
125
126 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
127 if (rc)
128 goto out;
129
130 rc = audio_hw_device_open(*mod, dev);
131 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
132 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
133 if (rc)
134 goto out;
135
136 return 0;
137
138out:
139 *mod = NULL;
140 *dev = NULL;
141 return rc;
142}
143
144static const char *audio_interfaces[] = {
145 "primary",
146 "a2dp",
147 "usb",
148};
149#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
150
Mathias Agopian65ab4712010-07-14 17:59:35 -0700151// ----------------------------------------------------------------------------
152
153AudioFlinger::AudioFlinger()
154 : BnAudioFlinger(),
Eric Laurent59bd0da2011-08-01 09:52:20 -0700155 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700156 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700158}
159
160void AudioFlinger::onFirstRef()
161{
Dima Zavin799a70e2011-04-18 16:57:27 -0700162 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700163
Eric Laurent93575202011-01-18 18:39:02 -0800164 Mutex::Autolock _l(mLock);
165
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167 mHardwareStatus = AUDIO_HW_IDLE;
168
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
170 const hw_module_t *mod;
171 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700172
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
174 if (rc)
175 continue;
176
177 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
178 mod->name, mod->id);
179 mAudioHwDevs.push(dev);
180
181 if (!mPrimaryHardwareDev) {
182 mPrimaryHardwareDev = dev;
183 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700184 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 }
186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700187
188 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700189
Dima Zavin799a70e2011-04-18 16:57:27 -0700190 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
191 LOGE("Primary audio interface not found");
192 return;
193 }
194
195 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
196 audio_hw_device_t *dev = mAudioHwDevs[i];
197
198 mHardwareStatus = AUDIO_HW_INIT;
199 rc = dev->init_check(dev);
200 if (rc == 0) {
201 AutoMutex lock(mHardwareLock);
202
203 mMode = AUDIO_MODE_NORMAL;
204 mHardwareStatus = AUDIO_HW_SET_MODE;
205 dev->set_mode(dev, mMode);
206 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
207 dev->set_master_volume(dev, 1.0f);
208 mHardwareStatus = AUDIO_HW_IDLE;
209 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700210 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700211}
212
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700213status_t AudioFlinger::initCheck() const
214{
215 Mutex::Autolock _l(mLock);
216 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
217 return NO_INIT;
218 return NO_ERROR;
219}
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221AudioFlinger::~AudioFlinger()
222{
Dima Zavin799a70e2011-04-18 16:57:27 -0700223 int num_devs = mAudioHwDevs.size();
224
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225 while (!mRecordThreads.isEmpty()) {
226 // closeInput() will remove first entry from mRecordThreads
227 closeInput(mRecordThreads.keyAt(0));
228 }
229 while (!mPlaybackThreads.isEmpty()) {
230 // closeOutput() will remove first entry from mPlaybackThreads
231 closeOutput(mPlaybackThreads.keyAt(0));
232 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700233
234 for (int i = 0; i < num_devs; i++) {
235 audio_hw_device_t *dev = mAudioHwDevs[i];
236 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700237 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700238 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700239}
240
Dima Zavin799a70e2011-04-18 16:57:27 -0700241audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
242{
243 /* first matching HW device is returned */
244 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 if ((dev->get_supported_devices(dev) & devices) == devices)
247 return dev;
248 }
249 return NULL;
250}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251
252status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
253{
254 const size_t SIZE = 256;
255 char buffer[SIZE];
256 String8 result;
257
258 result.append("Clients:\n");
259 for (size_t i = 0; i < mClients.size(); ++i) {
260 wp<Client> wClient = mClients.valueAt(i);
261 if (wClient != 0) {
262 sp<Client> client = wClient.promote();
263 if (client != 0) {
264 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
265 result.append(buffer);
266 }
267 }
268 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700269
270 result.append("Global session refs:\n");
271 result.append(" session pid cnt\n");
272 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
273 AudioSessionRef *r = mAudioSessionRefs[i];
274 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
275 result.append(buffer);
276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277 write(fd, result.string(), result.size());
278 return NO_ERROR;
279}
280
281
282status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 int hardwareStatus = mHardwareStatus;
288
289 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
290 result.append(buffer);
291 write(fd, result.string(), result.size());
292 return NO_ERROR;
293}
294
295status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
296{
297 const size_t SIZE = 256;
298 char buffer[SIZE];
299 String8 result;
300 snprintf(buffer, SIZE, "Permission Denial: "
301 "can't dump AudioFlinger from pid=%d, uid=%d\n",
302 IPCThreadState::self()->getCallingPid(),
303 IPCThreadState::self()->getCallingUid());
304 result.append(buffer);
305 write(fd, result.string(), result.size());
306 return NO_ERROR;
307}
308
309static bool tryLock(Mutex& mutex)
310{
311 bool locked = false;
312 for (int i = 0; i < kDumpLockRetries; ++i) {
313 if (mutex.tryLock() == NO_ERROR) {
314 locked = true;
315 break;
316 }
317 usleep(kDumpLockSleep);
318 }
319 return locked;
320}
321
322status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
323{
324 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
325 dumpPermissionDenial(fd, args);
326 } else {
327 // get state of hardware lock
328 bool hardwareLocked = tryLock(mHardwareLock);
329 if (!hardwareLocked) {
330 String8 result(kHardwareLockedString);
331 write(fd, result.string(), result.size());
332 } else {
333 mHardwareLock.unlock();
334 }
335
336 bool locked = tryLock(mLock);
337
338 // failed to lock - AudioFlinger is probably deadlocked
339 if (!locked) {
340 String8 result(kDeadlockedString);
341 write(fd, result.string(), result.size());
342 }
343
344 dumpClients(fd, args);
345 dumpInternals(fd, args);
346
347 // dump playback threads
348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
349 mPlaybackThreads.valueAt(i)->dump(fd, args);
350 }
351
352 // dump record threads
353 for (size_t i = 0; i < mRecordThreads.size(); i++) {
354 mRecordThreads.valueAt(i)->dump(fd, args);
355 }
356
Dima Zavin799a70e2011-04-18 16:57:27 -0700357 // dump all hardware devs
358 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
359 audio_hw_device_t *dev = mAudioHwDevs[i];
360 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700361 }
362 if (locked) mLock.unlock();
363 }
364 return NO_ERROR;
365}
366
367
368// IAudioFlinger interface
369
370
371sp<IAudioTrack> AudioFlinger::createTrack(
372 pid_t pid,
373 int streamType,
374 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700375 uint32_t format,
376 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700377 int frameCount,
378 uint32_t flags,
379 const sp<IMemory>& sharedBuffer,
380 int output,
381 int *sessionId,
382 status_t *status)
383{
384 sp<PlaybackThread::Track> track;
385 sp<TrackHandle> trackHandle;
386 sp<Client> client;
387 wp<Client> wclient;
388 status_t lStatus;
389 int lSessionId;
390
Dima Zavinfce7a472011-04-19 22:30:36 -0700391 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700392 LOGE("invalid stream type");
393 lStatus = BAD_VALUE;
394 goto Exit;
395 }
396
397 {
398 Mutex::Autolock _l(mLock);
399 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700400 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 if (thread == NULL) {
402 LOGE("unknown output thread");
403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
407 wclient = mClients.valueFor(pid);
408
409 if (wclient != NULL) {
410 client = wclient.promote();
411 } else {
412 client = new Client(this, pid);
413 mClients.add(pid, client);
414 }
415
Mathias Agopian65ab4712010-07-14 17:59:35 -0700416 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700417 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700418 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700419 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
420 if (mPlaybackThreads.keyAt(i) != output) {
421 // prevent same audio session on different output threads
422 uint32_t sessions = t->hasAudioSession(*sessionId);
423 if (sessions & PlaybackThread::TRACK_SESSION) {
424 lStatus = BAD_VALUE;
425 goto Exit;
426 }
427 // check if an effect with same session ID is waiting for a track to be created
428 if (sessions & PlaybackThread::EFFECT_SESSION) {
429 effectThread = t.get();
430 }
Eric Laurentde070132010-07-13 04:45:46 -0700431 }
432 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 lSessionId = *sessionId;
434 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700435 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700436 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700437 if (sessionId != NULL) {
438 *sessionId = lSessionId;
439 }
440 }
441 LOGV("createTrack() lSessionId: %d", lSessionId);
442
443 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700444 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700445
446 // move effect chain to this output thread if an effect on same session was waiting
447 // for a track to be created
448 if (lStatus == NO_ERROR && effectThread != NULL) {
449 Mutex::Autolock _dl(thread->mLock);
450 Mutex::Autolock _sl(effectThread->mLock);
451 moveEffectChain_l(lSessionId, effectThread, thread, true);
452 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453 }
454 if (lStatus == NO_ERROR) {
455 trackHandle = new TrackHandle(track);
456 } else {
457 // remove local strong reference to Client before deleting the Track so that the Client
458 // destructor is called by the TrackBase destructor with mLock held
459 client.clear();
460 track.clear();
461 }
462
463Exit:
464 if(status) {
465 *status = lStatus;
466 }
467 return trackHandle;
468}
469
470uint32_t AudioFlinger::sampleRate(int output) const
471{
472 Mutex::Autolock _l(mLock);
473 PlaybackThread *thread = checkPlaybackThread_l(output);
474 if (thread == NULL) {
475 LOGW("sampleRate() unknown thread %d", output);
476 return 0;
477 }
478 return thread->sampleRate();
479}
480
481int AudioFlinger::channelCount(int output) const
482{
483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
486 LOGW("channelCount() unknown thread %d", output);
487 return 0;
488 }
489 return thread->channelCount();
490}
491
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700492uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700493{
494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
497 LOGW("format() unknown thread %d", output);
498 return 0;
499 }
500 return thread->format();
501}
502
503size_t AudioFlinger::frameCount(int output) const
504{
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
508 LOGW("frameCount() unknown thread %d", output);
509 return 0;
510 }
511 return thread->frameCount();
512}
513
514uint32_t AudioFlinger::latency(int output) const
515{
516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
519 LOGW("latency() unknown thread %d", output);
520 return 0;
521 }
522 return thread->latency();
523}
524
525status_t AudioFlinger::setMasterVolume(float value)
526{
Eric Laurenta1884f92011-08-23 08:25:03 -0700527 status_t ret = initCheck();
528 if (ret != NO_ERROR) {
529 return ret;
530 }
531
Mathias Agopian65ab4712010-07-14 17:59:35 -0700532 // check calling permissions
533 if (!settingsAllowed()) {
534 return PERMISSION_DENIED;
535 }
536
537 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800538 { // scope for the lock
539 AutoMutex lock(mHardwareLock);
540 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700541 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800542 value = 1.0f;
543 }
544 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546
Eric Laurent93575202011-01-18 18:39:02 -0800547 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700548 mMasterVolume = value;
549 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
550 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
551
552 return NO_ERROR;
553}
554
555status_t AudioFlinger::setMode(int mode)
556{
Eric Laurenta1884f92011-08-23 08:25:03 -0700557 status_t ret = initCheck();
558 if (ret != NO_ERROR) {
559 return ret;
560 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561
562 // check calling permissions
563 if (!settingsAllowed()) {
564 return PERMISSION_DENIED;
565 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700566 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567 LOGW("Illegal value: setMode(%d)", mode);
568 return BAD_VALUE;
569 }
570
571 { // scope for the lock
572 AutoMutex lock(mHardwareLock);
573 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700574 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 mHardwareStatus = AUDIO_HW_IDLE;
576 }
577
578 if (NO_ERROR == ret) {
579 Mutex::Autolock _l(mLock);
580 mMode = mode;
581 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
582 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 }
584
585 return ret;
586}
587
588status_t AudioFlinger::setMicMute(bool state)
589{
Eric Laurenta1884f92011-08-23 08:25:03 -0700590 status_t ret = initCheck();
591 if (ret != NO_ERROR) {
592 return ret;
593 }
594
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 // check calling permissions
596 if (!settingsAllowed()) {
597 return PERMISSION_DENIED;
598 }
599
600 AutoMutex lock(mHardwareLock);
601 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700602 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 mHardwareStatus = AUDIO_HW_IDLE;
604 return ret;
605}
606
607bool AudioFlinger::getMicMute() const
608{
Eric Laurenta1884f92011-08-23 08:25:03 -0700609 status_t ret = initCheck();
610 if (ret != NO_ERROR) {
611 return false;
612 }
613
Dima Zavinfce7a472011-04-19 22:30:36 -0700614 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700616 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 mHardwareStatus = AUDIO_HW_IDLE;
618 return state;
619}
620
621status_t AudioFlinger::setMasterMute(bool muted)
622{
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
627
Eric Laurent93575202011-01-18 18:39:02 -0800628 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 mMasterMute = muted;
630 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
631 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
632
633 return NO_ERROR;
634}
635
636float AudioFlinger::masterVolume() const
637{
638 return mMasterVolume;
639}
640
641bool AudioFlinger::masterMute() const
642{
643 return mMasterMute;
644}
645
646status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
647{
648 // check calling permissions
649 if (!settingsAllowed()) {
650 return PERMISSION_DENIED;
651 }
652
Dima Zavinfce7a472011-04-19 22:30:36 -0700653 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700654 return BAD_VALUE;
655 }
656
657 AutoMutex lock(mLock);
658 PlaybackThread *thread = NULL;
659 if (output) {
660 thread = checkPlaybackThread_l(output);
661 if (thread == NULL) {
662 return BAD_VALUE;
663 }
664 }
665
666 mStreamTypes[stream].volume = value;
667
668 if (thread == NULL) {
669 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
670 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
671 }
672 } else {
673 thread->setStreamVolume(stream, value);
674 }
675
676 return NO_ERROR;
677}
678
679status_t AudioFlinger::setStreamMute(int stream, bool muted)
680{
681 // check calling permissions
682 if (!settingsAllowed()) {
683 return PERMISSION_DENIED;
684 }
685
Dima Zavinfce7a472011-04-19 22:30:36 -0700686 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
687 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700688 return BAD_VALUE;
689 }
690
Eric Laurent93575202011-01-18 18:39:02 -0800691 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 mStreamTypes[stream].mute = muted;
693 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
694 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
695
696 return NO_ERROR;
697}
698
699float AudioFlinger::streamVolume(int stream, int output) const
700{
Dima Zavinfce7a472011-04-19 22:30:36 -0700701 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return 0.0f;
703 }
704
705 AutoMutex lock(mLock);
706 float volume;
707 if (output) {
708 PlaybackThread *thread = checkPlaybackThread_l(output);
709 if (thread == NULL) {
710 return 0.0f;
711 }
712 volume = thread->streamVolume(stream);
713 } else {
714 volume = mStreamTypes[stream].volume;
715 }
716
717 return volume;
718}
719
720bool AudioFlinger::streamMute(int stream) const
721{
Dima Zavinfce7a472011-04-19 22:30:36 -0700722 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700723 return true;
724 }
725
726 return mStreamTypes[stream].mute;
727}
728
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
730{
731 status_t result;
732
733 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
734 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
735 // check calling permissions
736 if (!settingsAllowed()) {
737 return PERMISSION_DENIED;
738 }
739
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 // ioHandle == 0 means the parameters are global to the audio hardware interface
741 if (ioHandle == 0) {
742 AutoMutex lock(mHardwareLock);
743 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700744 status_t final_result = NO_ERROR;
745 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
746 audio_hw_device_t *dev = mAudioHwDevs[i];
747 result = dev->set_parameters(dev, keyValuePairs.string());
748 final_result = result ?: final_result;
749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700750 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700751 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
752 AudioParameter param = AudioParameter(keyValuePairs);
753 String8 value;
754 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
755 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700756 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
757 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700758 for (size_t i = 0; i < mRecordThreads.size(); i++) {
759 sp<RecordThread> thread = mRecordThreads.valueAt(i);
760 RecordThread::RecordTrack *track = thread->track();
761 if (track != NULL) {
762 audio_devices_t device = (audio_devices_t)(
763 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700764 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 thread->setEffectSuspended(FX_IID_AEC,
766 suspend,
767 track->sessionId());
768 thread->setEffectSuspended(FX_IID_NS,
769 suspend,
770 track->sessionId());
771 }
772 }
Eric Laurentbee53372011-08-29 12:42:48 -0700773 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700774 }
775 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700776 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777 }
778
779 // hold a strong ref on thread in case closeOutput() or closeInput() is called
780 // and the thread is exited once the lock is released
781 sp<ThreadBase> thread;
782 {
783 Mutex::Autolock _l(mLock);
784 thread = checkPlaybackThread_l(ioHandle);
785 if (thread == NULL) {
786 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700787 } else if (thread.get() == primaryPlaybackThread_l()) {
788 // indicate output device change to all input threads for pre processing
789 AudioParameter param = AudioParameter(keyValuePairs);
790 int value;
791 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
792 for (size_t i = 0; i < mRecordThreads.size(); i++) {
793 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
794 }
795 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700796 }
797 }
798 if (thread != NULL) {
799 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700800 return result;
801 }
802 return BAD_VALUE;
803}
804
805String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
806{
807// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
808// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
809
810 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700811 String8 out_s8;
812
Dima Zavin799a70e2011-04-18 16:57:27 -0700813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
814 audio_hw_device_t *dev = mAudioHwDevs[i];
815 char *s = dev->get_parameters(dev, keys.string());
816 out_s8 += String8(s);
817 free(s);
818 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700819 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 }
821
822 Mutex::Autolock _l(mLock);
823
824 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
825 if (playbackThread != NULL) {
826 return playbackThread->getParameters(keys);
827 }
828 RecordThread *recordThread = checkRecordThread_l(ioHandle);
829 if (recordThread != NULL) {
830 return recordThread->getParameters(keys);
831 }
832 return String8("");
833}
834
835size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
836{
Eric Laurenta1884f92011-08-23 08:25:03 -0700837 status_t ret = initCheck();
838 if (ret != NO_ERROR) {
839 return 0;
840 }
841
Dima Zavin799a70e2011-04-18 16:57:27 -0700842 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843}
844
845unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
846{
847 if (ioHandle == 0) {
848 return 0;
849 }
850
851 Mutex::Autolock _l(mLock);
852
853 RecordThread *recordThread = checkRecordThread_l(ioHandle);
854 if (recordThread != NULL) {
855 return recordThread->getInputFramesLost();
856 }
857 return 0;
858}
859
860status_t AudioFlinger::setVoiceVolume(float value)
861{
Eric Laurenta1884f92011-08-23 08:25:03 -0700862 status_t ret = initCheck();
863 if (ret != NO_ERROR) {
864 return ret;
865 }
866
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 // check calling permissions
868 if (!settingsAllowed()) {
869 return PERMISSION_DENIED;
870 }
871
872 AutoMutex lock(mHardwareLock);
873 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700874 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 mHardwareStatus = AUDIO_HW_IDLE;
876
877 return ret;
878}
879
880status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
881{
882 status_t status;
883
884 Mutex::Autolock _l(mLock);
885
886 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
887 if (playbackThread != NULL) {
888 return playbackThread->getRenderPosition(halFrames, dspFrames);
889 }
890
891 return BAD_VALUE;
892}
893
894void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
895{
896
897 Mutex::Autolock _l(mLock);
898
899 int pid = IPCThreadState::self()->getCallingPid();
900 if (mNotificationClients.indexOfKey(pid) < 0) {
901 sp<NotificationClient> notificationClient = new NotificationClient(this,
902 client,
903 pid);
904 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
905
906 mNotificationClients.add(pid, notificationClient);
907
908 sp<IBinder> binder = client->asBinder();
909 binder->linkToDeath(notificationClient);
910
911 // the config change is always sent from playback or record threads to avoid deadlock
912 // with AudioSystem::gLock
913 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
914 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
915 }
916
917 for (size_t i = 0; i < mRecordThreads.size(); i++) {
918 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
919 }
920 }
921}
922
923void AudioFlinger::removeNotificationClient(pid_t pid)
924{
925 Mutex::Autolock _l(mLock);
926
927 int index = mNotificationClients.indexOfKey(pid);
928 if (index >= 0) {
929 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
930 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 mNotificationClients.removeItem(pid);
932 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700933
934 LOGV("%d died, releasing its sessions", pid);
935 int num = mAudioSessionRefs.size();
936 bool removed = false;
937 for (int i = 0; i< num; i++) {
938 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
939 LOGV(" pid %d @ %d", ref->pid, i);
940 if (ref->pid == pid) {
941 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
942 mAudioSessionRefs.removeAt(i);
943 delete ref;
944 removed = true;
945 i--;
946 num--;
947 }
948 }
949 if (removed) {
950 purgeStaleEffects_l();
951 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700952}
953
954// audioConfigChanged_l() must be called with AudioFlinger::mLock held
955void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
956{
957 size_t size = mNotificationClients.size();
958 for (size_t i = 0; i < size; i++) {
959 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
960 }
961}
962
963// removeClient_l() must be called with AudioFlinger::mLock held
964void AudioFlinger::removeClient_l(pid_t pid)
965{
966 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
967 mClients.removeItem(pid);
968}
969
970
971// ----------------------------------------------------------------------------
972
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700973AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700974 : Thread(false),
975 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700976 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
977 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700978{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700979 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980}
981
982AudioFlinger::ThreadBase::~ThreadBase()
983{
984 mParamCond.broadcast();
985 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700986 // do not lock the mutex in destructor
987 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700988 if (mPowerManager != 0) {
989 sp<IBinder> binder = mPowerManager->asBinder();
990 binder->unlinkToDeath(mDeathRecipient);
991 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992}
993
994void AudioFlinger::ThreadBase::exit()
995{
996 // keep a strong ref on ourself so that we wont get
997 // destroyed in the middle of requestExitAndWait()
998 sp <ThreadBase> strongMe = this;
999
1000 LOGV("ThreadBase::exit");
1001 {
1002 AutoMutex lock(&mLock);
1003 mExiting = true;
1004 requestExit();
1005 mWaitWorkCV.signal();
1006 }
1007 requestExitAndWait();
1008}
1009
1010uint32_t AudioFlinger::ThreadBase::sampleRate() const
1011{
1012 return mSampleRate;
1013}
1014
1015int AudioFlinger::ThreadBase::channelCount() const
1016{
1017 return (int)mChannelCount;
1018}
1019
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001020uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001021{
1022 return mFormat;
1023}
1024
1025size_t AudioFlinger::ThreadBase::frameCount() const
1026{
1027 return mFrameCount;
1028}
1029
1030status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1031{
1032 status_t status;
1033
1034 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1035 Mutex::Autolock _l(mLock);
1036
1037 mNewParameters.add(keyValuePairs);
1038 mWaitWorkCV.signal();
1039 // wait condition with timeout in case the thread loop has exited
1040 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001041 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 status = mParamStatus;
1043 mWaitWorkCV.signal();
1044 } else {
1045 status = TIMED_OUT;
1046 }
1047 return status;
1048}
1049
1050void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1051{
1052 Mutex::Autolock _l(mLock);
1053 sendConfigEvent_l(event, param);
1054}
1055
1056// sendConfigEvent_l() must be called with ThreadBase::mLock held
1057void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1058{
1059 ConfigEvent *configEvent = new ConfigEvent();
1060 configEvent->mEvent = event;
1061 configEvent->mParam = param;
1062 mConfigEvents.add(configEvent);
1063 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1064 mWaitWorkCV.signal();
1065}
1066
1067void AudioFlinger::ThreadBase::processConfigEvents()
1068{
1069 mLock.lock();
1070 while(!mConfigEvents.isEmpty()) {
1071 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1072 ConfigEvent *configEvent = mConfigEvents[0];
1073 mConfigEvents.removeAt(0);
1074 // release mLock before locking AudioFlinger mLock: lock order is always
1075 // AudioFlinger then ThreadBase to avoid cross deadlock
1076 mLock.unlock();
1077 mAudioFlinger->mLock.lock();
1078 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1079 mAudioFlinger->mLock.unlock();
1080 delete configEvent;
1081 mLock.lock();
1082 }
1083 mLock.unlock();
1084}
1085
1086status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1087{
1088 const size_t SIZE = 256;
1089 char buffer[SIZE];
1090 String8 result;
1091
1092 bool locked = tryLock(mLock);
1093 if (!locked) {
1094 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1095 write(fd, buffer, strlen(buffer));
1096 }
1097
1098 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1105 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001106 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1107 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1111 result.append(buffer);
1112
1113 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1114 result.append(buffer);
1115 result.append(" Index Command");
1116 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1117 snprintf(buffer, SIZE, "\n %02d ", i);
1118 result.append(buffer);
1119 result.append(mNewParameters[i]);
1120 }
1121
1122 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1123 result.append(buffer);
1124 snprintf(buffer, SIZE, " Index event param\n");
1125 result.append(buffer);
1126 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1127 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1128 result.append(buffer);
1129 }
1130 result.append("\n");
1131
1132 write(fd, result.string(), result.size());
1133
1134 if (locked) {
1135 mLock.unlock();
1136 }
1137 return NO_ERROR;
1138}
1139
Eric Laurent1d2bff02011-07-24 17:49:51 -07001140status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1141{
1142 const size_t SIZE = 256;
1143 char buffer[SIZE];
1144 String8 result;
1145
1146 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1147 write(fd, buffer, strlen(buffer));
1148
1149 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1150 sp<EffectChain> chain = mEffectChains[i];
1151 if (chain != 0) {
1152 chain->dump(fd, args);
1153 }
1154 }
1155 return NO_ERROR;
1156}
1157
Eric Laurentfeb0db62011-07-22 09:04:31 -07001158void AudioFlinger::ThreadBase::acquireWakeLock()
1159{
1160 Mutex::Autolock _l(mLock);
1161 acquireWakeLock_l();
1162}
1163
1164void AudioFlinger::ThreadBase::acquireWakeLock_l()
1165{
1166 if (mPowerManager == 0) {
1167 // use checkService() to avoid blocking if power service is not up yet
1168 sp<IBinder> binder =
1169 defaultServiceManager()->checkService(String16("power"));
1170 if (binder == 0) {
1171 LOGW("Thread %s cannot connect to the power manager service", mName);
1172 } else {
1173 mPowerManager = interface_cast<IPowerManager>(binder);
1174 binder->linkToDeath(mDeathRecipient);
1175 }
1176 }
1177 if (mPowerManager != 0) {
1178 sp<IBinder> binder = new BBinder();
1179 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1180 binder,
1181 String16(mName));
1182 if (status == NO_ERROR) {
1183 mWakeLockToken = binder;
1184 }
1185 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1186 }
1187}
1188
1189void AudioFlinger::ThreadBase::releaseWakeLock()
1190{
1191 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001192 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001193}
1194
1195void AudioFlinger::ThreadBase::releaseWakeLock_l()
1196{
1197 if (mWakeLockToken != 0) {
1198 LOGV("releaseWakeLock_l() %s", mName);
1199 if (mPowerManager != 0) {
1200 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1201 }
1202 mWakeLockToken.clear();
1203 }
1204}
1205
1206void AudioFlinger::ThreadBase::clearPowerManager()
1207{
1208 Mutex::Autolock _l(mLock);
1209 releaseWakeLock_l();
1210 mPowerManager.clear();
1211}
1212
1213void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1214{
1215 sp<ThreadBase> thread = mThread.promote();
1216 if (thread != 0) {
1217 thread->clearPowerManager();
1218 }
1219 LOGW("power manager service died !!!");
1220}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001221
Eric Laurent59255e42011-07-27 19:49:51 -07001222void AudioFlinger::ThreadBase::setEffectSuspended(
1223 const effect_uuid_t *type, bool suspend, int sessionId)
1224{
1225 Mutex::Autolock _l(mLock);
1226 setEffectSuspended_l(type, suspend, sessionId);
1227}
1228
1229void AudioFlinger::ThreadBase::setEffectSuspended_l(
1230 const effect_uuid_t *type, bool suspend, int sessionId)
1231{
1232 sp<EffectChain> chain;
1233 chain = getEffectChain_l(sessionId);
1234 if (chain != 0) {
1235 if (type != NULL) {
1236 chain->setEffectSuspended_l(type, suspend);
1237 } else {
1238 chain->setEffectSuspendedAll_l(suspend);
1239 }
1240 }
1241
1242 updateSuspendedSessions_l(type, suspend, sessionId);
1243}
1244
1245void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1246{
1247 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1248 if (index < 0) {
1249 return;
1250 }
1251
1252 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1253 mSuspendedSessions.editValueAt(index);
1254
1255 for (size_t i = 0; i < sessionEffects.size(); i++) {
1256 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1257 for (int j = 0; j < desc->mRefCount; j++) {
1258 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1259 chain->setEffectSuspendedAll_l(true);
1260 } else {
1261 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1262 desc->mType.timeLow);
1263 chain->setEffectSuspended_l(&desc->mType, true);
1264 }
1265 }
1266 }
1267}
1268
Eric Laurent59255e42011-07-27 19:49:51 -07001269void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1270 bool suspend,
1271 int sessionId)
1272{
1273 int index = mSuspendedSessions.indexOfKey(sessionId);
1274
1275 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1276
1277 if (suspend) {
1278 if (index >= 0) {
1279 sessionEffects = mSuspendedSessions.editValueAt(index);
1280 } else {
1281 mSuspendedSessions.add(sessionId, sessionEffects);
1282 }
1283 } else {
1284 if (index < 0) {
1285 return;
1286 }
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 }
1289
1290
1291 int key = EffectChain::kKeyForSuspendAll;
1292 if (type != NULL) {
1293 key = type->timeLow;
1294 }
1295 index = sessionEffects.indexOfKey(key);
1296
1297 sp <SuspendedSessionDesc> desc;
1298 if (suspend) {
1299 if (index >= 0) {
1300 desc = sessionEffects.valueAt(index);
1301 } else {
1302 desc = new SuspendedSessionDesc();
1303 if (type != NULL) {
1304 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1305 }
1306 sessionEffects.add(key, desc);
1307 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1308 }
1309 desc->mRefCount++;
1310 } else {
1311 if (index < 0) {
1312 return;
1313 }
1314 desc = sessionEffects.valueAt(index);
1315 if (--desc->mRefCount == 0) {
1316 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1317 sessionEffects.removeItemsAt(index);
1318 if (sessionEffects.isEmpty()) {
1319 LOGV("updateSuspendedSessions_l() restore removing session %d",
1320 sessionId);
1321 mSuspendedSessions.removeItem(sessionId);
1322 }
1323 }
1324 }
1325 if (!sessionEffects.isEmpty()) {
1326 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1327 }
1328}
1329
1330void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1331 bool enabled,
1332 int sessionId)
1333{
1334 Mutex::Autolock _l(mLock);
1335
Eric Laurentdb7c0792011-08-10 10:37:50 -07001336 if (mType != RECORD) {
1337 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1338 // another session. This gives the priority to well behaved effect control panels
1339 // and applications not using global effects.
1340 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1341 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1342 }
1343 }
Eric Laurent59255e42011-07-27 19:49:51 -07001344
1345 sp<EffectChain> chain = getEffectChain_l(sessionId);
1346 if (chain != 0) {
1347 chain->checkSuspendOnEffectEnabled(effect, enabled);
1348 }
1349}
1350
Mathias Agopian65ab4712010-07-14 17:59:35 -07001351// ----------------------------------------------------------------------------
1352
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001353AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1354 AudioStreamOut* output,
1355 int id,
1356 uint32_t device)
1357 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001358 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001359 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001360{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001361 snprintf(mName, kNameLength, "AudioOut_%d", id);
1362
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363 readOutputParameters();
1364
1365 mMasterVolume = mAudioFlinger->masterVolume();
1366 mMasterMute = mAudioFlinger->masterMute();
1367
Dima Zavinfce7a472011-04-19 22:30:36 -07001368 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1370 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001371 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372 }
1373}
1374
1375AudioFlinger::PlaybackThread::~PlaybackThread()
1376{
1377 delete [] mMixBuffer;
1378}
1379
1380status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1381{
1382 dumpInternals(fd, args);
1383 dumpTracks(fd, args);
1384 dumpEffectChains(fd, args);
1385 return NO_ERROR;
1386}
1387
1388status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1389{
1390 const size_t SIZE = 256;
1391 char buffer[SIZE];
1392 String8 result;
1393
1394 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1395 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001396 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397 for (size_t i = 0; i < mTracks.size(); ++i) {
1398 sp<Track> track = mTracks[i];
1399 if (track != 0) {
1400 track->dump(buffer, SIZE);
1401 result.append(buffer);
1402 }
1403 }
1404
1405 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1406 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001407 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1409 wp<Track> wTrack = mActiveTracks[i];
1410 if (wTrack != 0) {
1411 sp<Track> track = wTrack.promote();
1412 if (track != 0) {
1413 track->dump(buffer, SIZE);
1414 result.append(buffer);
1415 }
1416 }
1417 }
1418 write(fd, result.string(), result.size());
1419 return NO_ERROR;
1420}
1421
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1423{
1424 const size_t SIZE = 256;
1425 char buffer[SIZE];
1426 String8 result;
1427
1428 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1429 result.append(buffer);
1430 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1431 result.append(buffer);
1432 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1433 result.append(buffer);
1434 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1435 result.append(buffer);
1436 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1437 result.append(buffer);
1438 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1439 result.append(buffer);
1440 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1441 result.append(buffer);
1442 write(fd, result.string(), result.size());
1443
1444 dumpBase(fd, args);
1445
1446 return NO_ERROR;
1447}
1448
1449// Thread virtuals
1450status_t AudioFlinger::PlaybackThread::readyToRun()
1451{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001452 status_t status = initCheck();
1453 if (status == NO_ERROR) {
1454 LOGI("AudioFlinger's thread %p ready to run", this);
1455 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001457 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001458 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001459}
1460
1461void AudioFlinger::PlaybackThread::onFirstRef()
1462{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001463 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001464}
1465
1466// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1467sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1468 const sp<AudioFlinger::Client>& client,
1469 int streamType,
1470 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001471 uint32_t format,
1472 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 int frameCount,
1474 const sp<IMemory>& sharedBuffer,
1475 int sessionId,
1476 status_t *status)
1477{
1478 sp<Track> track;
1479 status_t lStatus;
1480
1481 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001482 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1483 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1484 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1485 "for output %p with format %d",
1486 sampleRate, format, channelMask, mOutput, mFormat);
1487 lStatus = BAD_VALUE;
1488 goto Exit;
1489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490 }
1491 } else {
1492 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1493 if (sampleRate > mSampleRate*2) {
1494 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1495 lStatus = BAD_VALUE;
1496 goto Exit;
1497 }
1498 }
1499
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001500 lStatus = initCheck();
1501 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001503 goto Exit;
1504 }
1505
1506 { // scope for mLock
1507 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001508
1509 // all tracks in same audio session must share the same routing strategy otherwise
1510 // conflicts will happen when tracks are moved from one output to another by audio policy
1511 // manager
1512 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001513 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001514 for (size_t i = 0; i < mTracks.size(); ++i) {
1515 sp<Track> t = mTracks[i];
1516 if (t != 0) {
1517 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001518 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001519 lStatus = BAD_VALUE;
1520 goto Exit;
1521 }
1522 }
1523 }
1524
Mathias Agopian65ab4712010-07-14 17:59:35 -07001525 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001526 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001527 if (track->getCblk() == NULL || track->name() < 0) {
1528 lStatus = NO_MEMORY;
1529 goto Exit;
1530 }
1531 mTracks.add(track);
1532
1533 sp<EffectChain> chain = getEffectChain_l(sessionId);
1534 if (chain != 0) {
1535 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1536 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001537 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001538 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001540
1541 // invalidate track immediately if the stream type was moved to another thread since
1542 // createTrack() was called by the client process.
1543 if (!mStreamTypes[streamType].valid) {
1544 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1545 this, streamType);
1546 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1547 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001548 }
1549 lStatus = NO_ERROR;
1550
1551Exit:
1552 if(status) {
1553 *status = lStatus;
1554 }
1555 return track;
1556}
1557
1558uint32_t AudioFlinger::PlaybackThread::latency() const
1559{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001560 Mutex::Autolock _l(mLock);
1561 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001562 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001563 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001564 return 0;
1565 }
1566}
1567
1568status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1569{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 mMasterVolume = value;
1571 return NO_ERROR;
1572}
1573
1574status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1575{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 mMasterMute = muted;
1577 return NO_ERROR;
1578}
1579
1580float AudioFlinger::PlaybackThread::masterVolume() const
1581{
1582 return mMasterVolume;
1583}
1584
1585bool AudioFlinger::PlaybackThread::masterMute() const
1586{
1587 return mMasterMute;
1588}
1589
1590status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1591{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 mStreamTypes[stream].volume = value;
1593 return NO_ERROR;
1594}
1595
1596status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1597{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 mStreamTypes[stream].mute = muted;
1599 return NO_ERROR;
1600}
1601
1602float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1603{
1604 return mStreamTypes[stream].volume;
1605}
1606
1607bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1608{
1609 return mStreamTypes[stream].mute;
1610}
1611
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612// addTrack_l() must be called with ThreadBase::mLock held
1613status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1614{
1615 status_t status = ALREADY_EXISTS;
1616
1617 // set retry count for buffer fill
1618 track->mRetryCount = kMaxTrackStartupRetries;
1619 if (mActiveTracks.indexOf(track) < 0) {
1620 // the track is newly added, make sure it fills up all its
1621 // buffers before playing. This is to ensure the client will
1622 // effectively get the latency it requested.
1623 track->mFillingUpStatus = Track::FS_FILLING;
1624 track->mResetDone = false;
1625 mActiveTracks.add(track);
1626 if (track->mainBuffer() != mMixBuffer) {
1627 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1628 if (chain != 0) {
1629 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001630 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631 }
1632 }
1633
1634 status = NO_ERROR;
1635 }
1636
1637 LOGV("mWaitWorkCV.broadcast");
1638 mWaitWorkCV.broadcast();
1639
1640 return status;
1641}
1642
1643// destroyTrack_l() must be called with ThreadBase::mLock held
1644void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1645{
1646 track->mState = TrackBase::TERMINATED;
1647 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001648 removeTrack_l(track);
1649 }
1650}
1651
1652void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1653{
1654 mTracks.remove(track);
1655 deleteTrackName_l(track->name());
1656 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1657 if (chain != 0) {
1658 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 }
1660}
1661
1662String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1663{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001664 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001665 char *s;
1666
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001667 Mutex::Autolock _l(mLock);
1668 if (initCheck() != NO_ERROR) {
1669 return out_s8;
1670 }
1671
Dima Zavin799a70e2011-04-18 16:57:27 -07001672 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001673 out_s8 = String8(s);
1674 free(s);
1675 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676}
1677
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001678// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1680 AudioSystem::OutputDescriptor desc;
1681 void *param2 = 0;
1682
1683 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1684
1685 switch (event) {
1686 case AudioSystem::OUTPUT_OPENED:
1687 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001688 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001689 desc.samplingRate = mSampleRate;
1690 desc.format = mFormat;
1691 desc.frameCount = mFrameCount;
1692 desc.latency = latency();
1693 param2 = &desc;
1694 break;
1695
1696 case AudioSystem::STREAM_CONFIG_CHANGED:
1697 param2 = &param;
1698 case AudioSystem::OUTPUT_CLOSED:
1699 default:
1700 break;
1701 }
1702 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1703}
1704
1705void AudioFlinger::PlaybackThread::readOutputParameters()
1706{
Dima Zavin799a70e2011-04-18 16:57:27 -07001707 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001708 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1709 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001710 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1711 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1712 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713
1714 // FIXME - Current mixer implementation only supports stereo output: Always
1715 // Allocate a stereo buffer even if HW output is mono.
1716 if (mMixBuffer != NULL) delete[] mMixBuffer;
1717 mMixBuffer = new int16_t[mFrameCount * 2];
1718 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1719
Eric Laurentde070132010-07-13 04:45:46 -07001720 // force reconfiguration of effect chains and engines to take new buffer size and audio
1721 // parameters into account
1722 // Note that mLock is not held when readOutputParameters() is called from the constructor
1723 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1724 // matter.
1725 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1726 Vector< sp<EffectChain> > effectChains = mEffectChains;
1727 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001728 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730}
1731
1732status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1733{
1734 if (halFrames == 0 || dspFrames == 0) {
1735 return BAD_VALUE;
1736 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001737 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001738 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001739 return INVALID_OPERATION;
1740 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001741 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742
Dima Zavin799a70e2011-04-18 16:57:27 -07001743 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744}
1745
Eric Laurent39e94f82010-07-28 01:32:47 -07001746uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747{
1748 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001749 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001751 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 }
1753
1754 for (size_t i = 0; i < mTracks.size(); ++i) {
1755 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001756 if (sessionId == track->sessionId() &&
1757 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001758 result |= TRACK_SESSION;
1759 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001760 }
1761 }
1762
Eric Laurent39e94f82010-07-28 01:32:47 -07001763 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
Eric Laurentde070132010-07-13 04:45:46 -07001766uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1767{
Dima Zavinfce7a472011-04-19 22:30:36 -07001768 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001769 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001770 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1771 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001772 }
1773 for (size_t i = 0; i < mTracks.size(); i++) {
1774 sp<Track> track = mTracks[i];
1775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001777 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001778 }
1779 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001781}
1782
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001784AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1785{
1786 Mutex::Autolock _l(mLock);
1787 return mOutput;
1788}
1789
1790AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1791{
1792 Mutex::Autolock _l(mLock);
1793 AudioStreamOut *output = mOutput;
1794 mOutput = NULL;
1795 return output;
1796}
1797
1798// this method must always be called either with ThreadBase mLock held or inside the thread loop
1799audio_stream_t* AudioFlinger::PlaybackThread::stream()
1800{
1801 if (mOutput == NULL) {
1802 return NULL;
1803 }
1804 return &mOutput->stream->common;
1805}
1806
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807// ----------------------------------------------------------------------------
1808
Dima Zavin799a70e2011-04-18 16:57:27 -07001809AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001810 : PlaybackThread(audioFlinger, output, id, device),
1811 mAudioMixer(0)
1812{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001813 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1815
1816 // FIXME - Current mixer implementation only supports stereo output
1817 if (mChannelCount == 1) {
1818 LOGE("Invalid audio hardware channel count");
1819 }
1820}
1821
1822AudioFlinger::MixerThread::~MixerThread()
1823{
1824 delete mAudioMixer;
1825}
1826
1827bool AudioFlinger::MixerThread::threadLoop()
1828{
1829 Vector< sp<Track> > tracksToRemove;
1830 uint32_t mixerStatus = MIXER_IDLE;
1831 nsecs_t standbyTime = systemTime();
1832 size_t mixBufferSize = mFrameCount * mFrameSize;
1833 // FIXME: Relaxed timing because of a certain device that can't meet latency
1834 // Should be reduced to 2x after the vendor fixes the driver issue
1835 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1836 nsecs_t lastWarning = 0;
1837 bool longStandbyExit = false;
1838 uint32_t activeSleepTime = activeSleepTimeUs();
1839 uint32_t idleSleepTime = idleSleepTimeUs();
1840 uint32_t sleepTime = idleSleepTime;
1841 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001842#ifdef DEBUG_CPU_USAGE
1843 ThreadCpuUsage cpu;
1844 const CentralTendencyStatistics& stats = cpu.statistics();
1845#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846
Eric Laurentfeb0db62011-07-22 09:04:31 -07001847 acquireWakeLock();
1848
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 while (!exitPending())
1850 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001851#ifdef DEBUG_CPU_USAGE
1852 cpu.sampleAndEnable();
1853 unsigned n = stats.n();
1854 // cpu.elapsed() is expensive, so don't call it every loop
1855 if ((n & 127) == 1) {
1856 long long elapsed = cpu.elapsed();
1857 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1858 double perLoop = elapsed / (double) n;
1859 double perLoop100 = perLoop * 0.01;
1860 double mean = stats.mean();
1861 double stddev = stats.stddev();
1862 double minimum = stats.minimum();
1863 double maximum = stats.maximum();
1864 cpu.resetStatistics();
1865 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",
1866 elapsed * .000000001, n, perLoop * .000001,
1867 mean * .001,
1868 stddev * .001,
1869 minimum * .001,
1870 maximum * .001,
1871 mean / perLoop100,
1872 stddev / perLoop100,
1873 minimum / perLoop100,
1874 maximum / perLoop100);
1875 }
1876 }
1877#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 processConfigEvents();
1879
1880 mixerStatus = MIXER_IDLE;
1881 { // scope for mLock
1882
1883 Mutex::Autolock _l(mLock);
1884
1885 if (checkForNewParameters_l()) {
1886 mixBufferSize = mFrameCount * mFrameSize;
1887 // FIXME: Relaxed timing because of a certain device that can't meet latency
1888 // Should be reduced to 2x after the vendor fixes the driver issue
1889 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1890 activeSleepTime = activeSleepTimeUs();
1891 idleSleepTime = idleSleepTimeUs();
1892 }
1893
1894 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1895
1896 // put audio hardware into standby after short delay
1897 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1898 mSuspended) {
1899 if (!mStandby) {
1900 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001901 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001902 mStandby = true;
1903 mBytesWritten = 0;
1904 }
1905
1906 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1907 // we're about to wait, flush the binder command buffer
1908 IPCThreadState::self()->flushCommands();
1909
1910 if (exitPending()) break;
1911
Eric Laurentfeb0db62011-07-22 09:04:31 -07001912 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 // wait until we have something to do...
1914 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1915 mWaitWorkCV.wait(mLock);
1916 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001917 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001918
1919 if (mMasterMute == false) {
1920 char value[PROPERTY_VALUE_MAX];
1921 property_get("ro.audio.silent", value, "0");
1922 if (atoi(value)) {
1923 LOGD("Silence is golden");
1924 setMasterMute(true);
1925 }
1926 }
1927
1928 standbyTime = systemTime() + kStandbyTimeInNsecs;
1929 sleepTime = idleSleepTime;
1930 continue;
1931 }
1932 }
1933
1934 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1935
1936 // prevent any changes in effect chain list and in each effect chain
1937 // during mixing and effect process as the audio buffers could be deleted
1938 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001939 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001940 }
1941
1942 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1943 // mix buffers...
1944 mAudioMixer->process();
1945 sleepTime = 0;
1946 standbyTime = systemTime() + kStandbyTimeInNsecs;
1947 //TODO: delay standby when effects have a tail
1948 } else {
1949 // If no tracks are ready, sleep once for the duration of an output
1950 // buffer size, then write 0s to the output
1951 if (sleepTime == 0) {
1952 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1953 sleepTime = activeSleepTime;
1954 } else {
1955 sleepTime = idleSleepTime;
1956 }
1957 } else if (mBytesWritten != 0 ||
1958 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1959 memset (mMixBuffer, 0, mixBufferSize);
1960 sleepTime = 0;
1961 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1962 }
1963 // TODO add standby time extension fct of effect tail
1964 }
1965
1966 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001967 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 }
1969 // sleepTime == 0 means we must write to audio hardware
1970 if (sleepTime == 0) {
1971 for (size_t i = 0; i < effectChains.size(); i ++) {
1972 effectChains[i]->process_l();
1973 }
1974 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001975 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 mLastWriteTime = systemTime();
1977 mInWrite = true;
1978 mBytesWritten += mixBufferSize;
1979
Dima Zavin799a70e2011-04-18 16:57:27 -07001980 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1982 mNumWrites++;
1983 mInWrite = false;
1984 nsecs_t now = systemTime();
1985 nsecs_t delta = now - mLastWriteTime;
1986 if (delta > maxPeriod) {
1987 mNumDelayedWrites++;
1988 if ((now - lastWarning) > kWarningThrottle) {
1989 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1990 ns2ms(delta), mNumDelayedWrites, this);
1991 lastWarning = now;
1992 }
1993 if (mStandby) {
1994 longStandbyExit = true;
1995 }
1996 }
1997 mStandby = false;
1998 } else {
1999 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002000 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002001 usleep(sleepTime);
2002 }
2003
2004 // finally let go of all our tracks, without the lock held
2005 // since we can't guarantee the destructors won't acquire that
2006 // same lock.
2007 tracksToRemove.clear();
2008
2009 // Effect chains will be actually deleted here if they were removed from
2010 // mEffectChains list during mixing or effects processing
2011 effectChains.clear();
2012 }
2013
2014 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002015 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016 }
2017
Eric Laurentfeb0db62011-07-22 09:04:31 -07002018 releaseWakeLock();
2019
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 LOGV("MixerThread %p exiting", this);
2021 return false;
2022}
2023
2024// prepareTracks_l() must be called with ThreadBase::mLock held
2025uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2026{
2027
2028 uint32_t mixerStatus = MIXER_IDLE;
2029 // find out which tracks need to be processed
2030 size_t count = activeTracks.size();
2031 size_t mixedTracks = 0;
2032 size_t tracksWithEffect = 0;
2033
2034 float masterVolume = mMasterVolume;
2035 bool masterMute = mMasterMute;
2036
Eric Laurent571d49c2010-08-11 05:20:11 -07002037 if (masterMute) {
2038 masterVolume = 0;
2039 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002041 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002043 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002044 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002045 masterVolume = (float)((v + (1 << 23)) >> 24);
2046 chain.clear();
2047 }
2048
2049 for (size_t i=0 ; i<count ; i++) {
2050 sp<Track> t = activeTracks[i].promote();
2051 if (t == 0) continue;
2052
2053 Track* const track = t.get();
2054 audio_track_cblk_t* cblk = track->cblk();
2055
2056 // The first time a track is added we wait
2057 // for all its buffers to be filled before processing it
2058 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07002059 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 !track->isPaused() && !track->isTerminated())
2061 {
2062 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2063
2064 mixedTracks++;
2065
2066 // track->mainBuffer() != mMixBuffer means there is an effect chain
2067 // connected to the track
2068 chain.clear();
2069 if (track->mainBuffer() != mMixBuffer) {
2070 chain = getEffectChain_l(track->sessionId());
2071 // Delegate volume control to effect in track effect chain if needed
2072 if (chain != 0) {
2073 tracksWithEffect++;
2074 } else {
2075 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2076 track->name(), track->sessionId());
2077 }
2078 }
2079
2080
2081 int param = AudioMixer::VOLUME;
2082 if (track->mFillingUpStatus == Track::FS_FILLED) {
2083 // no ramp for the first volume setting
2084 track->mFillingUpStatus = Track::FS_ACTIVE;
2085 if (track->mState == TrackBase::RESUMING) {
2086 track->mState = TrackBase::ACTIVE;
2087 param = AudioMixer::RAMP_VOLUME;
2088 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002089 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 } else if (cblk->server != 0) {
2091 // If the track is stopped before the first frame was mixed,
2092 // do not apply ramp
2093 param = AudioMixer::RAMP_VOLUME;
2094 }
2095
2096 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002097 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002098 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002100 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002101 if (track->isPausing()) {
2102 track->setPaused();
2103 }
2104 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002105
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 // read original volumes with volume control
2107 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002108 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002109 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2110 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002111
Eric Laurente0aed6d2010-09-10 17:44:44 -07002112 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002113 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002114 // Delegate volume control to effect in track effect chain if needed
2115 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2116 // Do not ramp volume if volume is controlled by effect
2117 param = AudioMixer::VOLUME;
2118 track->mHasVolumeController = true;
2119 } else {
2120 // force no volume ramp when volume controller was just disabled or removed
2121 // from effect chain to avoid volume spike
2122 if (track->mHasVolumeController) {
2123 param = AudioMixer::VOLUME;
2124 }
2125 track->mHasVolumeController = false;
2126 }
2127
2128 // Convert volumes from 8.24 to 4.12 format
2129 int16_t left, right, aux;
2130 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2131 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2132 left = int16_t(v_clamped);
2133 v_clamped = (vr + (1 << 11)) >> 12;
2134 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2135 right = int16_t(v_clamped);
2136
2137 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2138 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 // XXX: these things DON'T need to be done each time
2141 mAudioMixer->setBufferProvider(track);
2142 mAudioMixer->enable(AudioMixer::MIXING);
2143
2144 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2145 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2146 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2147 mAudioMixer->setParameter(
2148 AudioMixer::TRACK,
2149 AudioMixer::FORMAT, (void *)track->format());
2150 mAudioMixer->setParameter(
2151 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002152 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 mAudioMixer->setParameter(
2154 AudioMixer::RESAMPLE,
2155 AudioMixer::SAMPLE_RATE,
2156 (void *)(cblk->sampleRate));
2157 mAudioMixer->setParameter(
2158 AudioMixer::TRACK,
2159 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2160 mAudioMixer->setParameter(
2161 AudioMixer::TRACK,
2162 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2163
2164 // reset retry count
2165 track->mRetryCount = kMaxTrackRetries;
2166 mixerStatus = MIXER_TRACKS_READY;
2167 } else {
2168 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2169 if (track->isStopped()) {
2170 track->reset();
2171 }
2172 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2173 // We have consumed all the buffers of this track.
2174 // Remove it from the list of active tracks.
2175 tracksToRemove->add(track);
2176 } else {
2177 // No buffers for this track. Give it a few chances to
2178 // fill a buffer, then remove it from active list.
2179 if (--(track->mRetryCount) <= 0) {
2180 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2181 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002182 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002183 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002184 } else if (mixerStatus != MIXER_TRACKS_READY) {
2185 mixerStatus = MIXER_TRACKS_ENABLED;
2186 }
2187 }
2188 mAudioMixer->disable(AudioMixer::MIXING);
2189 }
2190 }
2191
2192 // remove all the tracks that need to be...
2193 count = tracksToRemove->size();
2194 if (UNLIKELY(count)) {
2195 for (size_t i=0 ; i<count ; i++) {
2196 const sp<Track>& track = tracksToRemove->itemAt(i);
2197 mActiveTracks.remove(track);
2198 if (track->mainBuffer() != mMixBuffer) {
2199 chain = getEffectChain_l(track->sessionId());
2200 if (chain != 0) {
2201 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002202 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
2204 }
2205 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002206 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 }
2208 }
2209 }
2210
2211 // mix buffer must be cleared if all tracks are connected to an
2212 // effect chain as in this case the mixer will not write to
2213 // mix buffer and track effects will accumulate into it
2214 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2215 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2216 }
2217
2218 return mixerStatus;
2219}
2220
2221void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2222{
Eric Laurentde070132010-07-13 04:45:46 -07002223 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2224 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002225 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002226
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 size_t size = mTracks.size();
2228 for (size_t i = 0; i < size; i++) {
2229 sp<Track> t = mTracks[i];
2230 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002231 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002233 }
2234 }
2235}
2236
Eric Laurent9f6530f2011-08-30 10:18:54 -07002237void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2238{
2239 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2240 this, streamType, valid);
2241 Mutex::Autolock _l(mLock);
2242
2243 mStreamTypes[streamType].valid = valid;
2244}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002245
2246// getTrackName_l() must be called with ThreadBase::mLock held
2247int AudioFlinger::MixerThread::getTrackName_l()
2248{
2249 return mAudioMixer->getTrackName();
2250}
2251
2252// deleteTrackName_l() must be called with ThreadBase::mLock held
2253void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2254{
2255 LOGV("remove track (%d) and delete from mixer", name);
2256 mAudioMixer->deleteTrackName(name);
2257}
2258
2259// checkForNewParameters_l() must be called with ThreadBase::mLock held
2260bool AudioFlinger::MixerThread::checkForNewParameters_l()
2261{
2262 bool reconfig = false;
2263
2264 while (!mNewParameters.isEmpty()) {
2265 status_t status = NO_ERROR;
2266 String8 keyValuePair = mNewParameters[0];
2267 AudioParameter param = AudioParameter(keyValuePair);
2268 int value;
2269
2270 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2271 reconfig = true;
2272 }
2273 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002274 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002275 status = BAD_VALUE;
2276 } else {
2277 reconfig = true;
2278 }
2279 }
2280 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002281 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 status = BAD_VALUE;
2283 } else {
2284 reconfig = true;
2285 }
2286 }
2287 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2288 // do not accept frame count changes if tracks are open as the track buffer
2289 // size depends on frame count and correct behavior would not be garantied
2290 // if frame count is changed after track creation
2291 if (!mTracks.isEmpty()) {
2292 status = INVALID_OPERATION;
2293 } else {
2294 reconfig = true;
2295 }
2296 }
2297 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002298 // when changing the audio output device, call addBatteryData to notify
2299 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002300 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002301 uint32_t params = 0;
2302 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002303 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002304 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2305 }
2306
2307 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002308 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002309 // check if any other device (except speaker) is on
2310 if (value & deviceWithoutSpeaker ) {
2311 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2312 }
2313
2314 if (params != 0) {
2315 addBatteryData(params);
2316 }
2317 }
2318
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 // forward device change to effects that have requested to be
2320 // aware of attached audio device.
2321 mDevice = (uint32_t)value;
2322 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002323 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002324 }
2325 }
2326
2327 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002328 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002329 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002331 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002332 mStandby = true;
2333 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002334 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002335 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 }
2337 if (status == NO_ERROR && reconfig) {
2338 delete mAudioMixer;
2339 readOutputParameters();
2340 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2341 for (size_t i = 0; i < mTracks.size() ; i++) {
2342 int name = getTrackName_l();
2343 if (name < 0) break;
2344 mTracks[i]->mName = name;
2345 // limit track sample rate to 2 x new output sample rate
2346 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2347 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2348 }
2349 }
2350 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2351 }
2352 }
2353
2354 mNewParameters.removeAt(0);
2355
2356 mParamStatus = status;
2357 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002358 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2359 // already timed out waiting for the status and will never signal the condition.
2360 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 }
2362 return reconfig;
2363}
2364
2365status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2366{
2367 const size_t SIZE = 256;
2368 char buffer[SIZE];
2369 String8 result;
2370
2371 PlaybackThread::dumpInternals(fd, args);
2372
2373 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2374 result.append(buffer);
2375 write(fd, result.string(), result.size());
2376 return NO_ERROR;
2377}
2378
2379uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2380{
Dima Zavin799a70e2011-04-18 16:57:27 -07002381 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382}
2383
2384uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2385{
Eric Laurent60e18242010-07-29 06:50:24 -07002386 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387}
2388
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002389uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2390{
2391 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2392}
2393
Mathias Agopian65ab4712010-07-14 17:59:35 -07002394// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002395AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 : PlaybackThread(audioFlinger, output, id, device)
2397{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002398 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399}
2400
2401AudioFlinger::DirectOutputThread::~DirectOutputThread()
2402{
2403}
2404
2405
2406static inline int16_t clamp16(int32_t sample)
2407{
2408 if ((sample>>15) ^ (sample>>31))
2409 sample = 0x7FFF ^ (sample>>31);
2410 return sample;
2411}
2412
2413static inline
2414int32_t mul(int16_t in, int16_t v)
2415{
2416#if defined(__arm__) && !defined(__thumb__)
2417 int32_t out;
2418 asm( "smulbb %[out], %[in], %[v] \n"
2419 : [out]"=r"(out)
2420 : [in]"%r"(in), [v]"r"(v)
2421 : );
2422 return out;
2423#else
2424 return in * int32_t(v);
2425#endif
2426}
2427
2428void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2429{
2430 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002431 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 return;
2433 }
2434
2435 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002436 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 size_t count = mFrameCount * mChannelCount;
2438 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2439 int16_t *dst = mMixBuffer + count-1;
2440 while(count--) {
2441 *dst-- = (int16_t)(*src--^0x80) << 8;
2442 }
2443 }
2444
2445 size_t frameCount = mFrameCount;
2446 int16_t *out = mMixBuffer;
2447 if (ramp) {
2448 if (mChannelCount == 1) {
2449 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2450 int32_t vlInc = d / (int32_t)frameCount;
2451 int32_t vl = ((int32_t)mLeftVolShort << 16);
2452 do {
2453 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2454 out++;
2455 vl += vlInc;
2456 } while (--frameCount);
2457
2458 } else {
2459 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2460 int32_t vlInc = d / (int32_t)frameCount;
2461 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2462 int32_t vrInc = d / (int32_t)frameCount;
2463 int32_t vl = ((int32_t)mLeftVolShort << 16);
2464 int32_t vr = ((int32_t)mRightVolShort << 16);
2465 do {
2466 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2467 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2468 out += 2;
2469 vl += vlInc;
2470 vr += vrInc;
2471 } while (--frameCount);
2472 }
2473 } else {
2474 if (mChannelCount == 1) {
2475 do {
2476 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2477 out++;
2478 } while (--frameCount);
2479 } else {
2480 do {
2481 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2482 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2483 out += 2;
2484 } while (--frameCount);
2485 }
2486 }
2487
2488 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002489 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 size_t count = mFrameCount * mChannelCount;
2491 int16_t *src = mMixBuffer;
2492 uint8_t *dst = (uint8_t *)mMixBuffer;
2493 while(count--) {
2494 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2495 }
2496 }
2497
2498 mLeftVolShort = leftVol;
2499 mRightVolShort = rightVol;
2500}
2501
2502bool AudioFlinger::DirectOutputThread::threadLoop()
2503{
2504 uint32_t mixerStatus = MIXER_IDLE;
2505 sp<Track> trackToRemove;
2506 sp<Track> activeTrack;
2507 nsecs_t standbyTime = systemTime();
2508 int8_t *curBuf;
2509 size_t mixBufferSize = mFrameCount*mFrameSize;
2510 uint32_t activeSleepTime = activeSleepTimeUs();
2511 uint32_t idleSleepTime = idleSleepTimeUs();
2512 uint32_t sleepTime = idleSleepTime;
2513 // use shorter standby delay as on normal output to release
2514 // hardware resources as soon as possible
2515 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2516
Eric Laurentfeb0db62011-07-22 09:04:31 -07002517 acquireWakeLock();
2518
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519 while (!exitPending())
2520 {
2521 bool rampVolume;
2522 uint16_t leftVol;
2523 uint16_t rightVol;
2524 Vector< sp<EffectChain> > effectChains;
2525
2526 processConfigEvents();
2527
2528 mixerStatus = MIXER_IDLE;
2529
2530 { // scope for the mLock
2531
2532 Mutex::Autolock _l(mLock);
2533
2534 if (checkForNewParameters_l()) {
2535 mixBufferSize = mFrameCount*mFrameSize;
2536 activeSleepTime = activeSleepTimeUs();
2537 idleSleepTime = idleSleepTimeUs();
2538 standbyDelay = microseconds(activeSleepTime*2);
2539 }
2540
2541 // put audio hardware into standby after short delay
2542 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2543 mSuspended) {
2544 // wait until we have something to do...
2545 if (!mStandby) {
2546 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002547 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 mStandby = true;
2549 mBytesWritten = 0;
2550 }
2551
2552 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2553 // we're about to wait, flush the binder command buffer
2554 IPCThreadState::self()->flushCommands();
2555
2556 if (exitPending()) break;
2557
Eric Laurentfeb0db62011-07-22 09:04:31 -07002558 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2560 mWaitWorkCV.wait(mLock);
2561 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002562 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563
2564 if (mMasterMute == false) {
2565 char value[PROPERTY_VALUE_MAX];
2566 property_get("ro.audio.silent", value, "0");
2567 if (atoi(value)) {
2568 LOGD("Silence is golden");
2569 setMasterMute(true);
2570 }
2571 }
2572
2573 standbyTime = systemTime() + standbyDelay;
2574 sleepTime = idleSleepTime;
2575 continue;
2576 }
2577 }
2578
2579 effectChains = mEffectChains;
2580
2581 // find out which tracks need to be processed
2582 if (mActiveTracks.size() != 0) {
2583 sp<Track> t = mActiveTracks[0].promote();
2584 if (t == 0) continue;
2585
2586 Track* const track = t.get();
2587 audio_track_cblk_t* cblk = track->cblk();
2588
2589 // The first time a track is added we wait
2590 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002591 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592 !track->isPaused() && !track->isTerminated())
2593 {
2594 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2595
2596 if (track->mFillingUpStatus == Track::FS_FILLED) {
2597 track->mFillingUpStatus = Track::FS_ACTIVE;
2598 mLeftVolFloat = mRightVolFloat = 0;
2599 mLeftVolShort = mRightVolShort = 0;
2600 if (track->mState == TrackBase::RESUMING) {
2601 track->mState = TrackBase::ACTIVE;
2602 rampVolume = true;
2603 }
2604 } else if (cblk->server != 0) {
2605 // If the track is stopped before the first frame was mixed,
2606 // do not apply ramp
2607 rampVolume = true;
2608 }
2609 // compute volume for this track
2610 float left, right;
2611 if (track->isMuted() || mMasterMute || track->isPausing() ||
2612 mStreamTypes[track->type()].mute) {
2613 left = right = 0;
2614 if (track->isPausing()) {
2615 track->setPaused();
2616 }
2617 } else {
2618 float typeVolume = mStreamTypes[track->type()].volume;
2619 float v = mMasterVolume * typeVolume;
2620 float v_clamped = v * cblk->volume[0];
2621 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2622 left = v_clamped/MAX_GAIN;
2623 v_clamped = v * cblk->volume[1];
2624 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2625 right = v_clamped/MAX_GAIN;
2626 }
2627
2628 if (left != mLeftVolFloat || right != mRightVolFloat) {
2629 mLeftVolFloat = left;
2630 mRightVolFloat = right;
2631
2632 // If audio HAL implements volume control,
2633 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002634 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002635 left = 1.0f;
2636 right = 1.0f;
2637 }
2638
2639 // Convert volumes from float to 8.24
2640 uint32_t vl = (uint32_t)(left * (1 << 24));
2641 uint32_t vr = (uint32_t)(right * (1 << 24));
2642
2643 // Delegate volume control to effect in track effect chain if needed
2644 // only one effect chain can be present on DirectOutputThread, so if
2645 // there is one, the track is connected to it
2646 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002647 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002648 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 rampVolume = false;
2650 }
2651 }
2652
2653 // Convert volumes from 8.24 to 4.12 format
2654 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2655 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2656 leftVol = (uint16_t)v_clamped;
2657 v_clamped = (vr + (1 << 11)) >> 12;
2658 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2659 rightVol = (uint16_t)v_clamped;
2660 } else {
2661 leftVol = mLeftVolShort;
2662 rightVol = mRightVolShort;
2663 rampVolume = false;
2664 }
2665
2666 // reset retry count
2667 track->mRetryCount = kMaxTrackRetriesDirect;
2668 activeTrack = t;
2669 mixerStatus = MIXER_TRACKS_READY;
2670 } else {
2671 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2672 if (track->isStopped()) {
2673 track->reset();
2674 }
2675 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2676 // We have consumed all the buffers of this track.
2677 // Remove it from the list of active tracks.
2678 trackToRemove = track;
2679 } else {
2680 // No buffers for this track. Give it a few chances to
2681 // fill a buffer, then remove it from active list.
2682 if (--(track->mRetryCount) <= 0) {
2683 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2684 trackToRemove = track;
2685 } else {
2686 mixerStatus = MIXER_TRACKS_ENABLED;
2687 }
2688 }
2689 }
2690 }
2691
2692 // remove all the tracks that need to be...
2693 if (UNLIKELY(trackToRemove != 0)) {
2694 mActiveTracks.remove(trackToRemove);
2695 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002696 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2697 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002698 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002699 }
2700 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002701 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002702 }
2703 }
2704
Eric Laurentde070132010-07-13 04:45:46 -07002705 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002706 }
2707
2708 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2709 AudioBufferProvider::Buffer buffer;
2710 size_t frameCount = mFrameCount;
2711 curBuf = (int8_t *)mMixBuffer;
2712 // output audio to hardware
2713 while (frameCount) {
2714 buffer.frameCount = frameCount;
2715 activeTrack->getNextBuffer(&buffer);
2716 if (UNLIKELY(buffer.raw == 0)) {
2717 memset(curBuf, 0, frameCount * mFrameSize);
2718 break;
2719 }
2720 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2721 frameCount -= buffer.frameCount;
2722 curBuf += buffer.frameCount * mFrameSize;
2723 activeTrack->releaseBuffer(&buffer);
2724 }
2725 sleepTime = 0;
2726 standbyTime = systemTime() + standbyDelay;
2727 } else {
2728 if (sleepTime == 0) {
2729 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2730 sleepTime = activeSleepTime;
2731 } else {
2732 sleepTime = idleSleepTime;
2733 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002734 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002735 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2736 sleepTime = 0;
2737 }
2738 }
2739
2740 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002741 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 }
2743 // sleepTime == 0 means we must write to audio hardware
2744 if (sleepTime == 0) {
2745 if (mixerStatus == MIXER_TRACKS_READY) {
2746 applyVolume(leftVol, rightVol, rampVolume);
2747 }
2748 for (size_t i = 0; i < effectChains.size(); i ++) {
2749 effectChains[i]->process_l();
2750 }
Eric Laurentde070132010-07-13 04:45:46 -07002751 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002752
2753 mLastWriteTime = systemTime();
2754 mInWrite = true;
2755 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002756 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2758 mNumWrites++;
2759 mInWrite = false;
2760 mStandby = false;
2761 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002762 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763 usleep(sleepTime);
2764 }
2765
2766 // finally let go of removed track, without the lock held
2767 // since we can't guarantee the destructors won't acquire that
2768 // same lock.
2769 trackToRemove.clear();
2770 activeTrack.clear();
2771
2772 // Effect chains will be actually deleted here if they were removed from
2773 // mEffectChains list during mixing or effects processing
2774 effectChains.clear();
2775 }
2776
2777 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002778 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 }
2780
Eric Laurentfeb0db62011-07-22 09:04:31 -07002781 releaseWakeLock();
2782
Mathias Agopian65ab4712010-07-14 17:59:35 -07002783 LOGV("DirectOutputThread %p exiting", this);
2784 return false;
2785}
2786
2787// getTrackName_l() must be called with ThreadBase::mLock held
2788int AudioFlinger::DirectOutputThread::getTrackName_l()
2789{
2790 return 0;
2791}
2792
2793// deleteTrackName_l() must be called with ThreadBase::mLock held
2794void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2795{
2796}
2797
2798// checkForNewParameters_l() must be called with ThreadBase::mLock held
2799bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2800{
2801 bool reconfig = false;
2802
2803 while (!mNewParameters.isEmpty()) {
2804 status_t status = NO_ERROR;
2805 String8 keyValuePair = mNewParameters[0];
2806 AudioParameter param = AudioParameter(keyValuePair);
2807 int value;
2808
2809 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2810 // do not accept frame count changes if tracks are open as the track buffer
2811 // size depends on frame count and correct behavior would not be garantied
2812 // if frame count is changed after track creation
2813 if (!mTracks.isEmpty()) {
2814 status = INVALID_OPERATION;
2815 } else {
2816 reconfig = true;
2817 }
2818 }
2819 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002820 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002821 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002823 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 mStandby = true;
2825 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002826 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002827 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002828 }
2829 if (status == NO_ERROR && reconfig) {
2830 readOutputParameters();
2831 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2832 }
2833 }
2834
2835 mNewParameters.removeAt(0);
2836
2837 mParamStatus = status;
2838 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002839 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2840 // already timed out waiting for the status and will never signal the condition.
2841 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 }
2843 return reconfig;
2844}
2845
2846uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2847{
2848 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002849 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002850 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002851 } else {
2852 time = 10000;
2853 }
2854 return time;
2855}
2856
2857uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2858{
2859 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002860 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002861 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862 } else {
2863 time = 10000;
2864 }
2865 return time;
2866}
2867
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002868uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2869{
2870 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002871 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002872 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2873 } else {
2874 time = 10000;
2875 }
2876 return time;
2877}
2878
2879
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880// ----------------------------------------------------------------------------
2881
2882AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2883 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2884{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002885 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 addOutputTrack(mainThread);
2887}
2888
2889AudioFlinger::DuplicatingThread::~DuplicatingThread()
2890{
2891 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2892 mOutputTracks[i]->destroy();
2893 }
2894 mOutputTracks.clear();
2895}
2896
2897bool AudioFlinger::DuplicatingThread::threadLoop()
2898{
2899 Vector< sp<Track> > tracksToRemove;
2900 uint32_t mixerStatus = MIXER_IDLE;
2901 nsecs_t standbyTime = systemTime();
2902 size_t mixBufferSize = mFrameCount*mFrameSize;
2903 SortedVector< sp<OutputTrack> > outputTracks;
2904 uint32_t writeFrames = 0;
2905 uint32_t activeSleepTime = activeSleepTimeUs();
2906 uint32_t idleSleepTime = idleSleepTimeUs();
2907 uint32_t sleepTime = idleSleepTime;
2908 Vector< sp<EffectChain> > effectChains;
2909
Eric Laurentfeb0db62011-07-22 09:04:31 -07002910 acquireWakeLock();
2911
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 while (!exitPending())
2913 {
2914 processConfigEvents();
2915
2916 mixerStatus = MIXER_IDLE;
2917 { // scope for the mLock
2918
2919 Mutex::Autolock _l(mLock);
2920
2921 if (checkForNewParameters_l()) {
2922 mixBufferSize = mFrameCount*mFrameSize;
2923 updateWaitTime();
2924 activeSleepTime = activeSleepTimeUs();
2925 idleSleepTime = idleSleepTimeUs();
2926 }
2927
2928 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2929
2930 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2931 outputTracks.add(mOutputTracks[i]);
2932 }
2933
2934 // put audio hardware into standby after short delay
2935 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2936 mSuspended) {
2937 if (!mStandby) {
2938 for (size_t i = 0; i < outputTracks.size(); i++) {
2939 outputTracks[i]->stop();
2940 }
2941 mStandby = true;
2942 mBytesWritten = 0;
2943 }
2944
2945 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2946 // we're about to wait, flush the binder command buffer
2947 IPCThreadState::self()->flushCommands();
2948 outputTracks.clear();
2949
2950 if (exitPending()) break;
2951
Eric Laurentfeb0db62011-07-22 09:04:31 -07002952 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2954 mWaitWorkCV.wait(mLock);
2955 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002956 acquireWakeLock_l();
2957
Mathias Agopian65ab4712010-07-14 17:59:35 -07002958 if (mMasterMute == false) {
2959 char value[PROPERTY_VALUE_MAX];
2960 property_get("ro.audio.silent", value, "0");
2961 if (atoi(value)) {
2962 LOGD("Silence is golden");
2963 setMasterMute(true);
2964 }
2965 }
2966
2967 standbyTime = systemTime() + kStandbyTimeInNsecs;
2968 sleepTime = idleSleepTime;
2969 continue;
2970 }
2971 }
2972
2973 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2974
2975 // prevent any changes in effect chain list and in each effect chain
2976 // during mixing and effect process as the audio buffers could be deleted
2977 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002978 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002979 }
2980
2981 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2982 // mix buffers...
2983 if (outputsReady(outputTracks)) {
2984 mAudioMixer->process();
2985 } else {
2986 memset(mMixBuffer, 0, mixBufferSize);
2987 }
2988 sleepTime = 0;
2989 writeFrames = mFrameCount;
2990 } else {
2991 if (sleepTime == 0) {
2992 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2993 sleepTime = activeSleepTime;
2994 } else {
2995 sleepTime = idleSleepTime;
2996 }
2997 } else if (mBytesWritten != 0) {
2998 // flush remaining overflow buffers in output tracks
2999 for (size_t i = 0; i < outputTracks.size(); i++) {
3000 if (outputTracks[i]->isActive()) {
3001 sleepTime = 0;
3002 writeFrames = 0;
3003 memset(mMixBuffer, 0, mixBufferSize);
3004 break;
3005 }
3006 }
3007 }
3008 }
3009
3010 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003011 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 }
3013 // sleepTime == 0 means we must write to audio hardware
3014 if (sleepTime == 0) {
3015 for (size_t i = 0; i < effectChains.size(); i ++) {
3016 effectChains[i]->process_l();
3017 }
3018 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003019 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003020
3021 standbyTime = systemTime() + kStandbyTimeInNsecs;
3022 for (size_t i = 0; i < outputTracks.size(); i++) {
3023 outputTracks[i]->write(mMixBuffer, writeFrames);
3024 }
3025 mStandby = false;
3026 mBytesWritten += mixBufferSize;
3027 } else {
3028 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003029 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003030 usleep(sleepTime);
3031 }
3032
3033 // finally let go of all our tracks, without the lock held
3034 // since we can't guarantee the destructors won't acquire that
3035 // same lock.
3036 tracksToRemove.clear();
3037 outputTracks.clear();
3038
3039 // Effect chains will be actually deleted here if they were removed from
3040 // mEffectChains list during mixing or effects processing
3041 effectChains.clear();
3042 }
3043
Eric Laurentfeb0db62011-07-22 09:04:31 -07003044 releaseWakeLock();
3045
Mathias Agopian65ab4712010-07-14 17:59:35 -07003046 return false;
3047}
3048
3049void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3050{
3051 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3052 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3053 this,
3054 mSampleRate,
3055 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003056 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057 frameCount);
3058 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003059 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003060 mOutputTracks.add(outputTrack);
3061 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3062 updateWaitTime();
3063 }
3064}
3065
3066void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3067{
3068 Mutex::Autolock _l(mLock);
3069 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3070 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3071 mOutputTracks[i]->destroy();
3072 mOutputTracks.removeAt(i);
3073 updateWaitTime();
3074 return;
3075 }
3076 }
3077 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3078}
3079
3080void AudioFlinger::DuplicatingThread::updateWaitTime()
3081{
3082 mWaitTimeMs = UINT_MAX;
3083 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3084 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3085 if (strong != NULL) {
3086 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3087 if (waitTimeMs < mWaitTimeMs) {
3088 mWaitTimeMs = waitTimeMs;
3089 }
3090 }
3091 }
3092}
3093
3094
3095bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3096{
3097 for (size_t i = 0; i < outputTracks.size(); i++) {
3098 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3099 if (thread == 0) {
3100 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3101 return false;
3102 }
3103 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3104 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3105 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3106 return false;
3107 }
3108 }
3109 return true;
3110}
3111
3112uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3113{
3114 return (mWaitTimeMs * 1000) / 2;
3115}
3116
3117// ----------------------------------------------------------------------------
3118
3119// TrackBase constructor must be called with AudioFlinger::mLock held
3120AudioFlinger::ThreadBase::TrackBase::TrackBase(
3121 const wp<ThreadBase>& thread,
3122 const sp<Client>& client,
3123 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003124 uint32_t format,
3125 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003126 int frameCount,
3127 uint32_t flags,
3128 const sp<IMemory>& sharedBuffer,
3129 int sessionId)
3130 : RefBase(),
3131 mThread(thread),
3132 mClient(client),
3133 mCblk(0),
3134 mFrameCount(0),
3135 mState(IDLE),
3136 mClientTid(-1),
3137 mFormat(format),
3138 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3139 mSessionId(sessionId)
3140{
3141 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3142
3143 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3144 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003145 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003146 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3147 if (sharedBuffer == 0) {
3148 size += bufferSize;
3149 }
3150
3151 if (client != NULL) {
3152 mCblkMemory = client->heap()->allocate(size);
3153 if (mCblkMemory != 0) {
3154 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3155 if (mCblk) { // construct the shared structure in-place.
3156 new(mCblk) audio_track_cblk_t();
3157 // clear all buffers
3158 mCblk->frameCount = frameCount;
3159 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003160 mChannelCount = channelCount;
3161 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 if (sharedBuffer == 0) {
3163 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3164 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3165 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003166 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 mCblk->flags = CBLK_UNDERRUN_ON;
3168 } else {
3169 mBuffer = sharedBuffer->pointer();
3170 }
3171 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3172 }
3173 } else {
3174 LOGE("not enough memory for AudioTrack size=%u", size);
3175 client->heap()->dump("AudioTrack");
3176 return;
3177 }
3178 } else {
3179 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3180 if (mCblk) { // construct the shared structure in-place.
3181 new(mCblk) audio_track_cblk_t();
3182 // clear all buffers
3183 mCblk->frameCount = frameCount;
3184 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003185 mChannelCount = channelCount;
3186 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3188 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3189 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003190 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003191 mCblk->flags = CBLK_UNDERRUN_ON;
3192 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3193 }
3194 }
3195}
3196
3197AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3198{
3199 if (mCblk) {
3200 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3201 if (mClient == NULL) {
3202 delete mCblk;
3203 }
3204 }
3205 mCblkMemory.clear(); // and free the shared memory
3206 if (mClient != NULL) {
3207 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3208 mClient.clear();
3209 }
3210}
3211
3212void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3213{
3214 buffer->raw = 0;
3215 mFrameCount = buffer->frameCount;
3216 step();
3217 buffer->frameCount = 0;
3218}
3219
3220bool AudioFlinger::ThreadBase::TrackBase::step() {
3221 bool result;
3222 audio_track_cblk_t* cblk = this->cblk();
3223
3224 result = cblk->stepServer(mFrameCount);
3225 if (!result) {
3226 LOGV("stepServer failed acquiring cblk mutex");
3227 mFlags |= STEPSERVER_FAILED;
3228 }
3229 return result;
3230}
3231
3232void AudioFlinger::ThreadBase::TrackBase::reset() {
3233 audio_track_cblk_t* cblk = this->cblk();
3234
3235 cblk->user = 0;
3236 cblk->server = 0;
3237 cblk->userBase = 0;
3238 cblk->serverBase = 0;
3239 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3240 LOGV("TrackBase::reset");
3241}
3242
3243sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3244{
3245 return mCblkMemory;
3246}
3247
3248int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3249 return (int)mCblk->sampleRate;
3250}
3251
3252int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003253 return (const int)mChannelCount;
3254}
3255
3256uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3257 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258}
3259
3260void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3261 audio_track_cblk_t* cblk = this->cblk();
3262 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3263 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3264
3265 // Check validity of returned pointer in case the track control block would have been corrupted.
3266 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3267 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3268 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 -07003269 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003270 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003271 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 return 0;
3273 }
3274
3275 return bufferStart;
3276}
3277
3278// ----------------------------------------------------------------------------
3279
3280// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3281AudioFlinger::PlaybackThread::Track::Track(
3282 const wp<ThreadBase>& thread,
3283 const sp<Client>& client,
3284 int streamType,
3285 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003286 uint32_t format,
3287 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288 int frameCount,
3289 const sp<IMemory>& sharedBuffer,
3290 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003291 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003292 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3293 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003294{
3295 if (mCblk != NULL) {
3296 sp<ThreadBase> baseThread = thread.promote();
3297 if (baseThread != 0) {
3298 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3299 mName = playbackThread->getTrackName_l();
3300 mMainBuffer = playbackThread->mixBuffer();
3301 }
3302 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3303 if (mName < 0) {
3304 LOGE("no more track names available");
3305 }
3306 mVolume[0] = 1.0f;
3307 mVolume[1] = 1.0f;
3308 mStreamType = streamType;
3309 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3310 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003311 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003312 }
3313}
3314
3315AudioFlinger::PlaybackThread::Track::~Track()
3316{
3317 LOGV("PlaybackThread::Track destructor");
3318 sp<ThreadBase> thread = mThread.promote();
3319 if (thread != 0) {
3320 Mutex::Autolock _l(thread->mLock);
3321 mState = TERMINATED;
3322 }
3323}
3324
3325void AudioFlinger::PlaybackThread::Track::destroy()
3326{
3327 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3328 // by removing it from mTracks vector, so there is a risk that this Tracks's
3329 // desctructor is called. As the destructor needs to lock mLock,
3330 // we must acquire a strong reference on this Track before locking mLock
3331 // here so that the destructor is called only when exiting this function.
3332 // On the other hand, as long as Track::destroy() is only called by
3333 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3334 // this Track with its member mTrack.
3335 sp<Track> keep(this);
3336 { // scope for mLock
3337 sp<ThreadBase> thread = mThread.promote();
3338 if (thread != 0) {
3339 if (!isOutputTrack()) {
3340 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003341 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003342 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003343 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003344
3345 // to track the speaker usage
3346 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003347 }
3348 AudioSystem::releaseOutput(thread->id());
3349 }
3350 Mutex::Autolock _l(thread->mLock);
3351 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3352 playbackThread->destroyTrack_l(this);
3353 }
3354 }
3355}
3356
3357void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3358{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003359 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 -07003360 mName - AudioMixer::TRACK0,
3361 (mClient == NULL) ? getpid() : mClient->pid(),
3362 mStreamType,
3363 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003364 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 mSessionId,
3366 mFrameCount,
3367 mState,
3368 mMute,
3369 mFillingUpStatus,
3370 mCblk->sampleRate,
3371 mCblk->volume[0],
3372 mCblk->volume[1],
3373 mCblk->server,
3374 mCblk->user,
3375 (int)mMainBuffer,
3376 (int)mAuxBuffer);
3377}
3378
3379status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3380{
3381 audio_track_cblk_t* cblk = this->cblk();
3382 uint32_t framesReady;
3383 uint32_t framesReq = buffer->frameCount;
3384
3385 // Check if last stepServer failed, try to step now
3386 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3387 if (!step()) goto getNextBuffer_exit;
3388 LOGV("stepServer recovered");
3389 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3390 }
3391
3392 framesReady = cblk->framesReady();
3393
3394 if (LIKELY(framesReady)) {
3395 uint32_t s = cblk->server;
3396 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3397
3398 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3399 if (framesReq > framesReady) {
3400 framesReq = framesReady;
3401 }
3402 if (s + framesReq > bufferEnd) {
3403 framesReq = bufferEnd - s;
3404 }
3405
3406 buffer->raw = getBuffer(s, framesReq);
3407 if (buffer->raw == 0) goto getNextBuffer_exit;
3408
3409 buffer->frameCount = framesReq;
3410 return NO_ERROR;
3411 }
3412
3413getNextBuffer_exit:
3414 buffer->raw = 0;
3415 buffer->frameCount = 0;
3416 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3417 return NOT_ENOUGH_DATA;
3418}
3419
3420bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003421 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003422
3423 if (mCblk->framesReady() >= mCblk->frameCount ||
3424 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3425 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003426 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003427 return true;
3428 }
3429 return false;
3430}
3431
3432status_t AudioFlinger::PlaybackThread::Track::start()
3433{
3434 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003435 LOGV("start(%d), calling thread %d session %d",
3436 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003437 sp<ThreadBase> thread = mThread.promote();
3438 if (thread != 0) {
3439 Mutex::Autolock _l(thread->mLock);
3440 int state = mState;
3441 // here the track could be either new, or restarted
3442 // in both cases "unstop" the track
3443 if (mState == PAUSED) {
3444 mState = TrackBase::RESUMING;
3445 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3446 } else {
3447 mState = TrackBase::ACTIVE;
3448 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3449 }
3450
3451 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3452 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003453 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003454 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003455 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003457
3458 // to track the speaker usage
3459 if (status == NO_ERROR) {
3460 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003462 }
3463 if (status == NO_ERROR) {
3464 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3465 playbackThread->addTrack_l(this);
3466 } else {
3467 mState = state;
3468 }
3469 } else {
3470 status = BAD_VALUE;
3471 }
3472 return status;
3473}
3474
3475void AudioFlinger::PlaybackThread::Track::stop()
3476{
3477 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3478 sp<ThreadBase> thread = mThread.promote();
3479 if (thread != 0) {
3480 Mutex::Autolock _l(thread->mLock);
3481 int state = mState;
3482 if (mState > STOPPED) {
3483 mState = STOPPED;
3484 // If the track is not active (PAUSED and buffers full), flush buffers
3485 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3486 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3487 reset();
3488 }
3489 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3490 }
3491 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3492 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003493 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003494 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003495 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003497
3498 // to track the speaker usage
3499 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 }
3501 }
3502}
3503
3504void AudioFlinger::PlaybackThread::Track::pause()
3505{
3506 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3507 sp<ThreadBase> thread = mThread.promote();
3508 if (thread != 0) {
3509 Mutex::Autolock _l(thread->mLock);
3510 if (mState == ACTIVE || mState == RESUMING) {
3511 mState = PAUSING;
3512 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3513 if (!isOutputTrack()) {
3514 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003515 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003516 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003517 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003519
3520 // to track the speaker usage
3521 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 }
3523 }
3524 }
3525}
3526
3527void AudioFlinger::PlaybackThread::Track::flush()
3528{
3529 LOGV("flush(%d)", mName);
3530 sp<ThreadBase> thread = mThread.promote();
3531 if (thread != 0) {
3532 Mutex::Autolock _l(thread->mLock);
3533 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3534 return;
3535 }
3536 // No point remaining in PAUSED state after a flush => go to
3537 // STOPPED state
3538 mState = STOPPED;
3539
Eric Laurent38ccae22011-03-28 18:37:07 -07003540 // do not reset the track if it is still in the process of being stopped or paused.
3541 // this will be done by prepareTracks_l() when the track is stopped.
3542 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3543 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3544 reset();
3545 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546 }
3547}
3548
3549void AudioFlinger::PlaybackThread::Track::reset()
3550{
3551 // Do not reset twice to avoid discarding data written just after a flush and before
3552 // the audioflinger thread detects the track is stopped.
3553 if (!mResetDone) {
3554 TrackBase::reset();
3555 // Force underrun condition to avoid false underrun callback until first data is
3556 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003557 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3558 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559 mFillingUpStatus = FS_FILLING;
3560 mResetDone = true;
3561 }
3562}
3563
3564void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3565{
3566 mMute = muted;
3567}
3568
3569void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3570{
3571 mVolume[0] = left;
3572 mVolume[1] = right;
3573}
3574
3575status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3576{
3577 status_t status = DEAD_OBJECT;
3578 sp<ThreadBase> thread = mThread.promote();
3579 if (thread != 0) {
3580 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3581 status = playbackThread->attachAuxEffect(this, EffectId);
3582 }
3583 return status;
3584}
3585
3586void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3587{
3588 mAuxEffectId = EffectId;
3589 mAuxBuffer = buffer;
3590}
3591
3592// ----------------------------------------------------------------------------
3593
3594// RecordTrack constructor must be called with AudioFlinger::mLock held
3595AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3596 const wp<ThreadBase>& thread,
3597 const sp<Client>& client,
3598 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003599 uint32_t format,
3600 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 int frameCount,
3602 uint32_t flags,
3603 int sessionId)
3604 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003605 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606 mOverflow(false)
3607{
3608 if (mCblk != NULL) {
3609 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003610 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003611 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003612 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003613 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 } else {
3615 mCblk->frameSize = sizeof(int8_t);
3616 }
3617 }
3618}
3619
3620AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3621{
3622 sp<ThreadBase> thread = mThread.promote();
3623 if (thread != 0) {
3624 AudioSystem::releaseInput(thread->id());
3625 }
3626}
3627
3628status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3629{
3630 audio_track_cblk_t* cblk = this->cblk();
3631 uint32_t framesAvail;
3632 uint32_t framesReq = buffer->frameCount;
3633
3634 // Check if last stepServer failed, try to step now
3635 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3636 if (!step()) goto getNextBuffer_exit;
3637 LOGV("stepServer recovered");
3638 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3639 }
3640
3641 framesAvail = cblk->framesAvailable_l();
3642
3643 if (LIKELY(framesAvail)) {
3644 uint32_t s = cblk->server;
3645 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3646
3647 if (framesReq > framesAvail) {
3648 framesReq = framesAvail;
3649 }
3650 if (s + framesReq > bufferEnd) {
3651 framesReq = bufferEnd - s;
3652 }
3653
3654 buffer->raw = getBuffer(s, framesReq);
3655 if (buffer->raw == 0) goto getNextBuffer_exit;
3656
3657 buffer->frameCount = framesReq;
3658 return NO_ERROR;
3659 }
3660
3661getNextBuffer_exit:
3662 buffer->raw = 0;
3663 buffer->frameCount = 0;
3664 return NOT_ENOUGH_DATA;
3665}
3666
3667status_t AudioFlinger::RecordThread::RecordTrack::start()
3668{
3669 sp<ThreadBase> thread = mThread.promote();
3670 if (thread != 0) {
3671 RecordThread *recordThread = (RecordThread *)thread.get();
3672 return recordThread->start(this);
3673 } else {
3674 return BAD_VALUE;
3675 }
3676}
3677
3678void AudioFlinger::RecordThread::RecordTrack::stop()
3679{
3680 sp<ThreadBase> thread = mThread.promote();
3681 if (thread != 0) {
3682 RecordThread *recordThread = (RecordThread *)thread.get();
3683 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003684 TrackBase::reset();
3685 // Force overerrun condition to avoid false overrun callback until first data is
3686 // read from buffer
3687 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 }
3689}
3690
3691void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3692{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003693 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003694 (mClient == NULL) ? getpid() : mClient->pid(),
3695 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003696 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003697 mSessionId,
3698 mFrameCount,
3699 mState,
3700 mCblk->sampleRate,
3701 mCblk->server,
3702 mCblk->user);
3703}
3704
3705
3706// ----------------------------------------------------------------------------
3707
3708AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3709 const wp<ThreadBase>& thread,
3710 DuplicatingThread *sourceThread,
3711 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003712 uint32_t format,
3713 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003715 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 mActive(false), mSourceThread(sourceThread)
3717{
3718
3719 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3720 if (mCblk != NULL) {
3721 mCblk->flags |= CBLK_DIRECTION_OUT;
3722 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3723 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3724 mOutBuffer.frameCount = 0;
3725 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003726 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3727 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3728 mCblk, mBuffer, mCblk->buffers,
3729 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730 } else {
3731 LOGW("Error creating output track on thread %p", playbackThread);
3732 }
3733}
3734
3735AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3736{
3737 clearBufferQueue();
3738}
3739
3740status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3741{
3742 status_t status = Track::start();
3743 if (status != NO_ERROR) {
3744 return status;
3745 }
3746
3747 mActive = true;
3748 mRetryCount = 127;
3749 return status;
3750}
3751
3752void AudioFlinger::PlaybackThread::OutputTrack::stop()
3753{
3754 Track::stop();
3755 clearBufferQueue();
3756 mOutBuffer.frameCount = 0;
3757 mActive = false;
3758}
3759
3760bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3761{
3762 Buffer *pInBuffer;
3763 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003764 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003765 bool outputBufferFull = false;
3766 inBuffer.frameCount = frames;
3767 inBuffer.i16 = data;
3768
3769 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3770
3771 if (!mActive && frames != 0) {
3772 start();
3773 sp<ThreadBase> thread = mThread.promote();
3774 if (thread != 0) {
3775 MixerThread *mixerThread = (MixerThread *)thread.get();
3776 if (mCblk->frameCount > frames){
3777 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3778 uint32_t startFrames = (mCblk->frameCount - frames);
3779 pInBuffer = new Buffer;
3780 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3781 pInBuffer->frameCount = startFrames;
3782 pInBuffer->i16 = pInBuffer->mBuffer;
3783 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3784 mBufferQueue.add(pInBuffer);
3785 } else {
3786 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3787 }
3788 }
3789 }
3790 }
3791
3792 while (waitTimeLeftMs) {
3793 // First write pending buffers, then new data
3794 if (mBufferQueue.size()) {
3795 pInBuffer = mBufferQueue.itemAt(0);
3796 } else {
3797 pInBuffer = &inBuffer;
3798 }
3799
3800 if (pInBuffer->frameCount == 0) {
3801 break;
3802 }
3803
3804 if (mOutBuffer.frameCount == 0) {
3805 mOutBuffer.frameCount = pInBuffer->frameCount;
3806 nsecs_t startTime = systemTime();
3807 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3808 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3809 outputBufferFull = true;
3810 break;
3811 }
3812 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3813 if (waitTimeLeftMs >= waitTimeMs) {
3814 waitTimeLeftMs -= waitTimeMs;
3815 } else {
3816 waitTimeLeftMs = 0;
3817 }
3818 }
3819
3820 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3821 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3822 mCblk->stepUser(outFrames);
3823 pInBuffer->frameCount -= outFrames;
3824 pInBuffer->i16 += outFrames * channelCount;
3825 mOutBuffer.frameCount -= outFrames;
3826 mOutBuffer.i16 += outFrames * channelCount;
3827
3828 if (pInBuffer->frameCount == 0) {
3829 if (mBufferQueue.size()) {
3830 mBufferQueue.removeAt(0);
3831 delete [] pInBuffer->mBuffer;
3832 delete pInBuffer;
3833 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3834 } else {
3835 break;
3836 }
3837 }
3838 }
3839
3840 // If we could not write all frames, allocate a buffer and queue it for next time.
3841 if (inBuffer.frameCount) {
3842 sp<ThreadBase> thread = mThread.promote();
3843 if (thread != 0 && !thread->standby()) {
3844 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3845 pInBuffer = new Buffer;
3846 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3847 pInBuffer->frameCount = inBuffer.frameCount;
3848 pInBuffer->i16 = pInBuffer->mBuffer;
3849 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3850 mBufferQueue.add(pInBuffer);
3851 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3852 } else {
3853 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3854 }
3855 }
3856 }
3857
3858 // Calling write() with a 0 length buffer, means that no more data will be written:
3859 // If no more buffers are pending, fill output track buffer to make sure it is started
3860 // by output mixer.
3861 if (frames == 0 && mBufferQueue.size() == 0) {
3862 if (mCblk->user < mCblk->frameCount) {
3863 frames = mCblk->frameCount - mCblk->user;
3864 pInBuffer = new Buffer;
3865 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3866 pInBuffer->frameCount = frames;
3867 pInBuffer->i16 = pInBuffer->mBuffer;
3868 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3869 mBufferQueue.add(pInBuffer);
3870 } else if (mActive) {
3871 stop();
3872 }
3873 }
3874
3875 return outputBufferFull;
3876}
3877
3878status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3879{
3880 int active;
3881 status_t result;
3882 audio_track_cblk_t* cblk = mCblk;
3883 uint32_t framesReq = buffer->frameCount;
3884
3885// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3886 buffer->frameCount = 0;
3887
3888 uint32_t framesAvail = cblk->framesAvailable();
3889
3890
3891 if (framesAvail == 0) {
3892 Mutex::Autolock _l(cblk->lock);
3893 goto start_loop_here;
3894 while (framesAvail == 0) {
3895 active = mActive;
3896 if (UNLIKELY(!active)) {
3897 LOGV("Not active and NO_MORE_BUFFERS");
3898 return AudioTrack::NO_MORE_BUFFERS;
3899 }
3900 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3901 if (result != NO_ERROR) {
3902 return AudioTrack::NO_MORE_BUFFERS;
3903 }
3904 // read the server count again
3905 start_loop_here:
3906 framesAvail = cblk->framesAvailable_l();
3907 }
3908 }
3909
3910// if (framesAvail < framesReq) {
3911// return AudioTrack::NO_MORE_BUFFERS;
3912// }
3913
3914 if (framesReq > framesAvail) {
3915 framesReq = framesAvail;
3916 }
3917
3918 uint32_t u = cblk->user;
3919 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3920
3921 if (u + framesReq > bufferEnd) {
3922 framesReq = bufferEnd - u;
3923 }
3924
3925 buffer->frameCount = framesReq;
3926 buffer->raw = (void *)cblk->buffer(u);
3927 return NO_ERROR;
3928}
3929
3930
3931void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3932{
3933 size_t size = mBufferQueue.size();
3934 Buffer *pBuffer;
3935
3936 for (size_t i = 0; i < size; i++) {
3937 pBuffer = mBufferQueue.itemAt(i);
3938 delete [] pBuffer->mBuffer;
3939 delete pBuffer;
3940 }
3941 mBufferQueue.clear();
3942}
3943
3944// ----------------------------------------------------------------------------
3945
3946AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3947 : RefBase(),
3948 mAudioFlinger(audioFlinger),
3949 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3950 mPid(pid)
3951{
3952 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3953}
3954
3955// Client destructor must be called with AudioFlinger::mLock held
3956AudioFlinger::Client::~Client()
3957{
3958 mAudioFlinger->removeClient_l(mPid);
3959}
3960
3961const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3962{
3963 return mMemoryDealer;
3964}
3965
3966// ----------------------------------------------------------------------------
3967
3968AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3969 const sp<IAudioFlingerClient>& client,
3970 pid_t pid)
3971 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3972{
3973}
3974
3975AudioFlinger::NotificationClient::~NotificationClient()
3976{
3977 mClient.clear();
3978}
3979
3980void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3981{
3982 sp<NotificationClient> keep(this);
3983 {
3984 mAudioFlinger->removeNotificationClient(mPid);
3985 }
3986}
3987
3988// ----------------------------------------------------------------------------
3989
3990AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3991 : BnAudioTrack(),
3992 mTrack(track)
3993{
3994}
3995
3996AudioFlinger::TrackHandle::~TrackHandle() {
3997 // just stop the track on deletion, associated resources
3998 // will be freed from the main thread once all pending buffers have
3999 // been played. Unless it's not in the active track list, in which
4000 // case we free everything now...
4001 mTrack->destroy();
4002}
4003
4004status_t AudioFlinger::TrackHandle::start() {
4005 return mTrack->start();
4006}
4007
4008void AudioFlinger::TrackHandle::stop() {
4009 mTrack->stop();
4010}
4011
4012void AudioFlinger::TrackHandle::flush() {
4013 mTrack->flush();
4014}
4015
4016void AudioFlinger::TrackHandle::mute(bool e) {
4017 mTrack->mute(e);
4018}
4019
4020void AudioFlinger::TrackHandle::pause() {
4021 mTrack->pause();
4022}
4023
4024void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4025 mTrack->setVolume(left, right);
4026}
4027
4028sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4029 return mTrack->getCblk();
4030}
4031
4032status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4033{
4034 return mTrack->attachAuxEffect(EffectId);
4035}
4036
4037status_t AudioFlinger::TrackHandle::onTransact(
4038 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4039{
4040 return BnAudioTrack::onTransact(code, data, reply, flags);
4041}
4042
4043// ----------------------------------------------------------------------------
4044
4045sp<IAudioRecord> AudioFlinger::openRecord(
4046 pid_t pid,
4047 int input,
4048 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004049 uint32_t format,
4050 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004051 int frameCount,
4052 uint32_t flags,
4053 int *sessionId,
4054 status_t *status)
4055{
4056 sp<RecordThread::RecordTrack> recordTrack;
4057 sp<RecordHandle> recordHandle;
4058 sp<Client> client;
4059 wp<Client> wclient;
4060 status_t lStatus;
4061 RecordThread *thread;
4062 size_t inFrameCount;
4063 int lSessionId;
4064
4065 // check calling permissions
4066 if (!recordingAllowed()) {
4067 lStatus = PERMISSION_DENIED;
4068 goto Exit;
4069 }
4070
4071 // add client to list
4072 { // scope for mLock
4073 Mutex::Autolock _l(mLock);
4074 thread = checkRecordThread_l(input);
4075 if (thread == NULL) {
4076 lStatus = BAD_VALUE;
4077 goto Exit;
4078 }
4079
4080 wclient = mClients.valueFor(pid);
4081 if (wclient != NULL) {
4082 client = wclient.promote();
4083 } else {
4084 client = new Client(this, pid);
4085 mClients.add(pid, client);
4086 }
4087
4088 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004089 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 lSessionId = *sessionId;
4091 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004092 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004093 if (sessionId != NULL) {
4094 *sessionId = lSessionId;
4095 }
4096 }
4097 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004098 recordTrack = thread->createRecordTrack_l(client,
4099 sampleRate,
4100 format,
4101 channelMask,
4102 frameCount,
4103 flags,
4104 lSessionId,
4105 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004107 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4109 // destructor is called by the TrackBase destructor with mLock held
4110 client.clear();
4111 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 goto Exit;
4113 }
4114
4115 // return to handle to client
4116 recordHandle = new RecordHandle(recordTrack);
4117 lStatus = NO_ERROR;
4118
4119Exit:
4120 if (status) {
4121 *status = lStatus;
4122 }
4123 return recordHandle;
4124}
4125
4126// ----------------------------------------------------------------------------
4127
4128AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4129 : BnAudioRecord(),
4130 mRecordTrack(recordTrack)
4131{
4132}
4133
4134AudioFlinger::RecordHandle::~RecordHandle() {
4135 stop();
4136}
4137
4138status_t AudioFlinger::RecordHandle::start() {
4139 LOGV("RecordHandle::start()");
4140 return mRecordTrack->start();
4141}
4142
4143void AudioFlinger::RecordHandle::stop() {
4144 LOGV("RecordHandle::stop()");
4145 mRecordTrack->stop();
4146}
4147
4148sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4149 return mRecordTrack->getCblk();
4150}
4151
4152status_t AudioFlinger::RecordHandle::onTransact(
4153 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4154{
4155 return BnAudioRecord::onTransact(code, data, reply, flags);
4156}
4157
4158// ----------------------------------------------------------------------------
4159
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004160AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4161 AudioStreamIn *input,
4162 uint32_t sampleRate,
4163 uint32_t channels,
4164 int id,
4165 uint32_t device) :
4166 ThreadBase(audioFlinger, id, device),
4167 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004169 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004170
4171 snprintf(mName, kNameLength, "AudioIn_%d", id);
4172
Dima Zavinfce7a472011-04-19 22:30:36 -07004173 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 mReqSampleRate = sampleRate;
4175 readInputParameters();
4176}
4177
4178
4179AudioFlinger::RecordThread::~RecordThread()
4180{
4181 delete[] mRsmpInBuffer;
4182 if (mResampler != 0) {
4183 delete mResampler;
4184 delete[] mRsmpOutBuffer;
4185 }
4186}
4187
4188void AudioFlinger::RecordThread::onFirstRef()
4189{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004190 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191}
4192
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004193status_t AudioFlinger::RecordThread::readyToRun()
4194{
4195 status_t status = initCheck();
4196 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4197 return status;
4198}
4199
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200bool AudioFlinger::RecordThread::threadLoop()
4201{
4202 AudioBufferProvider::Buffer buffer;
4203 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004204 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205
Eric Laurent44d98482010-09-30 16:12:31 -07004206 nsecs_t lastWarning = 0;
4207
Eric Laurentfeb0db62011-07-22 09:04:31 -07004208 acquireWakeLock();
4209
Mathias Agopian65ab4712010-07-14 17:59:35 -07004210 // start recording
4211 while (!exitPending()) {
4212
4213 processConfigEvents();
4214
4215 { // scope for mLock
4216 Mutex::Autolock _l(mLock);
4217 checkForNewParameters_l();
4218 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4219 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004220 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221 mStandby = true;
4222 }
4223
4224 if (exitPending()) break;
4225
Eric Laurentfeb0db62011-07-22 09:04:31 -07004226 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 LOGV("RecordThread: loop stopping");
4228 // go to sleep
4229 mWaitWorkCV.wait(mLock);
4230 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004231 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 continue;
4233 }
4234 if (mActiveTrack != 0) {
4235 if (mActiveTrack->mState == TrackBase::PAUSING) {
4236 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004237 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238 mStandby = true;
4239 }
4240 mActiveTrack.clear();
4241 mStartStopCond.broadcast();
4242 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4243 if (mReqChannelCount != mActiveTrack->channelCount()) {
4244 mActiveTrack.clear();
4245 mStartStopCond.broadcast();
4246 } else if (mBytesRead != 0) {
4247 // record start succeeds only if first read from audio input
4248 // succeeds
4249 if (mBytesRead > 0) {
4250 mActiveTrack->mState = TrackBase::ACTIVE;
4251 } else {
4252 mActiveTrack.clear();
4253 }
4254 mStartStopCond.broadcast();
4255 }
4256 mStandby = false;
4257 }
4258 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004259 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260 }
4261
4262 if (mActiveTrack != 0) {
4263 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4264 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004265 unlockEffectChains(effectChains);
4266 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004267 continue;
4268 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004269 for (size_t i = 0; i < effectChains.size(); i ++) {
4270 effectChains[i]->process_l();
4271 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004272
Mathias Agopian65ab4712010-07-14 17:59:35 -07004273 buffer.frameCount = mFrameCount;
4274 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4275 size_t framesOut = buffer.frameCount;
4276 if (mResampler == 0) {
4277 // no resampling
4278 while (framesOut) {
4279 size_t framesIn = mFrameCount - mRsmpInIndex;
4280 if (framesIn) {
4281 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4282 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4283 if (framesIn > framesOut)
4284 framesIn = framesOut;
4285 mRsmpInIndex += framesIn;
4286 framesOut -= framesIn;
4287 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004288 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004289 memcpy(dst, src, framesIn * mFrameSize);
4290 } else {
4291 int16_t *src16 = (int16_t *)src;
4292 int16_t *dst16 = (int16_t *)dst;
4293 if (mChannelCount == 1) {
4294 while (framesIn--) {
4295 *dst16++ = *src16;
4296 *dst16++ = *src16++;
4297 }
4298 } else {
4299 while (framesIn--) {
4300 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4301 src16 += 2;
4302 }
4303 }
4304 }
4305 }
4306 if (framesOut && mFrameCount == mRsmpInIndex) {
4307 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004308 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004309 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004310 framesOut = 0;
4311 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004312 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004313 mRsmpInIndex = 0;
4314 }
4315 if (mBytesRead < 0) {
4316 LOGE("Error reading audio input");
4317 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4318 // Force input into standby so that it tries to
4319 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004320 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004321 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 }
4323 mRsmpInIndex = mFrameCount;
4324 framesOut = 0;
4325 buffer.frameCount = 0;
4326 }
4327 }
4328 }
4329 } else {
4330 // resampling
4331
4332 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4333 // alter output frame count as if we were expecting stereo samples
4334 if (mChannelCount == 1 && mReqChannelCount == 1) {
4335 framesOut >>= 1;
4336 }
4337 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4338 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4339 // are 32 bit aligned which should be always true.
4340 if (mChannelCount == 2 && mReqChannelCount == 1) {
4341 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4342 // the resampler always outputs stereo samples: do post stereo to mono conversion
4343 int16_t *src = (int16_t *)mRsmpOutBuffer;
4344 int16_t *dst = buffer.i16;
4345 while (framesOut--) {
4346 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4347 src += 2;
4348 }
4349 } else {
4350 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4351 }
4352
4353 }
4354 mActiveTrack->releaseBuffer(&buffer);
4355 mActiveTrack->overflow();
4356 }
4357 // client isn't retrieving buffers fast enough
4358 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004359 if (!mActiveTrack->setOverflow()) {
4360 nsecs_t now = systemTime();
4361 if ((now - lastWarning) > kWarningThrottle) {
4362 LOGW("RecordThread: buffer overflow");
4363 lastWarning = now;
4364 }
4365 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004366 // Release the processor for a while before asking for a new buffer.
4367 // This will give the application more chance to read from the buffer and
4368 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004369 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 }
4371 }
Eric Laurentec437d82011-07-26 20:54:46 -07004372 // enable changes in effect chain
4373 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004374 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004375 }
4376
4377 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004378 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004379 }
4380 mActiveTrack.clear();
4381
4382 mStartStopCond.broadcast();
4383
Eric Laurentfeb0db62011-07-22 09:04:31 -07004384 releaseWakeLock();
4385
Mathias Agopian65ab4712010-07-14 17:59:35 -07004386 LOGV("RecordThread %p exiting", this);
4387 return false;
4388}
4389
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004390
4391sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4392 const sp<AudioFlinger::Client>& client,
4393 uint32_t sampleRate,
4394 int format,
4395 int channelMask,
4396 int frameCount,
4397 uint32_t flags,
4398 int sessionId,
4399 status_t *status)
4400{
4401 sp<RecordTrack> track;
4402 status_t lStatus;
4403
4404 lStatus = initCheck();
4405 if (lStatus != NO_ERROR) {
4406 LOGE("Audio driver not initialized.");
4407 goto Exit;
4408 }
4409
4410 { // scope for mLock
4411 Mutex::Autolock _l(mLock);
4412
4413 track = new RecordTrack(this, client, sampleRate,
4414 format, channelMask, frameCount, flags, sessionId);
4415
4416 if (track->getCblk() == NULL) {
4417 lStatus = NO_MEMORY;
4418 goto Exit;
4419 }
4420
4421 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004422 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4423 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004424 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004425 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4426 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004427 }
4428 lStatus = NO_ERROR;
4429
4430Exit:
4431 if (status) {
4432 *status = lStatus;
4433 }
4434 return track;
4435}
4436
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4438{
4439 LOGV("RecordThread::start");
4440 sp <ThreadBase> strongMe = this;
4441 status_t status = NO_ERROR;
4442 {
4443 AutoMutex lock(&mLock);
4444 if (mActiveTrack != 0) {
4445 if (recordTrack != mActiveTrack.get()) {
4446 status = -EBUSY;
4447 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4448 mActiveTrack->mState = TrackBase::ACTIVE;
4449 }
4450 return status;
4451 }
4452
4453 recordTrack->mState = TrackBase::IDLE;
4454 mActiveTrack = recordTrack;
4455 mLock.unlock();
4456 status_t status = AudioSystem::startInput(mId);
4457 mLock.lock();
4458 if (status != NO_ERROR) {
4459 mActiveTrack.clear();
4460 return status;
4461 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004462 mRsmpInIndex = mFrameCount;
4463 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004464 if (mResampler != NULL) {
4465 mResampler->reset();
4466 }
4467 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004468 // signal thread to start
4469 LOGV("Signal record thread");
4470 mWaitWorkCV.signal();
4471 // do not wait for mStartStopCond if exiting
4472 if (mExiting) {
4473 mActiveTrack.clear();
4474 status = INVALID_OPERATION;
4475 goto startError;
4476 }
4477 mStartStopCond.wait(mLock);
4478 if (mActiveTrack == 0) {
4479 LOGV("Record failed to start");
4480 status = BAD_VALUE;
4481 goto startError;
4482 }
4483 LOGV("Record started OK");
4484 return status;
4485 }
4486startError:
4487 AudioSystem::stopInput(mId);
4488 return status;
4489}
4490
4491void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4492 LOGV("RecordThread::stop");
4493 sp <ThreadBase> strongMe = this;
4494 {
4495 AutoMutex lock(&mLock);
4496 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4497 mActiveTrack->mState = TrackBase::PAUSING;
4498 // do not wait for mStartStopCond if exiting
4499 if (mExiting) {
4500 return;
4501 }
4502 mStartStopCond.wait(mLock);
4503 // if we have been restarted, recordTrack == mActiveTrack.get() here
4504 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4505 mLock.unlock();
4506 AudioSystem::stopInput(mId);
4507 mLock.lock();
4508 LOGV("Record stopped OK");
4509 }
4510 }
4511 }
4512}
4513
4514status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4515{
4516 const size_t SIZE = 256;
4517 char buffer[SIZE];
4518 String8 result;
4519 pid_t pid = 0;
4520
4521 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4522 result.append(buffer);
4523
4524 if (mActiveTrack != 0) {
4525 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004526 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 mActiveTrack->dump(buffer, SIZE);
4528 result.append(buffer);
4529
4530 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4531 result.append(buffer);
4532 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4533 result.append(buffer);
4534 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4535 result.append(buffer);
4536 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4537 result.append(buffer);
4538 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4539 result.append(buffer);
4540
4541
4542 } else {
4543 result.append("No record client\n");
4544 }
4545 write(fd, result.string(), result.size());
4546
4547 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004548 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004549
4550 return NO_ERROR;
4551}
4552
4553status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4554{
4555 size_t framesReq = buffer->frameCount;
4556 size_t framesReady = mFrameCount - mRsmpInIndex;
4557 int channelCount;
4558
4559 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004560 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004561 if (mBytesRead < 0) {
4562 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4563 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4564 // Force input into standby so that it tries to
4565 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004566 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004567 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004568 }
4569 buffer->raw = 0;
4570 buffer->frameCount = 0;
4571 return NOT_ENOUGH_DATA;
4572 }
4573 mRsmpInIndex = 0;
4574 framesReady = mFrameCount;
4575 }
4576
4577 if (framesReq > framesReady) {
4578 framesReq = framesReady;
4579 }
4580
4581 if (mChannelCount == 1 && mReqChannelCount == 2) {
4582 channelCount = 1;
4583 } else {
4584 channelCount = 2;
4585 }
4586 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4587 buffer->frameCount = framesReq;
4588 return NO_ERROR;
4589}
4590
4591void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4592{
4593 mRsmpInIndex += buffer->frameCount;
4594 buffer->frameCount = 0;
4595}
4596
4597bool AudioFlinger::RecordThread::checkForNewParameters_l()
4598{
4599 bool reconfig = false;
4600
4601 while (!mNewParameters.isEmpty()) {
4602 status_t status = NO_ERROR;
4603 String8 keyValuePair = mNewParameters[0];
4604 AudioParameter param = AudioParameter(keyValuePair);
4605 int value;
4606 int reqFormat = mFormat;
4607 int reqSamplingRate = mReqSampleRate;
4608 int reqChannelCount = mReqChannelCount;
4609
4610 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4611 reqSamplingRate = value;
4612 reconfig = true;
4613 }
4614 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4615 reqFormat = value;
4616 reconfig = true;
4617 }
4618 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004619 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620 reconfig = true;
4621 }
4622 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4623 // do not accept frame count changes if tracks are open as the track buffer
4624 // size depends on frame count and correct behavior would not be garantied
4625 // if frame count is changed after track creation
4626 if (mActiveTrack != 0) {
4627 status = INVALID_OPERATION;
4628 } else {
4629 reconfig = true;
4630 }
4631 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004632 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4633 // forward device change to effects that have requested to be
4634 // aware of attached audio device.
4635 for (size_t i = 0; i < mEffectChains.size(); i++) {
4636 mEffectChains[i]->setDevice_l(value);
4637 }
4638 // store input device and output device but do not forward output device to audio HAL.
4639 // Note that status is ignored by the caller for output device
4640 // (see AudioFlinger::setParameters()
4641 if (value & AUDIO_DEVICE_OUT_ALL) {
4642 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4643 status = BAD_VALUE;
4644 } else {
4645 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004646 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4647 if (mTrack != NULL) {
4648 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004649 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004650 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4651 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4652 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004653 }
4654 mDevice |= (uint32_t)value;
4655 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004656 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004657 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004658 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004659 mInput->stream->common.standby(&mInput->stream->common);
4660 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004661 }
4662 if (reconfig) {
4663 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004664 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004665 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004666 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4667 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004668 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004669 status = NO_ERROR;
4670 }
4671 if (status == NO_ERROR) {
4672 readInputParameters();
4673 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4674 }
4675 }
4676 }
4677
4678 mNewParameters.removeAt(0);
4679
4680 mParamStatus = status;
4681 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004682 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4683 // already timed out waiting for the status and will never signal the condition.
4684 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685 }
4686 return reconfig;
4687}
4688
4689String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4690{
Dima Zavinfce7a472011-04-19 22:30:36 -07004691 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004692 String8 out_s8 = String8();
4693
4694 Mutex::Autolock _l(mLock);
4695 if (initCheck() != NO_ERROR) {
4696 return out_s8;
4697 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004698
Dima Zavin799a70e2011-04-18 16:57:27 -07004699 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004700 out_s8 = String8(s);
4701 free(s);
4702 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004703}
4704
4705void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4706 AudioSystem::OutputDescriptor desc;
4707 void *param2 = 0;
4708
4709 switch (event) {
4710 case AudioSystem::INPUT_OPENED:
4711 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004712 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 desc.samplingRate = mSampleRate;
4714 desc.format = mFormat;
4715 desc.frameCount = mFrameCount;
4716 desc.latency = 0;
4717 param2 = &desc;
4718 break;
4719
4720 case AudioSystem::INPUT_CLOSED:
4721 default:
4722 break;
4723 }
4724 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4725}
4726
4727void AudioFlinger::RecordThread::readInputParameters()
4728{
4729 if (mRsmpInBuffer) delete mRsmpInBuffer;
4730 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4731 if (mResampler) delete mResampler;
4732 mResampler = 0;
4733
Dima Zavin799a70e2011-04-18 16:57:27 -07004734 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004735 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4736 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004737 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4738 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4739 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740 mFrameCount = mInputBytes / mFrameSize;
4741 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4742
4743 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4744 {
4745 int channelCount;
4746 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4747 // stereo to mono post process as the resampler always outputs stereo.
4748 if (mChannelCount == 1 && mReqChannelCount == 2) {
4749 channelCount = 1;
4750 } else {
4751 channelCount = 2;
4752 }
4753 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4754 mResampler->setSampleRate(mSampleRate);
4755 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4756 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4757
4758 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4759 if (mChannelCount == 1 && mReqChannelCount == 1) {
4760 mFrameCount >>= 1;
4761 }
4762
4763 }
4764 mRsmpInIndex = mFrameCount;
4765}
4766
4767unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4768{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004769 Mutex::Autolock _l(mLock);
4770 if (initCheck() != NO_ERROR) {
4771 return 0;
4772 }
4773
Dima Zavin799a70e2011-04-18 16:57:27 -07004774 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004775}
4776
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004777uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4778{
4779 Mutex::Autolock _l(mLock);
4780 uint32_t result = 0;
4781 if (getEffectChain_l(sessionId) != 0) {
4782 result = EFFECT_SESSION;
4783 }
4784
4785 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4786 result |= TRACK_SESSION;
4787 }
4788
4789 return result;
4790}
4791
Eric Laurent59bd0da2011-08-01 09:52:20 -07004792AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4793{
4794 Mutex::Autolock _l(mLock);
4795 return mTrack;
4796}
4797
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004798AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4799{
4800 Mutex::Autolock _l(mLock);
4801 return mInput;
4802}
4803
4804AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4805{
4806 Mutex::Autolock _l(mLock);
4807 AudioStreamIn *input = mInput;
4808 mInput = NULL;
4809 return input;
4810}
4811
4812// this method must always be called either with ThreadBase mLock held or inside the thread loop
4813audio_stream_t* AudioFlinger::RecordThread::stream()
4814{
4815 if (mInput == NULL) {
4816 return NULL;
4817 }
4818 return &mInput->stream->common;
4819}
4820
4821
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822// ----------------------------------------------------------------------------
4823
4824int AudioFlinger::openOutput(uint32_t *pDevices,
4825 uint32_t *pSamplingRate,
4826 uint32_t *pFormat,
4827 uint32_t *pChannels,
4828 uint32_t *pLatencyMs,
4829 uint32_t flags)
4830{
4831 status_t status;
4832 PlaybackThread *thread = NULL;
4833 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4834 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4835 uint32_t format = pFormat ? *pFormat : 0;
4836 uint32_t channels = pChannels ? *pChannels : 0;
4837 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004838 audio_stream_out_t *outStream;
4839 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004840
4841 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4842 pDevices ? *pDevices : 0,
4843 samplingRate,
4844 format,
4845 channels,
4846 flags);
4847
4848 if (pDevices == NULL || *pDevices == 0) {
4849 return 0;
4850 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004851
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852 Mutex::Autolock _l(mLock);
4853
Dima Zavin799a70e2011-04-18 16:57:27 -07004854 outHwDev = findSuitableHwDev_l(*pDevices);
4855 if (outHwDev == NULL)
4856 return 0;
4857
4858 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4859 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004861 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862 samplingRate,
4863 format,
4864 channels,
4865 status);
4866
4867 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004868 if (outStream != NULL) {
4869 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004870 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004871
Dima Zavinfce7a472011-04-19 22:30:36 -07004872 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4873 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4874 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 thread = new DirectOutputThread(this, output, id, *pDevices);
4876 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4877 } else {
4878 thread = new MixerThread(this, output, id, *pDevices);
4879 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880 }
4881 mPlaybackThreads.add(id, thread);
4882
4883 if (pSamplingRate) *pSamplingRate = samplingRate;
4884 if (pFormat) *pFormat = format;
4885 if (pChannels) *pChannels = channels;
4886 if (pLatencyMs) *pLatencyMs = thread->latency();
4887
4888 // notify client processes of the new output creation
4889 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4890 return id;
4891 }
4892
4893 return 0;
4894}
4895
4896int AudioFlinger::openDuplicateOutput(int output1, int output2)
4897{
4898 Mutex::Autolock _l(mLock);
4899 MixerThread *thread1 = checkMixerThread_l(output1);
4900 MixerThread *thread2 = checkMixerThread_l(output2);
4901
4902 if (thread1 == NULL || thread2 == NULL) {
4903 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4904 return 0;
4905 }
4906
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004907 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4909 thread->addOutputTrack(thread2);
4910 mPlaybackThreads.add(id, thread);
4911 // notify client processes of the new output creation
4912 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4913 return id;
4914}
4915
4916status_t AudioFlinger::closeOutput(int output)
4917{
4918 // keep strong reference on the playback thread so that
4919 // it is not destroyed while exit() is executed
4920 sp <PlaybackThread> thread;
4921 {
4922 Mutex::Autolock _l(mLock);
4923 thread = checkPlaybackThread_l(output);
4924 if (thread == NULL) {
4925 return BAD_VALUE;
4926 }
4927
4928 LOGV("closeOutput() %d", output);
4929
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004930 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004932 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4934 dupThread->removeOutputTrack((MixerThread *)thread.get());
4935 }
4936 }
4937 }
4938 void *param2 = 0;
4939 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4940 mPlaybackThreads.removeItem(output);
4941 }
4942 thread->exit();
4943
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004944 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004945 AudioStreamOut *out = thread->clearOutput();
4946 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07004947 out->hwDev->close_output_stream(out->hwDev, out->stream);
4948 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 }
4950 return NO_ERROR;
4951}
4952
4953status_t AudioFlinger::suspendOutput(int output)
4954{
4955 Mutex::Autolock _l(mLock);
4956 PlaybackThread *thread = checkPlaybackThread_l(output);
4957
4958 if (thread == NULL) {
4959 return BAD_VALUE;
4960 }
4961
4962 LOGV("suspendOutput() %d", output);
4963 thread->suspend();
4964
4965 return NO_ERROR;
4966}
4967
4968status_t AudioFlinger::restoreOutput(int output)
4969{
4970 Mutex::Autolock _l(mLock);
4971 PlaybackThread *thread = checkPlaybackThread_l(output);
4972
4973 if (thread == NULL) {
4974 return BAD_VALUE;
4975 }
4976
4977 LOGV("restoreOutput() %d", output);
4978
4979 thread->restore();
4980
4981 return NO_ERROR;
4982}
4983
4984int AudioFlinger::openInput(uint32_t *pDevices,
4985 uint32_t *pSamplingRate,
4986 uint32_t *pFormat,
4987 uint32_t *pChannels,
4988 uint32_t acoustics)
4989{
4990 status_t status;
4991 RecordThread *thread = NULL;
4992 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4993 uint32_t format = pFormat ? *pFormat : 0;
4994 uint32_t channels = pChannels ? *pChannels : 0;
4995 uint32_t reqSamplingRate = samplingRate;
4996 uint32_t reqFormat = format;
4997 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004998 audio_stream_in_t *inStream;
4999 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000
5001 if (pDevices == NULL || *pDevices == 0) {
5002 return 0;
5003 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005004
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 Mutex::Autolock _l(mLock);
5006
Dima Zavin799a70e2011-04-18 16:57:27 -07005007 inHwDev = findSuitableHwDev_l(*pDevices);
5008 if (inHwDev == NULL)
5009 return 0;
5010
5011 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5012 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005013 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005014 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005015 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005016 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017 samplingRate,
5018 format,
5019 channels,
5020 acoustics,
5021 status);
5022
5023 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5024 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5025 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005026 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005027 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005028 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005029 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005030 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005031 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5032 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005033 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005034 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005035 }
5036
Dima Zavin799a70e2011-04-18 16:57:27 -07005037 if (inStream != NULL) {
5038 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5039
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005040 int id = nextUniqueId();
5041 // Start record thread
5042 // RecorThread require both input and output device indication to forward to audio
5043 // pre processing modules
5044 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5045 thread = new RecordThread(this,
5046 input,
5047 reqSamplingRate,
5048 reqChannels,
5049 id,
5050 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005051 mRecordThreads.add(id, thread);
5052 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5053 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5054 if (pFormat) *pFormat = format;
5055 if (pChannels) *pChannels = reqChannels;
5056
Dima Zavin799a70e2011-04-18 16:57:27 -07005057 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058
5059 // notify client processes of the new input creation
5060 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5061 return id;
5062 }
5063
5064 return 0;
5065}
5066
5067status_t AudioFlinger::closeInput(int input)
5068{
5069 // keep strong reference on the record thread so that
5070 // it is not destroyed while exit() is executed
5071 sp <RecordThread> thread;
5072 {
5073 Mutex::Autolock _l(mLock);
5074 thread = checkRecordThread_l(input);
5075 if (thread == NULL) {
5076 return BAD_VALUE;
5077 }
5078
5079 LOGV("closeInput() %d", input);
5080 void *param2 = 0;
5081 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5082 mRecordThreads.removeItem(input);
5083 }
5084 thread->exit();
5085
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005086 AudioStreamIn *in = thread->clearInput();
5087 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005088 in->hwDev->close_input_stream(in->hwDev, in->stream);
5089 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090
5091 return NO_ERROR;
5092}
5093
5094status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5095{
5096 Mutex::Autolock _l(mLock);
5097 MixerThread *dstThread = checkMixerThread_l(output);
5098 if (dstThread == NULL) {
5099 LOGW("setStreamOutput() bad output id %d", output);
5100 return BAD_VALUE;
5101 }
5102
5103 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5104 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5105
Eric Laurent9f6530f2011-08-30 10:18:54 -07005106 dstThread->setStreamValid(stream, true);
5107
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5109 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5110 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005111 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005112 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005113 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005114 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005115 }
Eric Laurentde070132010-07-13 04:45:46 -07005116 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117
5118 return NO_ERROR;
5119}
5120
5121
5122int AudioFlinger::newAudioSessionId()
5123{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005124 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125}
5126
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005127void AudioFlinger::acquireAudioSessionId(int audioSession)
5128{
5129 Mutex::Autolock _l(mLock);
5130 int caller = IPCThreadState::self()->getCallingPid();
5131 LOGV("acquiring %d from %d", audioSession, caller);
5132 int num = mAudioSessionRefs.size();
5133 for (int i = 0; i< num; i++) {
5134 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5135 if (ref->sessionid == audioSession && ref->pid == caller) {
5136 ref->cnt++;
5137 LOGV(" incremented refcount to %d", ref->cnt);
5138 return;
5139 }
5140 }
5141 AudioSessionRef *ref = new AudioSessionRef();
5142 ref->sessionid = audioSession;
5143 ref->pid = caller;
5144 ref->cnt = 1;
5145 mAudioSessionRefs.push(ref);
5146 LOGV(" added new entry for %d", ref->sessionid);
5147}
5148
5149void AudioFlinger::releaseAudioSessionId(int audioSession)
5150{
5151 Mutex::Autolock _l(mLock);
5152 int caller = IPCThreadState::self()->getCallingPid();
5153 LOGV("releasing %d from %d", audioSession, caller);
5154 int num = mAudioSessionRefs.size();
5155 for (int i = 0; i< num; i++) {
5156 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5157 if (ref->sessionid == audioSession && ref->pid == caller) {
5158 ref->cnt--;
5159 LOGV(" decremented refcount to %d", ref->cnt);
5160 if (ref->cnt == 0) {
5161 mAudioSessionRefs.removeAt(i);
5162 delete ref;
5163 purgeStaleEffects_l();
5164 }
5165 return;
5166 }
5167 }
5168 LOGW("session id %d not found for pid %d", audioSession, caller);
5169}
5170
5171void AudioFlinger::purgeStaleEffects_l() {
5172
5173 LOGV("purging stale effects");
5174
5175 Vector< sp<EffectChain> > chains;
5176
5177 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5178 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5179 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5180 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005181 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5182 chains.push(ec);
5183 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005184 }
5185 }
5186 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5187 sp<RecordThread> t = mRecordThreads.valueAt(i);
5188 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5189 sp<EffectChain> ec = t->mEffectChains[j];
5190 chains.push(ec);
5191 }
5192 }
5193
5194 for (size_t i = 0; i < chains.size(); i++) {
5195 sp<EffectChain> ec = chains[i];
5196 int sessionid = ec->sessionId();
5197 sp<ThreadBase> t = ec->mThread.promote();
5198 if (t == 0) {
5199 continue;
5200 }
5201 size_t numsessionrefs = mAudioSessionRefs.size();
5202 bool found = false;
5203 for (size_t k = 0; k < numsessionrefs; k++) {
5204 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5205 if (ref->sessionid == sessionid) {
5206 LOGV(" session %d still exists for %d with %d refs",
5207 sessionid, ref->pid, ref->cnt);
5208 found = true;
5209 break;
5210 }
5211 }
5212 if (!found) {
5213 // remove all effects from the chain
5214 while (ec->mEffects.size()) {
5215 sp<EffectModule> effect = ec->mEffects[0];
5216 effect->unPin();
5217 Mutex::Autolock _l (t->mLock);
5218 t->removeEffect_l(effect);
5219 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5220 sp<EffectHandle> handle = effect->mHandles[j].promote();
5221 if (handle != 0) {
5222 handle->mEffect.clear();
5223 }
5224 }
5225 AudioSystem::unregisterEffect(effect->id());
5226 }
5227 }
5228 }
5229 return;
5230}
5231
Mathias Agopian65ab4712010-07-14 17:59:35 -07005232// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5233AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5234{
5235 PlaybackThread *thread = NULL;
5236 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5237 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5238 }
5239 return thread;
5240}
5241
5242// checkMixerThread_l() must be called with AudioFlinger::mLock held
5243AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5244{
5245 PlaybackThread *thread = checkPlaybackThread_l(output);
5246 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005247 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005248 thread = NULL;
5249 }
5250 }
5251 return (MixerThread *)thread;
5252}
5253
5254// checkRecordThread_l() must be called with AudioFlinger::mLock held
5255AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5256{
5257 RecordThread *thread = NULL;
5258 if (mRecordThreads.indexOfKey(input) >= 0) {
5259 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5260 }
5261 return thread;
5262}
5263
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005264uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005265{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005266 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005267}
5268
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005269AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5270{
5271 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5272 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005273 AudioStreamOut *output = thread->getOutput();
5274 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005275 return thread;
5276 }
5277 }
5278 return NULL;
5279}
5280
5281uint32_t AudioFlinger::primaryOutputDevice_l()
5282{
5283 PlaybackThread *thread = primaryPlaybackThread_l();
5284
5285 if (thread == NULL) {
5286 return 0;
5287 }
5288
5289 return thread->device();
5290}
5291
5292
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293// ----------------------------------------------------------------------------
5294// Effect management
5295// ----------------------------------------------------------------------------
5296
5297
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5299{
5300 Mutex::Autolock _l(mLock);
5301 return EffectQueryNumberEffects(numEffects);
5302}
5303
5304status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5305{
5306 Mutex::Autolock _l(mLock);
5307 return EffectQueryEffect(index, descriptor);
5308}
5309
5310status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5311{
5312 Mutex::Autolock _l(mLock);
5313 return EffectGetDescriptor(pUuid, descriptor);
5314}
5315
5316
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5318 effect_descriptor_t *pDesc,
5319 const sp<IEffectClient>& effectClient,
5320 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005321 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005322 int sessionId,
5323 status_t *status,
5324 int *id,
5325 int *enabled)
5326{
5327 status_t lStatus = NO_ERROR;
5328 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005329 effect_descriptor_t desc;
5330 sp<Client> client;
5331 wp<Client> wclient;
5332
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005333 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5334 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335
5336 if (pDesc == NULL) {
5337 lStatus = BAD_VALUE;
5338 goto Exit;
5339 }
5340
Eric Laurent84e9a102010-09-23 16:10:16 -07005341 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005342 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005343 lStatus = PERMISSION_DENIED;
5344 goto Exit;
5345 }
5346
Dima Zavinfce7a472011-04-19 22:30:36 -07005347 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005348 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005349 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005350 lStatus = PERMISSION_DENIED;
5351 goto Exit;
5352 }
5353
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005354 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005355 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005356 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005357 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005358 lStatus = BAD_VALUE;
5359 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005360 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005361 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005362 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005363 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005364 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005365 }
5366 }
5367
Mathias Agopian65ab4712010-07-14 17:59:35 -07005368 {
5369 Mutex::Autolock _l(mLock);
5370
Mathias Agopian65ab4712010-07-14 17:59:35 -07005371
5372 if (!EffectIsNullUuid(&pDesc->uuid)) {
5373 // if uuid is specified, request effect descriptor
5374 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5375 if (lStatus < 0) {
5376 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5377 goto Exit;
5378 }
5379 } else {
5380 // if uuid is not specified, look for an available implementation
5381 // of the required type in effect factory
5382 if (EffectIsNullUuid(&pDesc->type)) {
5383 LOGW("createEffect() no effect type");
5384 lStatus = BAD_VALUE;
5385 goto Exit;
5386 }
5387 uint32_t numEffects = 0;
5388 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005389 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 bool found = false;
5391
5392 lStatus = EffectQueryNumberEffects(&numEffects);
5393 if (lStatus < 0) {
5394 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5395 goto Exit;
5396 }
5397 for (uint32_t i = 0; i < numEffects; i++) {
5398 lStatus = EffectQueryEffect(i, &desc);
5399 if (lStatus < 0) {
5400 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5401 continue;
5402 }
5403 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5404 // If matching type found save effect descriptor. If the session is
5405 // 0 and the effect is not auxiliary, continue enumeration in case
5406 // an auxiliary version of this effect type is available
5407 found = true;
5408 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005409 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005410 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5411 break;
5412 }
5413 }
5414 }
5415 if (!found) {
5416 lStatus = BAD_VALUE;
5417 LOGW("createEffect() effect not found");
5418 goto Exit;
5419 }
5420 // For same effect type, chose auxiliary version over insert version if
5421 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005422 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5424 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5425 }
5426 }
5427
5428 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005429 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005430 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5431 lStatus = INVALID_OPERATION;
5432 goto Exit;
5433 }
5434
Eric Laurent59255e42011-07-27 19:49:51 -07005435 // check recording permission for visualizer
5436 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5437 !recordingAllowed()) {
5438 lStatus = PERMISSION_DENIED;
5439 goto Exit;
5440 }
5441
Mathias Agopian65ab4712010-07-14 17:59:35 -07005442 // return effect descriptor
5443 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5444
5445 // If output is not specified try to find a matching audio session ID in one of the
5446 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005447 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5448 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005449 // Note: io is never 0 when creating an effect on an input
5450 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005451 // look for the thread where the specified audio session is present
5452 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5453 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005454 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005455 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005456 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005457 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005458 if (io == 0) {
5459 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5460 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5461 io = mRecordThreads.keyAt(i);
5462 break;
5463 }
5464 }
5465 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005466 // If no output thread contains the requested session ID, default to
5467 // first output. The effect chain will be moved to the correct output
5468 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005469 if (io == 0 && mPlaybackThreads.size()) {
5470 io = mPlaybackThreads.keyAt(0);
5471 }
5472 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5473 }
5474 ThreadBase *thread = checkRecordThread_l(io);
5475 if (thread == NULL) {
5476 thread = checkPlaybackThread_l(io);
5477 if (thread == NULL) {
5478 LOGE("createEffect() unknown output thread");
5479 lStatus = BAD_VALUE;
5480 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005481 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005482 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005483
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 wclient = mClients.valueFor(pid);
5485
5486 if (wclient != NULL) {
5487 client = wclient.promote();
5488 } else {
5489 client = new Client(this, pid);
5490 mClients.add(pid, client);
5491 }
5492
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005493 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005494 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5495 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496 if (handle != 0 && id != NULL) {
5497 *id = handle->id();
5498 }
5499 }
5500
5501Exit:
5502 if(status) {
5503 *status = lStatus;
5504 }
5505 return handle;
5506}
5507
Eric Laurent59255e42011-07-27 19:49:51 -07005508status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005509{
5510 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005511 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005512 Mutex::Autolock _l(mLock);
5513 if (srcOutput == dstOutput) {
5514 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5515 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 }
Eric Laurentde070132010-07-13 04:45:46 -07005517 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5518 if (srcThread == NULL) {
5519 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5520 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005521 }
Eric Laurentde070132010-07-13 04:45:46 -07005522 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5523 if (dstThread == NULL) {
5524 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5525 return BAD_VALUE;
5526 }
5527
5528 Mutex::Autolock _dl(dstThread->mLock);
5529 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005530 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005531
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 return NO_ERROR;
5533}
5534
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005535// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005536status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005537 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005538 AudioFlinger::PlaybackThread *dstThread,
5539 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005540{
5541 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005542 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005543
Eric Laurent59255e42011-07-27 19:49:51 -07005544 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005545 if (chain == 0) {
5546 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005547 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005548 return INVALID_OPERATION;
5549 }
5550
Eric Laurent39e94f82010-07-28 01:32:47 -07005551 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005552 // so that a new chain is created with correct parameters when first effect is added. This is
5553 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5554 // removed.
5555 srcThread->removeEffectChain_l(chain);
5556
5557 // transfer all effects one by one so that new effect chain is created on new thread with
5558 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005559 int dstOutput = dstThread->id();
5560 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005561 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005562 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5563 while (effect != 0) {
5564 srcThread->removeEffect_l(effect);
5565 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07005566 // if the move request is not received from audio policy manager, the effect must be
5567 // re-registered with the new strategy and output
5568 if (dstChain == 0) {
5569 dstChain = effect->chain().promote();
5570 if (dstChain == 0) {
5571 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5572 srcThread->addEffect_l(effect);
5573 return NO_INIT;
5574 }
5575 strategy = dstChain->strategy();
5576 }
5577 if (reRegister) {
5578 AudioSystem::unregisterEffect(effect->id());
5579 AudioSystem::registerEffect(&effect->desc(),
5580 dstOutput,
5581 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005582 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005583 effect->id());
5584 }
Eric Laurentde070132010-07-13 04:45:46 -07005585 effect = chain->getEffectFromId_l(0);
5586 }
5587
5588 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005589}
5590
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005591
Mathias Agopian65ab4712010-07-14 17:59:35 -07005592// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005593sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005594 const sp<AudioFlinger::Client>& client,
5595 const sp<IEffectClient>& effectClient,
5596 int32_t priority,
5597 int sessionId,
5598 effect_descriptor_t *desc,
5599 int *enabled,
5600 status_t *status
5601 )
5602{
5603 sp<EffectModule> effect;
5604 sp<EffectHandle> handle;
5605 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005606 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005607 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005608 bool effectCreated = false;
5609 bool effectRegistered = false;
5610
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005611 lStatus = initCheck();
5612 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005613 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614 goto Exit;
5615 }
5616
5617 // Do not allow effects with session ID 0 on direct output or duplicating threads
5618 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005619 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005620 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5621 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005622 lStatus = BAD_VALUE;
5623 goto Exit;
5624 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005625 // Only Pre processor effects are allowed on input threads and only on input threads
5626 if ((mType == RECORD &&
5627 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5628 (mType != RECORD &&
5629 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5630 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5631 desc->name, desc->flags, mType);
5632 lStatus = BAD_VALUE;
5633 goto Exit;
5634 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005635
5636 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5637
5638 { // scope for mLock
5639 Mutex::Autolock _l(mLock);
5640
5641 // check for existing effect chain with the requested audio session
5642 chain = getEffectChain_l(sessionId);
5643 if (chain == 0) {
5644 // create a new chain for this session
5645 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5646 chain = new EffectChain(this, sessionId);
5647 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005648 chain->setStrategy(getStrategyForSession_l(sessionId));
5649 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005651 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 }
5653
5654 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5655
5656 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005657 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005659 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 if (lStatus != NO_ERROR) {
5661 goto Exit;
5662 }
5663 effectRegistered = true;
5664 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005665 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005666 lStatus = effect->status();
5667 if (lStatus != NO_ERROR) {
5668 goto Exit;
5669 }
Eric Laurentcab11242010-07-15 12:50:15 -07005670 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671 if (lStatus != NO_ERROR) {
5672 goto Exit;
5673 }
5674 effectCreated = true;
5675
5676 effect->setDevice(mDevice);
5677 effect->setMode(mAudioFlinger->getMode());
5678 }
5679 // create effect handle and connect it to effect module
5680 handle = new EffectHandle(effect, client, effectClient, priority);
5681 lStatus = effect->addHandle(handle);
5682 if (enabled) {
5683 *enabled = (int)effect->isEnabled();
5684 }
5685 }
5686
5687Exit:
5688 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005689 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005691 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692 }
5693 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005694 AudioSystem::unregisterEffect(effect->id());
5695 }
5696 if (chainCreated) {
5697 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698 }
5699 handle.clear();
5700 }
5701
5702 if(status) {
5703 *status = lStatus;
5704 }
5705 return handle;
5706}
5707
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005708sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5709{
5710 sp<EffectModule> effect;
5711
5712 sp<EffectChain> chain = getEffectChain_l(sessionId);
5713 if (chain != 0) {
5714 effect = chain->getEffectFromId_l(effectId);
5715 }
5716 return effect;
5717}
5718
Eric Laurentde070132010-07-13 04:45:46 -07005719// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5720// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005721status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005722{
5723 // check for existing effect chain with the requested audio session
5724 int sessionId = effect->sessionId();
5725 sp<EffectChain> chain = getEffectChain_l(sessionId);
5726 bool chainCreated = false;
5727
5728 if (chain == 0) {
5729 // create a new chain for this session
5730 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5731 chain = new EffectChain(this, sessionId);
5732 addEffectChain_l(chain);
5733 chain->setStrategy(getStrategyForSession_l(sessionId));
5734 chainCreated = true;
5735 }
5736 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5737
5738 if (chain->getEffectFromId_l(effect->id()) != 0) {
5739 LOGW("addEffect_l() %p effect %s already present in chain %p",
5740 this, effect->desc().name, chain.get());
5741 return BAD_VALUE;
5742 }
5743
5744 status_t status = chain->addEffect_l(effect);
5745 if (status != NO_ERROR) {
5746 if (chainCreated) {
5747 removeEffectChain_l(chain);
5748 }
5749 return status;
5750 }
5751
5752 effect->setDevice(mDevice);
5753 effect->setMode(mAudioFlinger->getMode());
5754 return NO_ERROR;
5755}
5756
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005757void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005758
5759 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005761 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5762 detachAuxEffect_l(effect->id());
5763 }
5764
5765 sp<EffectChain> chain = effect->chain().promote();
5766 if (chain != 0) {
5767 // remove effect chain if removing last effect
5768 if (chain->removeEffect_l(effect) == 0) {
5769 removeEffectChain_l(chain);
5770 }
5771 } else {
5772 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5773 }
5774}
5775
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005776void AudioFlinger::ThreadBase::lockEffectChains_l(
5777 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5778{
5779 effectChains = mEffectChains;
5780 for (size_t i = 0; i < mEffectChains.size(); i++) {
5781 mEffectChains[i]->lock();
5782 }
5783}
5784
5785void AudioFlinger::ThreadBase::unlockEffectChains(
5786 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5787{
5788 for (size_t i = 0; i < effectChains.size(); i++) {
5789 effectChains[i]->unlock();
5790 }
5791}
5792
5793sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5794{
5795 Mutex::Autolock _l(mLock);
5796 return getEffectChain_l(sessionId);
5797}
5798
5799sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5800{
5801 sp<EffectChain> chain;
5802
5803 size_t size = mEffectChains.size();
5804 for (size_t i = 0; i < size; i++) {
5805 if (mEffectChains[i]->sessionId() == sessionId) {
5806 chain = mEffectChains[i];
5807 break;
5808 }
5809 }
5810 return chain;
5811}
5812
5813void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5814{
5815 Mutex::Autolock _l(mLock);
5816 size_t size = mEffectChains.size();
5817 for (size_t i = 0; i < size; i++) {
5818 mEffectChains[i]->setMode_l(mode);
5819 }
5820}
5821
5822void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005823 const wp<EffectHandle>& handle,
5824 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005825
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005827 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 // delete the effect module if removing last handle on it
5829 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005830 if (!effect->isPinned() || unpiniflast) {
5831 removeEffect_l(effect);
5832 AudioSystem::unregisterEffect(effect->id());
5833 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005834 }
5835}
5836
5837status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5838{
5839 int session = chain->sessionId();
5840 int16_t *buffer = mMixBuffer;
5841 bool ownsBuffer = false;
5842
5843 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5844 if (session > 0) {
5845 // Only one effect chain can be present in direct output thread and it uses
5846 // the mix buffer as input
5847 if (mType != DIRECT) {
5848 size_t numSamples = mFrameCount * mChannelCount;
5849 buffer = new int16_t[numSamples];
5850 memset(buffer, 0, numSamples * sizeof(int16_t));
5851 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5852 ownsBuffer = true;
5853 }
5854
5855 // Attach all tracks with same session ID to this chain.
5856 for (size_t i = 0; i < mTracks.size(); ++i) {
5857 sp<Track> track = mTracks[i];
5858 if (session == track->sessionId()) {
5859 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5860 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005861 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005862 }
5863 }
5864
5865 // indicate all active tracks in the chain
5866 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5867 sp<Track> track = mActiveTracks[i].promote();
5868 if (track == 0) continue;
5869 if (session == track->sessionId()) {
5870 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005871 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872 }
5873 }
5874 }
5875
5876 chain->setInBuffer(buffer, ownsBuffer);
5877 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005878 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005879 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005880 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5881 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005882 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005883 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5884 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005885 // Effect chain for other sessions are inserted at beginning of effect
5886 // chains list to be processed before output mix effects. Relative order between other
5887 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888 size_t size = mEffectChains.size();
5889 size_t i = 0;
5890 for (i = 0; i < size; i++) {
5891 if (mEffectChains[i]->sessionId() < session) break;
5892 }
5893 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005894 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005895
5896 return NO_ERROR;
5897}
5898
5899size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5900{
5901 int session = chain->sessionId();
5902
5903 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5904
5905 for (size_t i = 0; i < mEffectChains.size(); i++) {
5906 if (chain == mEffectChains[i]) {
5907 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005908 // detach all active tracks from the chain
5909 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5910 sp<Track> track = mActiveTracks[i].promote();
5911 if (track == 0) continue;
5912 if (session == track->sessionId()) {
5913 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5914 chain.get(), session);
5915 chain->decActiveTrackCnt();
5916 }
5917 }
5918
Mathias Agopian65ab4712010-07-14 17:59:35 -07005919 // detach all tracks with same session ID from this chain
5920 for (size_t i = 0; i < mTracks.size(); ++i) {
5921 sp<Track> track = mTracks[i];
5922 if (session == track->sessionId()) {
5923 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005924 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 }
5926 }
Eric Laurentde070132010-07-13 04:45:46 -07005927 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 }
5929 }
5930 return mEffectChains.size();
5931}
5932
Eric Laurentde070132010-07-13 04:45:46 -07005933status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5934 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935{
5936 Mutex::Autolock _l(mLock);
5937 return attachAuxEffect_l(track, EffectId);
5938}
5939
Eric Laurentde070132010-07-13 04:45:46 -07005940status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5941 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005942{
5943 status_t status = NO_ERROR;
5944
5945 if (EffectId == 0) {
5946 track->setAuxBuffer(0, NULL);
5947 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005948 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5949 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 if (effect != 0) {
5951 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5952 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5953 } else {
5954 status = INVALID_OPERATION;
5955 }
5956 } else {
5957 status = BAD_VALUE;
5958 }
5959 }
5960 return status;
5961}
5962
5963void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5964{
5965 for (size_t i = 0; i < mTracks.size(); ++i) {
5966 sp<Track> track = mTracks[i];
5967 if (track->auxEffectId() == effectId) {
5968 attachAuxEffect_l(track, 0);
5969 }
5970 }
5971}
5972
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005973status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5974{
5975 // only one chain per input thread
5976 if (mEffectChains.size() != 0) {
5977 return INVALID_OPERATION;
5978 }
5979 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5980
5981 chain->setInBuffer(NULL);
5982 chain->setOutBuffer(NULL);
5983
Eric Laurent59255e42011-07-27 19:49:51 -07005984 checkSuspendOnAddEffectChain_l(chain);
5985
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005986 mEffectChains.add(chain);
5987
5988 return NO_ERROR;
5989}
5990
5991size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5992{
5993 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5994 LOGW_IF(mEffectChains.size() != 1,
5995 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5996 chain.get(), mEffectChains.size(), this);
5997 if (mEffectChains.size() == 1) {
5998 mEffectChains.removeAt(0);
5999 }
6000 return 0;
6001}
6002
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003// ----------------------------------------------------------------------------
6004// EffectModule implementation
6005// ----------------------------------------------------------------------------
6006
6007#undef LOG_TAG
6008#define LOG_TAG "AudioFlinger::EffectModule"
6009
6010AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6011 const wp<AudioFlinger::EffectChain>& chain,
6012 effect_descriptor_t *desc,
6013 int id,
6014 int sessionId)
6015 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006016 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017{
6018 LOGV("Constructor %p", this);
6019 int lStatus;
6020 sp<ThreadBase> thread = mThread.promote();
6021 if (thread == 0) {
6022 return;
6023 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024
6025 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6026
6027 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006028 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029
6030 if (mStatus != NO_ERROR) {
6031 return;
6032 }
6033 lStatus = init();
6034 if (lStatus < 0) {
6035 mStatus = lStatus;
6036 goto Error;
6037 }
6038
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006039 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6040 mPinned = true;
6041 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006042 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6043 return;
6044Error:
6045 EffectRelease(mEffectInterface);
6046 mEffectInterface = NULL;
6047 LOGV("Constructor Error %d", mStatus);
6048}
6049
6050AudioFlinger::EffectModule::~EffectModule()
6051{
6052 LOGV("Destructor %p", this);
6053 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006054 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6055 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6056 sp<ThreadBase> thread = mThread.promote();
6057 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006058 audio_stream_t *stream = thread->stream();
6059 if (stream != NULL) {
6060 stream->remove_audio_effect(stream, mEffectInterface);
6061 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006062 }
6063 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 // release effect engine
6065 EffectRelease(mEffectInterface);
6066 }
6067}
6068
6069status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6070{
6071 status_t status;
6072
6073 Mutex::Autolock _l(mLock);
6074 // First handle in mHandles has highest priority and controls the effect module
6075 int priority = handle->priority();
6076 size_t size = mHandles.size();
6077 sp<EffectHandle> h;
6078 size_t i;
6079 for (i = 0; i < size; i++) {
6080 h = mHandles[i].promote();
6081 if (h == 0) continue;
6082 if (h->priority() <= priority) break;
6083 }
6084 // if inserted in first place, move effect control from previous owner to this handle
6085 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006086 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006088 enabled = h->enabled();
6089 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090 }
Eric Laurent59255e42011-07-27 19:49:51 -07006091 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092 status = NO_ERROR;
6093 } else {
6094 status = ALREADY_EXISTS;
6095 }
Eric Laurent59255e42011-07-27 19:49:51 -07006096 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097 mHandles.insertAt(handle, i);
6098 return status;
6099}
6100
6101size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6102{
6103 Mutex::Autolock _l(mLock);
6104 size_t size = mHandles.size();
6105 size_t i;
6106 for (i = 0; i < size; i++) {
6107 if (mHandles[i] == handle) break;
6108 }
6109 if (i == size) {
6110 return size;
6111 }
Eric Laurent59255e42011-07-27 19:49:51 -07006112 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6113
6114 bool enabled = false;
6115 EffectHandle *hdl = handle.unsafe_get();
6116 if (hdl) {
6117 LOGV("removeHandle() unsafe_get OK");
6118 enabled = hdl->enabled();
6119 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 mHandles.removeAt(i);
6121 size = mHandles.size();
6122 // if removed from first place, move effect control from this handle to next in line
6123 if (i == 0 && size != 0) {
6124 sp<EffectHandle> h = mHandles[0].promote();
6125 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006126 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 }
6128 }
6129
Eric Laurentec437d82011-07-26 20:54:46 -07006130 // Prevent calls to process() and other functions on effect interface from now on.
6131 // The effect engine will be released by the destructor when the last strong reference on
6132 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006133 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006134 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006135 }
6136
Mathias Agopian65ab4712010-07-14 17:59:35 -07006137 return size;
6138}
6139
Eric Laurent59255e42011-07-27 19:49:51 -07006140sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6141{
6142 Mutex::Autolock _l(mLock);
6143 sp<EffectHandle> handle;
6144 if (mHandles.size() != 0) {
6145 handle = mHandles[0].promote();
6146 }
6147 return handle;
6148}
6149
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006150void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006151{
Eric Laurent59255e42011-07-27 19:49:51 -07006152 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 // keep a strong reference on this EffectModule to avoid calling the
6154 // destructor before we exit
6155 sp<EffectModule> keep(this);
6156 {
6157 sp<ThreadBase> thread = mThread.promote();
6158 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006159 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 }
6161 }
6162}
6163
6164void AudioFlinger::EffectModule::updateState() {
6165 Mutex::Autolock _l(mLock);
6166
6167 switch (mState) {
6168 case RESTART:
6169 reset_l();
6170 // FALL THROUGH
6171
6172 case STARTING:
6173 // clear auxiliary effect input buffer for next accumulation
6174 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6175 memset(mConfig.inputCfg.buffer.raw,
6176 0,
6177 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6178 }
6179 start_l();
6180 mState = ACTIVE;
6181 break;
6182 case STOPPING:
6183 stop_l();
6184 mDisableWaitCnt = mMaxDisableWaitCnt;
6185 mState = STOPPED;
6186 break;
6187 case STOPPED:
6188 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6189 // turn off sequence.
6190 if (--mDisableWaitCnt == 0) {
6191 reset_l();
6192 mState = IDLE;
6193 }
6194 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006195 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006196 break;
6197 }
6198}
6199
6200void AudioFlinger::EffectModule::process()
6201{
6202 Mutex::Autolock _l(mLock);
6203
Eric Laurentec437d82011-07-26 20:54:46 -07006204 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 mConfig.inputCfg.buffer.raw == NULL ||
6206 mConfig.outputCfg.buffer.raw == NULL) {
6207 return;
6208 }
6209
Eric Laurent8f45bd72010-08-31 13:50:07 -07006210 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6212 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6213 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6214 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006215 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 }
6217
6218 // do the actual processing in the effect engine
6219 int ret = (*mEffectInterface)->process(mEffectInterface,
6220 &mConfig.inputCfg.buffer,
6221 &mConfig.outputCfg.buffer);
6222
6223 // force transition to IDLE state when engine is ready
6224 if (mState == STOPPED && ret == -ENODATA) {
6225 mDisableWaitCnt = 1;
6226 }
6227
6228 // clear auxiliary effect input buffer for next accumulation
6229 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006230 memset(mConfig.inputCfg.buffer.raw, 0,
6231 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 }
6233 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006234 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6235 // If an insert effect is idle and input buffer is different from output buffer,
6236 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006237 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006238 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006239 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6240 int16_t *in = mConfig.inputCfg.buffer.s16;
6241 int16_t *out = mConfig.outputCfg.buffer.s16;
6242 for (size_t i = 0; i < frameCnt; i++) {
6243 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006245 }
6246 }
6247}
6248
6249void AudioFlinger::EffectModule::reset_l()
6250{
6251 if (mEffectInterface == NULL) {
6252 return;
6253 }
6254 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6255}
6256
6257status_t AudioFlinger::EffectModule::configure()
6258{
6259 uint32_t channels;
6260 if (mEffectInterface == NULL) {
6261 return NO_INIT;
6262 }
6263
6264 sp<ThreadBase> thread = mThread.promote();
6265 if (thread == 0) {
6266 return DEAD_OBJECT;
6267 }
6268
6269 // TODO: handle configuration of effects replacing track process
6270 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006271 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006273 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 }
6275
6276 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006277 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 } else {
6279 mConfig.inputCfg.channels = channels;
6280 }
6281 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006282 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6283 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 mConfig.inputCfg.samplingRate = thread->sampleRate();
6285 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6286 mConfig.inputCfg.bufferProvider.cookie = NULL;
6287 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6288 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6289 mConfig.outputCfg.bufferProvider.cookie = NULL;
6290 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6291 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6292 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6293 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006294 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006295 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296 // - in other sessions:
6297 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6298 // other effect: overwrites output buffer: input buffer == output buffer
6299 // Auxiliary effect:
6300 // accumulates in output buffer: input buffer != output buffer
6301 // Therefore: accumulate <=> input buffer != output buffer
6302 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6303 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6304 } else {
6305 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6306 }
6307 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6308 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6309 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6310 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6311
Eric Laurentde070132010-07-13 04:45:46 -07006312 LOGV("configure() %p thread %p buffer %p framecount %d",
6313 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6314
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006316 uint32_t size = sizeof(int);
6317 status_t status = (*mEffectInterface)->command(mEffectInterface,
6318 EFFECT_CMD_CONFIGURE,
6319 sizeof(effect_config_t),
6320 &mConfig,
6321 &size,
6322 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006323 if (status == 0) {
6324 status = cmdStatus;
6325 }
6326
6327 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6328 (1000 * mConfig.outputCfg.buffer.frameCount);
6329
6330 return status;
6331}
6332
6333status_t AudioFlinger::EffectModule::init()
6334{
6335 Mutex::Autolock _l(mLock);
6336 if (mEffectInterface == NULL) {
6337 return NO_INIT;
6338 }
6339 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006340 uint32_t size = sizeof(status_t);
6341 status_t status = (*mEffectInterface)->command(mEffectInterface,
6342 EFFECT_CMD_INIT,
6343 0,
6344 NULL,
6345 &size,
6346 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 if (status == 0) {
6348 status = cmdStatus;
6349 }
6350 return status;
6351}
6352
6353status_t AudioFlinger::EffectModule::start_l()
6354{
6355 if (mEffectInterface == NULL) {
6356 return NO_INIT;
6357 }
6358 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006359 uint32_t size = sizeof(status_t);
6360 status_t status = (*mEffectInterface)->command(mEffectInterface,
6361 EFFECT_CMD_ENABLE,
6362 0,
6363 NULL,
6364 &size,
6365 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366 if (status == 0) {
6367 status = cmdStatus;
6368 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006369 if (status == 0 &&
6370 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6371 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6372 sp<ThreadBase> thread = mThread.promote();
6373 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006374 audio_stream_t *stream = thread->stream();
6375 if (stream != NULL) {
6376 stream->add_audio_effect(stream, mEffectInterface);
6377 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006378 }
6379 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380 return status;
6381}
6382
Eric Laurentec437d82011-07-26 20:54:46 -07006383status_t AudioFlinger::EffectModule::stop()
6384{
6385 Mutex::Autolock _l(mLock);
6386 return stop_l();
6387}
6388
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389status_t AudioFlinger::EffectModule::stop_l()
6390{
6391 if (mEffectInterface == NULL) {
6392 return NO_INIT;
6393 }
6394 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006395 uint32_t size = sizeof(status_t);
6396 status_t status = (*mEffectInterface)->command(mEffectInterface,
6397 EFFECT_CMD_DISABLE,
6398 0,
6399 NULL,
6400 &size,
6401 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 if (status == 0) {
6403 status = cmdStatus;
6404 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006405 if (status == 0 &&
6406 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6407 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6408 sp<ThreadBase> thread = mThread.promote();
6409 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006410 audio_stream_t *stream = thread->stream();
6411 if (stream != NULL) {
6412 stream->remove_audio_effect(stream, mEffectInterface);
6413 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006414 }
6415 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006416 return status;
6417}
6418
Eric Laurent25f43952010-07-28 05:40:18 -07006419status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6420 uint32_t cmdSize,
6421 void *pCmdData,
6422 uint32_t *replySize,
6423 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424{
6425 Mutex::Autolock _l(mLock);
6426// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6427
Eric Laurentec437d82011-07-26 20:54:46 -07006428 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 return NO_INIT;
6430 }
Eric Laurent25f43952010-07-28 05:40:18 -07006431 status_t status = (*mEffectInterface)->command(mEffectInterface,
6432 cmdCode,
6433 cmdSize,
6434 pCmdData,
6435 replySize,
6436 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006438 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 for (size_t i = 1; i < mHandles.size(); i++) {
6440 sp<EffectHandle> h = mHandles[i].promote();
6441 if (h != 0) {
6442 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6443 }
6444 }
6445 }
6446 return status;
6447}
6448
6449status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6450{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006451
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 Mutex::Autolock _l(mLock);
6453 LOGV("setEnabled %p enabled %d", this, enabled);
6454
6455 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006456 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6457 if (enabled && status != NO_ERROR) {
6458 return status;
6459 }
6460
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 switch (mState) {
6462 // going from disabled to enabled
6463 case IDLE:
6464 mState = STARTING;
6465 break;
6466 case STOPPED:
6467 mState = RESTART;
6468 break;
6469 case STOPPING:
6470 mState = ACTIVE;
6471 break;
6472
6473 // going from enabled to disabled
6474 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006475 mState = STOPPED;
6476 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 case STARTING:
6478 mState = IDLE;
6479 break;
6480 case ACTIVE:
6481 mState = STOPPING;
6482 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006483 case DESTROYED:
6484 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485 }
6486 for (size_t i = 1; i < mHandles.size(); i++) {
6487 sp<EffectHandle> h = mHandles[i].promote();
6488 if (h != 0) {
6489 h->setEnabled(enabled);
6490 }
6491 }
6492 }
6493 return NO_ERROR;
6494}
6495
6496bool AudioFlinger::EffectModule::isEnabled()
6497{
6498 switch (mState) {
6499 case RESTART:
6500 case STARTING:
6501 case ACTIVE:
6502 return true;
6503 case IDLE:
6504 case STOPPING:
6505 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006506 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006507 default:
6508 return false;
6509 }
6510}
6511
Eric Laurent8f45bd72010-08-31 13:50:07 -07006512bool AudioFlinger::EffectModule::isProcessEnabled()
6513{
6514 switch (mState) {
6515 case RESTART:
6516 case ACTIVE:
6517 case STOPPING:
6518 case STOPPED:
6519 return true;
6520 case IDLE:
6521 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006522 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006523 default:
6524 return false;
6525 }
6526}
6527
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6529{
6530 Mutex::Autolock _l(mLock);
6531 status_t status = NO_ERROR;
6532
6533 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6534 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006535 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006536 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6537 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 status_t cmdStatus;
6539 uint32_t volume[2];
6540 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006541 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006542 volume[0] = *left;
6543 volume[1] = *right;
6544 if (controller) {
6545 pVolume = volume;
6546 }
Eric Laurent25f43952010-07-28 05:40:18 -07006547 status = (*mEffectInterface)->command(mEffectInterface,
6548 EFFECT_CMD_SET_VOLUME,
6549 size,
6550 volume,
6551 &size,
6552 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6554 *left = volume[0];
6555 *right = volume[1];
6556 }
6557 }
6558 return status;
6559}
6560
6561status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6562{
6563 Mutex::Autolock _l(mLock);
6564 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006565 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6566 // audio pre processing modules on RecordThread can receive both output and
6567 // input device indication in the same call
6568 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6569 if (dev) {
6570 status_t cmdStatus;
6571 uint32_t size = sizeof(status_t);
6572
6573 status = (*mEffectInterface)->command(mEffectInterface,
6574 EFFECT_CMD_SET_DEVICE,
6575 sizeof(uint32_t),
6576 &dev,
6577 &size,
6578 &cmdStatus);
6579 if (status == NO_ERROR) {
6580 status = cmdStatus;
6581 }
6582 }
6583 dev = device & AUDIO_DEVICE_IN_ALL;
6584 if (dev) {
6585 status_t cmdStatus;
6586 uint32_t size = sizeof(status_t);
6587
6588 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6589 EFFECT_CMD_SET_INPUT_DEVICE,
6590 sizeof(uint32_t),
6591 &dev,
6592 &size,
6593 &cmdStatus);
6594 if (status2 == NO_ERROR) {
6595 status2 = cmdStatus;
6596 }
6597 if (status == NO_ERROR) {
6598 status = status2;
6599 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600 }
6601 }
6602 return status;
6603}
6604
6605status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6606{
6607 Mutex::Autolock _l(mLock);
6608 status_t status = NO_ERROR;
6609 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006611 uint32_t size = sizeof(status_t);
6612 status = (*mEffectInterface)->command(mEffectInterface,
6613 EFFECT_CMD_SET_AUDIO_MODE,
6614 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006615 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006616 &size,
6617 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618 if (status == NO_ERROR) {
6619 status = cmdStatus;
6620 }
6621 }
6622 return status;
6623}
6624
Eric Laurent59255e42011-07-27 19:49:51 -07006625void AudioFlinger::EffectModule::setSuspended(bool suspended)
6626{
6627 Mutex::Autolock _l(mLock);
6628 mSuspended = suspended;
6629}
6630bool AudioFlinger::EffectModule::suspended()
6631{
6632 Mutex::Autolock _l(mLock);
6633 return mSuspended;
6634}
6635
Mathias Agopian65ab4712010-07-14 17:59:35 -07006636status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6637{
6638 const size_t SIZE = 256;
6639 char buffer[SIZE];
6640 String8 result;
6641
6642 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6643 result.append(buffer);
6644
6645 bool locked = tryLock(mLock);
6646 // failed to lock - AudioFlinger is probably deadlocked
6647 if (!locked) {
6648 result.append("\t\tCould not lock Fx mutex:\n");
6649 }
6650
6651 result.append("\t\tSession Status State Engine:\n");
6652 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6653 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6654 result.append(buffer);
6655
6656 result.append("\t\tDescriptor:\n");
6657 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6658 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6659 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6660 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6661 result.append(buffer);
6662 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6663 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6664 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6665 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6666 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006667 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006668 mDescriptor.apiVersion,
6669 mDescriptor.flags);
6670 result.append(buffer);
6671 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6672 mDescriptor.name);
6673 result.append(buffer);
6674 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6675 mDescriptor.implementor);
6676 result.append(buffer);
6677
6678 result.append("\t\t- Input configuration:\n");
6679 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6680 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6681 (uint32_t)mConfig.inputCfg.buffer.raw,
6682 mConfig.inputCfg.buffer.frameCount,
6683 mConfig.inputCfg.samplingRate,
6684 mConfig.inputCfg.channels,
6685 mConfig.inputCfg.format);
6686 result.append(buffer);
6687
6688 result.append("\t\t- Output configuration:\n");
6689 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6690 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6691 (uint32_t)mConfig.outputCfg.buffer.raw,
6692 mConfig.outputCfg.buffer.frameCount,
6693 mConfig.outputCfg.samplingRate,
6694 mConfig.outputCfg.channels,
6695 mConfig.outputCfg.format);
6696 result.append(buffer);
6697
6698 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6699 result.append(buffer);
6700 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6701 for (size_t i = 0; i < mHandles.size(); ++i) {
6702 sp<EffectHandle> handle = mHandles[i].promote();
6703 if (handle != 0) {
6704 handle->dump(buffer, SIZE);
6705 result.append(buffer);
6706 }
6707 }
6708
6709 result.append("\n");
6710
6711 write(fd, result.string(), result.length());
6712
6713 if (locked) {
6714 mLock.unlock();
6715 }
6716
6717 return NO_ERROR;
6718}
6719
6720// ----------------------------------------------------------------------------
6721// EffectHandle implementation
6722// ----------------------------------------------------------------------------
6723
6724#undef LOG_TAG
6725#define LOG_TAG "AudioFlinger::EffectHandle"
6726
6727AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6728 const sp<AudioFlinger::Client>& client,
6729 const sp<IEffectClient>& effectClient,
6730 int32_t priority)
6731 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006732 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006733 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006734{
6735 LOGV("constructor %p", this);
6736
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006737 if (client == 0) {
6738 return;
6739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6741 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6742 if (mCblkMemory != 0) {
6743 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6744
6745 if (mCblk) {
6746 new(mCblk) effect_param_cblk_t();
6747 mBuffer = (uint8_t *)mCblk + bufOffset;
6748 }
6749 } else {
6750 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6751 return;
6752 }
6753}
6754
6755AudioFlinger::EffectHandle::~EffectHandle()
6756{
6757 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006758 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07006759 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760}
6761
6762status_t AudioFlinger::EffectHandle::enable()
6763{
Eric Laurent59255e42011-07-27 19:49:51 -07006764 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006765 if (!mHasControl) return INVALID_OPERATION;
6766 if (mEffect == 0) return DEAD_OBJECT;
6767
Eric Laurentdb7c0792011-08-10 10:37:50 -07006768 if (mEnabled) {
6769 return NO_ERROR;
6770 }
6771
Eric Laurent59255e42011-07-27 19:49:51 -07006772 mEnabled = true;
6773
6774 sp<ThreadBase> thread = mEffect->thread().promote();
6775 if (thread != 0) {
6776 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6777 }
6778
6779 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6780 if (mEffect->suspended()) {
6781 return NO_ERROR;
6782 }
6783
Eric Laurentdb7c0792011-08-10 10:37:50 -07006784 status_t status = mEffect->setEnabled(true);
6785 if (status != NO_ERROR) {
6786 if (thread != 0) {
6787 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6788 }
6789 mEnabled = false;
6790 }
6791 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792}
6793
6794status_t AudioFlinger::EffectHandle::disable()
6795{
Eric Laurent59255e42011-07-27 19:49:51 -07006796 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006798 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006799
Eric Laurentdb7c0792011-08-10 10:37:50 -07006800 if (!mEnabled) {
6801 return NO_ERROR;
6802 }
Eric Laurent59255e42011-07-27 19:49:51 -07006803 mEnabled = false;
6804
6805 if (mEffect->suspended()) {
6806 return NO_ERROR;
6807 }
6808
6809 status_t status = mEffect->setEnabled(false);
6810
6811 sp<ThreadBase> thread = mEffect->thread().promote();
6812 if (thread != 0) {
6813 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6814 }
6815
6816 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006817}
6818
6819void AudioFlinger::EffectHandle::disconnect()
6820{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006821 disconnect(true);
6822}
6823
6824void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6825{
6826 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006827 if (mEffect == 0) {
6828 return;
6829 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006830 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006831
Eric Laurentdb7c0792011-08-10 10:37:50 -07006832 if (mEnabled) {
6833 sp<ThreadBase> thread = mEffect->thread().promote();
6834 if (thread != 0) {
6835 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6836 }
Eric Laurent59255e42011-07-27 19:49:51 -07006837 }
6838
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839 // release sp on module => module destructor can be called now
6840 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006841 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006842 if (mCblk) {
6843 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6844 }
6845 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006846 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6847 mClient.clear();
6848 }
6849}
6850
Eric Laurent25f43952010-07-28 05:40:18 -07006851status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6852 uint32_t cmdSize,
6853 void *pCmdData,
6854 uint32_t *replySize,
6855 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006856{
Eric Laurent25f43952010-07-28 05:40:18 -07006857// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6858// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006859
6860 // only get parameter command is permitted for applications not controlling the effect
6861 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6862 return INVALID_OPERATION;
6863 }
6864 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006865 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866
6867 // handle commands that are not forwarded transparently to effect engine
6868 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6869 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6870 // no risk to block the whole media server process or mixer threads is we are stuck here
6871 Mutex::Autolock _l(mCblk->lock);
6872 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6873 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6874 mCblk->serverIndex = 0;
6875 mCblk->clientIndex = 0;
6876 return BAD_VALUE;
6877 }
6878 status_t status = NO_ERROR;
6879 while (mCblk->serverIndex < mCblk->clientIndex) {
6880 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006881 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006882 int *p = (int *)(mBuffer + mCblk->serverIndex);
6883 int size = *p++;
6884 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6885 LOGW("command(): invalid parameter block size");
6886 break;
6887 }
6888 effect_param_t *param = (effect_param_t *)p;
6889 if (param->psize == 0 || param->vsize == 0) {
6890 LOGW("command(): null parameter or value size");
6891 mCblk->serverIndex += size;
6892 continue;
6893 }
Eric Laurent25f43952010-07-28 05:40:18 -07006894 uint32_t psize = sizeof(effect_param_t) +
6895 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6896 param->vsize;
6897 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6898 psize,
6899 p,
6900 &rsize,
6901 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006902 // stop at first error encountered
6903 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006904 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006905 *(int *)pReplyData = reply;
6906 break;
6907 } else if (reply != NO_ERROR) {
6908 *(int *)pReplyData = reply;
6909 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910 }
6911 mCblk->serverIndex += size;
6912 }
6913 mCblk->serverIndex = 0;
6914 mCblk->clientIndex = 0;
6915 return status;
6916 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006917 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 return enable();
6919 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006920 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006921 return disable();
6922 }
6923
6924 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6925}
6926
6927sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6928 return mCblkMemory;
6929}
6930
Eric Laurent59255e42011-07-27 19:49:51 -07006931void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006932{
6933 LOGV("setControl %p control %d", this, hasControl);
6934
6935 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006936 mEnabled = enabled;
6937
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938 if (signal && mEffectClient != 0) {
6939 mEffectClient->controlStatusChanged(hasControl);
6940 }
6941}
6942
Eric Laurent25f43952010-07-28 05:40:18 -07006943void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6944 uint32_t cmdSize,
6945 void *pCmdData,
6946 uint32_t replySize,
6947 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948{
6949 if (mEffectClient != 0) {
6950 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6951 }
6952}
6953
6954
6955
6956void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6957{
6958 if (mEffectClient != 0) {
6959 mEffectClient->enableStatusChanged(enabled);
6960 }
6961}
6962
6963status_t AudioFlinger::EffectHandle::onTransact(
6964 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6965{
6966 return BnEffect::onTransact(code, data, reply, flags);
6967}
6968
6969
6970void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6971{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006972 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973
6974 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6975 (mClient == NULL) ? getpid() : mClient->pid(),
6976 mPriority,
6977 mHasControl,
6978 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006979 mCblk ? mCblk->clientIndex : 0,
6980 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 );
6982
6983 if (locked) {
6984 mCblk->lock.unlock();
6985 }
6986}
6987
6988#undef LOG_TAG
6989#define LOG_TAG "AudioFlinger::EffectChain"
6990
6991AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6992 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006993 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6994 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6995 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006996{
Dima Zavinfce7a472011-04-19 22:30:36 -07006997 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998}
6999
7000AudioFlinger::EffectChain::~EffectChain()
7001{
7002 if (mOwnInBuffer) {
7003 delete mInBuffer;
7004 }
7005
7006}
7007
Eric Laurent59255e42011-07-27 19:49:51 -07007008// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007009sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010{
7011 sp<EffectModule> effect;
7012 size_t size = mEffects.size();
7013
7014 for (size_t i = 0; i < size; i++) {
7015 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7016 effect = mEffects[i];
7017 break;
7018 }
7019 }
7020 return effect;
7021}
7022
Eric Laurent59255e42011-07-27 19:49:51 -07007023// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007024sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007025{
7026 sp<EffectModule> effect;
7027 size_t size = mEffects.size();
7028
7029 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007030 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7031 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007032 effect = mEffects[i];
7033 break;
7034 }
7035 }
7036 return effect;
7037}
7038
Eric Laurent59255e42011-07-27 19:49:51 -07007039// getEffectFromType_l() must be called with ThreadBase::mLock held
7040sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7041 const effect_uuid_t *type)
7042{
7043 sp<EffectModule> effect;
7044 size_t size = mEffects.size();
7045
7046 for (size_t i = 0; i < size; i++) {
7047 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7048 effect = mEffects[i];
7049 break;
7050 }
7051 }
7052 return effect;
7053}
7054
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055// Must be called with EffectChain::mLock locked
7056void AudioFlinger::EffectChain::process_l()
7057{
Eric Laurentdac69112010-09-28 14:09:57 -07007058 sp<ThreadBase> thread = mThread.promote();
7059 if (thread == 0) {
7060 LOGW("process_l(): cannot promote mixer thread");
7061 return;
7062 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007063 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7064 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07007065 bool tracksOnSession = false;
7066 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07007067 tracksOnSession = (trackCnt() != 0);
7068 }
7069
7070 // if no track is active, input buffer must be cleared here as the mixer process
7071 // will not do it
7072 if (tracksOnSession &&
7073 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007074 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07007075 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07007076 }
7077
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07007079 // do not process effect if no track is present in same audio session
7080 if (isGlobalSession || tracksOnSession) {
7081 for (size_t i = 0; i < size; i++) {
7082 mEffects[i]->process();
7083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 }
7085 for (size_t i = 0; i < size; i++) {
7086 mEffects[i]->updateState();
7087 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088}
7089
Eric Laurentcab11242010-07-15 12:50:15 -07007090// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007091status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092{
7093 effect_descriptor_t desc = effect->desc();
7094 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7095
7096 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007097 effect->setChain(this);
7098 sp<ThreadBase> thread = mThread.promote();
7099 if (thread == 0) {
7100 return NO_INIT;
7101 }
7102 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103
7104 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7105 // Auxiliary effects are inserted at the beginning of mEffects vector as
7106 // they are processed first and accumulated in chain input buffer
7107 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007108
Mathias Agopian65ab4712010-07-14 17:59:35 -07007109 // the input buffer for auxiliary effect contains mono samples in
7110 // 32 bit format. This is to avoid saturation in AudoMixer
7111 // accumulation stage. Saturation is done in EffectModule::process() before
7112 // calling the process in effect engine
7113 size_t numSamples = thread->frameCount();
7114 int32_t *buffer = new int32_t[numSamples];
7115 memset(buffer, 0, numSamples * sizeof(int32_t));
7116 effect->setInBuffer((int16_t *)buffer);
7117 // auxiliary effects output samples to chain input buffer for further processing
7118 // by insert effects
7119 effect->setOutBuffer(mInBuffer);
7120 } else {
7121 // Insert effects are inserted at the end of mEffects vector as they are processed
7122 // after track and auxiliary effects.
7123 // Insert effect order as a function of indicated preference:
7124 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7125 // another effect is present
7126 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7127 // last effect claiming first position
7128 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7129 // first effect claiming last position
7130 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7131 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7132 // already present
7133
7134 int size = (int)mEffects.size();
7135 int idx_insert = size;
7136 int idx_insert_first = -1;
7137 int idx_insert_last = -1;
7138
7139 for (int i = 0; i < size; i++) {
7140 effect_descriptor_t d = mEffects[i]->desc();
7141 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7142 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7143 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7144 // check invalid effect chaining combinations
7145 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7146 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007147 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007148 return INVALID_OPERATION;
7149 }
7150 // remember position of first insert effect and by default
7151 // select this as insert position for new effect
7152 if (idx_insert == size) {
7153 idx_insert = i;
7154 }
7155 // remember position of last insert effect claiming
7156 // first position
7157 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7158 idx_insert_first = i;
7159 }
7160 // remember position of first insert effect claiming
7161 // last position
7162 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7163 idx_insert_last == -1) {
7164 idx_insert_last = i;
7165 }
7166 }
7167 }
7168
7169 // modify idx_insert from first position if needed
7170 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7171 if (idx_insert_last != -1) {
7172 idx_insert = idx_insert_last;
7173 } else {
7174 idx_insert = size;
7175 }
7176 } else {
7177 if (idx_insert_first != -1) {
7178 idx_insert = idx_insert_first + 1;
7179 }
7180 }
7181
7182 // always read samples from chain input buffer
7183 effect->setInBuffer(mInBuffer);
7184
7185 // if last effect in the chain, output samples to chain
7186 // output buffer, otherwise to chain input buffer
7187 if (idx_insert == size) {
7188 if (idx_insert != 0) {
7189 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7190 mEffects[idx_insert-1]->configure();
7191 }
7192 effect->setOutBuffer(mOutBuffer);
7193 } else {
7194 effect->setOutBuffer(mInBuffer);
7195 }
7196 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007197
Eric Laurentcab11242010-07-15 12:50:15 -07007198 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007199 }
7200 effect->configure();
7201 return NO_ERROR;
7202}
7203
Eric Laurentcab11242010-07-15 12:50:15 -07007204// removeEffect_l() must be called with PlaybackThread::mLock held
7205size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206{
7207 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007208 int size = (int)mEffects.size();
7209 int i;
7210 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7211
7212 for (i = 0; i < size; i++) {
7213 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007214 // calling stop here will remove pre-processing effect from the audio HAL.
7215 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7216 // the middle of a read from audio HAL
7217 mEffects[i]->stop();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007218 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7219 delete[] effect->inBuffer();
7220 } else {
7221 if (i == size - 1 && i != 0) {
7222 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7223 mEffects[i - 1]->configure();
7224 }
7225 }
7226 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007227 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007228 break;
7229 }
7230 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007231
7232 return mEffects.size();
7233}
7234
Eric Laurentcab11242010-07-15 12:50:15 -07007235// setDevice_l() must be called with PlaybackThread::mLock held
7236void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237{
7238 size_t size = mEffects.size();
7239 for (size_t i = 0; i < size; i++) {
7240 mEffects[i]->setDevice(device);
7241 }
7242}
7243
Eric Laurentcab11242010-07-15 12:50:15 -07007244// setMode_l() must be called with PlaybackThread::mLock held
7245void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007246{
7247 size_t size = mEffects.size();
7248 for (size_t i = 0; i < size; i++) {
7249 mEffects[i]->setMode(mode);
7250 }
7251}
7252
Eric Laurentcab11242010-07-15 12:50:15 -07007253// setVolume_l() must be called with PlaybackThread::mLock held
7254bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007255{
7256 uint32_t newLeft = *left;
7257 uint32_t newRight = *right;
7258 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007259 int ctrlIdx = -1;
7260 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007261
Eric Laurentcab11242010-07-15 12:50:15 -07007262 // first update volume controller
7263 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007264 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007265 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7266 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007267 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007268 break;
7269 }
7270 }
7271
7272 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007273 if (hasControl) {
7274 *left = mNewLeftVolume;
7275 *right = mNewRightVolume;
7276 }
7277 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007278 }
7279
7280 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007281 mLeftVolume = newLeft;
7282 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007283
7284 // second get volume update from volume controller
7285 if (ctrlIdx >= 0) {
7286 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007287 mNewLeftVolume = newLeft;
7288 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007289 }
7290 // then indicate volume to all other effects in chain.
7291 // Pass altered volume to effects before volume controller
7292 // and requested volume to effects after controller
7293 uint32_t lVol = newLeft;
7294 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007295
Mathias Agopian65ab4712010-07-14 17:59:35 -07007296 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007297 if ((int)i == ctrlIdx) continue;
7298 // this also works for ctrlIdx == -1 when there is no volume controller
7299 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300 lVol = *left;
7301 rVol = *right;
7302 }
7303 mEffects[i]->setVolume(&lVol, &rVol, false);
7304 }
7305 *left = newLeft;
7306 *right = newRight;
7307
7308 return hasControl;
7309}
7310
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7312{
7313 const size_t SIZE = 256;
7314 char buffer[SIZE];
7315 String8 result;
7316
7317 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7318 result.append(buffer);
7319
7320 bool locked = tryLock(mLock);
7321 // failed to lock - AudioFlinger is probably deadlocked
7322 if (!locked) {
7323 result.append("\tCould not lock mutex:\n");
7324 }
7325
Eric Laurentcab11242010-07-15 12:50:15 -07007326 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7327 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007328 mEffects.size(),
7329 (uint32_t)mInBuffer,
7330 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331 mActiveTrackCnt);
7332 result.append(buffer);
7333 write(fd, result.string(), result.size());
7334
7335 for (size_t i = 0; i < mEffects.size(); ++i) {
7336 sp<EffectModule> effect = mEffects[i];
7337 if (effect != 0) {
7338 effect->dump(fd, args);
7339 }
7340 }
7341
7342 if (locked) {
7343 mLock.unlock();
7344 }
7345
7346 return NO_ERROR;
7347}
7348
Eric Laurent59255e42011-07-27 19:49:51 -07007349// must be called with ThreadBase::mLock held
7350void AudioFlinger::EffectChain::setEffectSuspended_l(
7351 const effect_uuid_t *type, bool suspend)
7352{
7353 sp<SuspendedEffectDesc> desc;
7354 // use effect type UUID timelow as key as there is no real risk of identical
7355 // timeLow fields among effect type UUIDs.
7356 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7357 if (suspend) {
7358 if (index >= 0) {
7359 desc = mSuspendedEffects.valueAt(index);
7360 } else {
7361 desc = new SuspendedEffectDesc();
7362 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7363 mSuspendedEffects.add(type->timeLow, desc);
7364 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7365 }
7366 if (desc->mRefCount++ == 0) {
7367 sp<EffectModule> effect = getEffectIfEnabled(type);
7368 if (effect != 0) {
7369 desc->mEffect = effect;
7370 effect->setSuspended(true);
7371 effect->setEnabled(false);
7372 }
7373 }
7374 } else {
7375 if (index < 0) {
7376 return;
7377 }
7378 desc = mSuspendedEffects.valueAt(index);
7379 if (desc->mRefCount <= 0) {
7380 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7381 desc->mRefCount = 1;
7382 }
7383 if (--desc->mRefCount == 0) {
7384 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7385 if (desc->mEffect != 0) {
7386 sp<EffectModule> effect = desc->mEffect.promote();
7387 if (effect != 0) {
7388 effect->setSuspended(false);
7389 sp<EffectHandle> handle = effect->controlHandle();
7390 if (handle != 0) {
7391 effect->setEnabled(handle->enabled());
7392 }
7393 }
7394 desc->mEffect.clear();
7395 }
7396 mSuspendedEffects.removeItemsAt(index);
7397 }
7398 }
7399}
7400
7401// must be called with ThreadBase::mLock held
7402void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7403{
7404 sp<SuspendedEffectDesc> desc;
7405
7406 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7407 if (suspend) {
7408 if (index >= 0) {
7409 desc = mSuspendedEffects.valueAt(index);
7410 } else {
7411 desc = new SuspendedEffectDesc();
7412 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7413 LOGV("setEffectSuspendedAll_l() add entry for 0");
7414 }
7415 if (desc->mRefCount++ == 0) {
7416 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7417 for (size_t i = 0; i < effects.size(); i++) {
7418 setEffectSuspended_l(&effects[i]->desc().type, true);
7419 }
7420 }
7421 } else {
7422 if (index < 0) {
7423 return;
7424 }
7425 desc = mSuspendedEffects.valueAt(index);
7426 if (desc->mRefCount <= 0) {
7427 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7428 desc->mRefCount = 1;
7429 }
7430 if (--desc->mRefCount == 0) {
7431 Vector<const effect_uuid_t *> types;
7432 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7433 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7434 continue;
7435 }
7436 types.add(&mSuspendedEffects.valueAt(i)->mType);
7437 }
7438 for (size_t i = 0; i < types.size(); i++) {
7439 setEffectSuspended_l(types[i], false);
7440 }
7441 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7442 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7443 }
7444 }
7445}
7446
Eric Laurent6bffdb82011-09-23 08:40:41 -07007447
7448// The volume effect is used for automated tests only
7449#ifndef OPENSL_ES_H_
7450static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7451 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7452const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7453#endif //OPENSL_ES_H_
7454
Eric Laurentdb7c0792011-08-10 10:37:50 -07007455bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7456{
7457 // auxiliary effects and visualizer are never suspended on output mix
7458 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7459 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007460 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7461 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007462 return false;
7463 }
7464 return true;
7465}
7466
Eric Laurent59255e42011-07-27 19:49:51 -07007467Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7468{
7469 Vector< sp<EffectModule> > effects;
7470 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007471 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007472 continue;
7473 }
7474 effects.add(mEffects[i]);
7475 }
7476 return effects;
7477}
7478
7479sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7480 const effect_uuid_t *type)
7481{
7482 sp<EffectModule> effect;
7483 effect = getEffectFromType_l(type);
7484 if (effect != 0 && !effect->isEnabled()) {
7485 effect.clear();
7486 }
7487 return effect;
7488}
7489
7490void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7491 bool enabled)
7492{
7493 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7494 if (enabled) {
7495 if (index < 0) {
7496 // if the effect is not suspend check if all effects are suspended
7497 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7498 if (index < 0) {
7499 return;
7500 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007501 if (!isEffectEligibleForSuspend(effect->desc())) {
7502 return;
7503 }
Eric Laurent59255e42011-07-27 19:49:51 -07007504 setEffectSuspended_l(&effect->desc().type, enabled);
7505 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007506 if (index < 0) {
7507 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7508 return;
7509 }
Eric Laurent59255e42011-07-27 19:49:51 -07007510 }
7511 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7512 effect->desc().type.timeLow);
7513 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7514 // if effect is requested to suspended but was not yet enabled, supend it now.
7515 if (desc->mEffect == 0) {
7516 desc->mEffect = effect;
7517 effect->setEnabled(false);
7518 effect->setSuspended(true);
7519 }
7520 } else {
7521 if (index < 0) {
7522 return;
7523 }
7524 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7525 effect->desc().type.timeLow);
7526 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7527 desc->mEffect.clear();
7528 effect->setSuspended(false);
7529 }
7530}
7531
Mathias Agopian65ab4712010-07-14 17:59:35 -07007532#undef LOG_TAG
7533#define LOG_TAG "AudioFlinger"
7534
7535// ----------------------------------------------------------------------------
7536
7537status_t AudioFlinger::onTransact(
7538 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7539{
7540 return BnAudioFlinger::onTransact(code, data, reply, flags);
7541}
7542
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543}; // namespace android