blob: 58482d57f09a75bde8c2cae044a601cea0226641 [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 Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
68static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
69static const char* kHardwareLockedString = "Hardware lock is taken\n";
70
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
73static const float MAX_GAIN_INT = 0x1000;
74
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
85static const int kDumpLockSleep = 20000;
86
87static const nsecs_t kWarningThrottle = seconds(5);
88
Eric Laurent7c7f10b2011-06-17 21:29:58 -070089// RecordThread loop sleep time upon application overrun or audio HAL read error
90static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070091
Eric Laurent60cd0a02011-09-13 11:40:21 -070092static const nsecs_t kSetParametersTimeout = seconds(2);
93
Eric Laurent7cafbb32011-11-22 18:50:29 -080094// minimum sleep time for the mixer thread loop when tracks are active but in underrun
95static const uint32_t kMinThreadSleepTimeUs = 5000;
96// maximum divider applied to the active sleep time in the mixer thread loop
97static const uint32_t kMaxThreadSleepTimeShift = 2;
98
99
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100// ----------------------------------------------------------------------------
101
102static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
105 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
106 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107}
108
109static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
111 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
112 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
113 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114}
115
Gloria Wang9ee159b2011-02-24 14:51:45 -0800116// To collect the amplifier usage
117static void addBatteryData(uint32_t params) {
118 sp<IBinder> binder =
119 defaultServiceManager()->getService(String16("media.player"));
120 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
121 if (service.get() == NULL) {
122 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
139 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
152static const char *audio_interfaces[] = {
153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Eric Laurent59bd0da2011-08-01 09:52:20 -0700163 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700164 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700171
Eric Laurent93575202011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin799a70e2011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175 mHardwareStatus = AUDIO_HW_IDLE;
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
178 const hw_module_t *mod;
179 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700180
Dima Zavin799a70e2011-04-18 16:57:27 -0700181 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
182 if (rc)
183 continue;
184
185 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
186 mod->name, mod->id);
187 mAudioHwDevs.push(dev);
188
189 if (!mPrimaryHardwareDev) {
190 mPrimaryHardwareDev = dev;
191 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 }
194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195
196 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
199 LOGE("Primary audio interface not found");
200 return;
201 }
202
203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204 audio_hw_device_t *dev = mAudioHwDevs[i];
205
206 mHardwareStatus = AUDIO_HW_INIT;
207 rc = dev->init_check(dev);
208 if (rc == 0) {
209 AutoMutex lock(mHardwareLock);
210
211 mMode = AUDIO_MODE_NORMAL;
212 mHardwareStatus = AUDIO_HW_SET_MODE;
213 dev->set_mode(dev, mMode);
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 dev->set_master_volume(dev, 1.0f);
216 mHardwareStatus = AUDIO_HW_IDLE;
217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219}
220
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700221status_t AudioFlinger::initCheck() const
222{
223 Mutex::Autolock _l(mLock);
224 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
225 return NO_INIT;
226 return NO_ERROR;
227}
228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229AudioFlinger::~AudioFlinger()
230{
Dima Zavin799a70e2011-04-18 16:57:27 -0700231 int num_devs = mAudioHwDevs.size();
232
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700241
242 for (int i = 0; i < num_devs; i++) {
243 audio_hw_device_t *dev = mAudioHwDevs[i];
244 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
Dima Zavin799a70e2011-04-18 16:57:27 -0700249audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
250{
251 /* first matching HW device is returned */
252 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
253 audio_hw_device_t *dev = mAudioHwDevs[i];
254 if ((dev->get_supported_devices(dev) & devices) == devices)
255 return dev;
256 }
257 return NULL;
258}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259
260status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
261{
262 const size_t SIZE = 256;
263 char buffer[SIZE];
264 String8 result;
265
266 result.append("Clients:\n");
267 for (size_t i = 0; i < mClients.size(); ++i) {
268 wp<Client> wClient = mClients.valueAt(i);
269 if (wClient != 0) {
270 sp<Client> client = wClient.promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
274 }
275 }
276 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700277
278 result.append("Global session refs:\n");
279 result.append(" session pid cnt\n");
280 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
281 AudioSessionRef *r = mAudioSessionRefs[i];
282 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
283 result.append(buffer);
284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285 write(fd, result.string(), result.size());
286 return NO_ERROR;
287}
288
289
290status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
295 int hardwareStatus = mHardwareStatus;
296
297 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
298 result.append(buffer);
299 write(fd, result.string(), result.size());
300 return NO_ERROR;
301}
302
303status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308 snprintf(buffer, SIZE, "Permission Denial: "
309 "can't dump AudioFlinger from pid=%d, uid=%d\n",
310 IPCThreadState::self()->getCallingPid(),
311 IPCThreadState::self()->getCallingUid());
312 result.append(buffer);
313 write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
317static bool tryLock(Mutex& mutex)
318{
319 bool locked = false;
320 for (int i = 0; i < kDumpLockRetries; ++i) {
321 if (mutex.tryLock() == NO_ERROR) {
322 locked = true;
323 break;
324 }
325 usleep(kDumpLockSleep);
326 }
327 return locked;
328}
329
330status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
331{
332 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
333 dumpPermissionDenial(fd, args);
334 } else {
335 // get state of hardware lock
336 bool hardwareLocked = tryLock(mHardwareLock);
337 if (!hardwareLocked) {
338 String8 result(kHardwareLockedString);
339 write(fd, result.string(), result.size());
340 } else {
341 mHardwareLock.unlock();
342 }
343
344 bool locked = tryLock(mLock);
345
346 // failed to lock - AudioFlinger is probably deadlocked
347 if (!locked) {
348 String8 result(kDeadlockedString);
349 write(fd, result.string(), result.size());
350 }
351
352 dumpClients(fd, args);
353 dumpInternals(fd, args);
354
355 // dump playback threads
356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
357 mPlaybackThreads.valueAt(i)->dump(fd, args);
358 }
359
360 // dump record threads
361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
362 mRecordThreads.valueAt(i)->dump(fd, args);
363 }
364
Dima Zavin799a70e2011-04-18 16:57:27 -0700365 // dump all hardware devs
366 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
367 audio_hw_device_t *dev = mAudioHwDevs[i];
368 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369 }
370 if (locked) mLock.unlock();
371 }
372 return NO_ERROR;
373}
374
375
376// IAudioFlinger interface
377
378
379sp<IAudioTrack> AudioFlinger::createTrack(
380 pid_t pid,
381 int streamType,
382 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700383 uint32_t format,
384 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 int frameCount,
386 uint32_t flags,
387 const sp<IMemory>& sharedBuffer,
388 int output,
389 int *sessionId,
390 status_t *status)
391{
392 sp<PlaybackThread::Track> track;
393 sp<TrackHandle> trackHandle;
394 sp<Client> client;
395 wp<Client> wclient;
396 status_t lStatus;
397 int lSessionId;
398
Dima Zavinfce7a472011-04-19 22:30:36 -0700399 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400 LOGE("invalid stream type");
401 lStatus = BAD_VALUE;
402 goto Exit;
403 }
404
405 {
406 Mutex::Autolock _l(mLock);
407 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700408 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 if (thread == NULL) {
410 LOGE("unknown output thread");
411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414
415 wclient = mClients.valueFor(pid);
416
417 if (wclient != NULL) {
418 client = wclient.promote();
419 } else {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
Steve Block3856b092011-10-20 11:56:00 +0100424 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700425 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700426 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700427 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
428 if (mPlaybackThreads.keyAt(i) != output) {
429 // prevent same audio session on different output threads
430 uint32_t sessions = t->hasAudioSession(*sessionId);
431 if (sessions & PlaybackThread::TRACK_SESSION) {
432 lStatus = BAD_VALUE;
433 goto Exit;
434 }
435 // check if an effect with same session ID is waiting for a track to be created
436 if (sessions & PlaybackThread::EFFECT_SESSION) {
437 effectThread = t.get();
438 }
Eric Laurentde070132010-07-13 04:45:46 -0700439 }
440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 lSessionId = *sessionId;
442 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700443 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700444 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 if (sessionId != NULL) {
446 *sessionId = lSessionId;
447 }
448 }
Steve Block3856b092011-10-20 11:56:00 +0100449 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450
451 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700452 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700453
454 // move effect chain to this output thread if an effect on same session was waiting
455 // for a track to be created
456 if (lStatus == NO_ERROR && effectThread != NULL) {
457 Mutex::Autolock _dl(thread->mLock);
458 Mutex::Autolock _sl(effectThread->mLock);
459 moveEffectChain_l(lSessionId, effectThread, thread, true);
460 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 }
462 if (lStatus == NO_ERROR) {
463 trackHandle = new TrackHandle(track);
464 } else {
465 // remove local strong reference to Client before deleting the Track so that the Client
466 // destructor is called by the TrackBase destructor with mLock held
467 client.clear();
468 track.clear();
469 }
470
471Exit:
472 if(status) {
473 *status = lStatus;
474 }
475 return trackHandle;
476}
477
478uint32_t AudioFlinger::sampleRate(int output) const
479{
480 Mutex::Autolock _l(mLock);
481 PlaybackThread *thread = checkPlaybackThread_l(output);
482 if (thread == NULL) {
483 LOGW("sampleRate() unknown thread %d", output);
484 return 0;
485 }
486 return thread->sampleRate();
487}
488
489int AudioFlinger::channelCount(int output) const
490{
491 Mutex::Autolock _l(mLock);
492 PlaybackThread *thread = checkPlaybackThread_l(output);
493 if (thread == NULL) {
494 LOGW("channelCount() unknown thread %d", output);
495 return 0;
496 }
497 return thread->channelCount();
498}
499
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700500uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501{
502 Mutex::Autolock _l(mLock);
503 PlaybackThread *thread = checkPlaybackThread_l(output);
504 if (thread == NULL) {
505 LOGW("format() unknown thread %d", output);
506 return 0;
507 }
508 return thread->format();
509}
510
511size_t AudioFlinger::frameCount(int output) const
512{
513 Mutex::Autolock _l(mLock);
514 PlaybackThread *thread = checkPlaybackThread_l(output);
515 if (thread == NULL) {
516 LOGW("frameCount() unknown thread %d", output);
517 return 0;
518 }
519 return thread->frameCount();
520}
521
522uint32_t AudioFlinger::latency(int output) const
523{
524 Mutex::Autolock _l(mLock);
525 PlaybackThread *thread = checkPlaybackThread_l(output);
526 if (thread == NULL) {
527 LOGW("latency() unknown thread %d", output);
528 return 0;
529 }
530 return thread->latency();
531}
532
533status_t AudioFlinger::setMasterVolume(float value)
534{
Eric Laurenta1884f92011-08-23 08:25:03 -0700535 status_t ret = initCheck();
536 if (ret != NO_ERROR) {
537 return ret;
538 }
539
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540 // check calling permissions
541 if (!settingsAllowed()) {
542 return PERMISSION_DENIED;
543 }
544
545 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800546 { // scope for the lock
547 AutoMutex lock(mHardwareLock);
548 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700549 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800550 value = 1.0f;
551 }
552 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554
Eric Laurent93575202011-01-18 18:39:02 -0800555 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 mMasterVolume = value;
557 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
558 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
559
560 return NO_ERROR;
561}
562
563status_t AudioFlinger::setMode(int mode)
564{
Eric Laurenta1884f92011-08-23 08:25:03 -0700565 status_t ret = initCheck();
566 if (ret != NO_ERROR) {
567 return ret;
568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569
570 // check calling permissions
571 if (!settingsAllowed()) {
572 return PERMISSION_DENIED;
573 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700574 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 LOGW("Illegal value: setMode(%d)", mode);
576 return BAD_VALUE;
577 }
578
579 { // scope for the lock
580 AutoMutex lock(mHardwareLock);
581 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700582 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 mHardwareStatus = AUDIO_HW_IDLE;
584 }
585
586 if (NO_ERROR == ret) {
587 Mutex::Autolock _l(mLock);
588 mMode = mode;
589 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
590 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 }
592
593 return ret;
594}
595
596status_t AudioFlinger::setMicMute(bool state)
597{
Eric Laurenta1884f92011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
608 AutoMutex lock(mHardwareLock);
609 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700610 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 mHardwareStatus = AUDIO_HW_IDLE;
612 return ret;
613}
614
615bool AudioFlinger::getMicMute() const
616{
Eric Laurenta1884f92011-08-23 08:25:03 -0700617 status_t ret = initCheck();
618 if (ret != NO_ERROR) {
619 return false;
620 }
621
Dima Zavinfce7a472011-04-19 22:30:36 -0700622 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700624 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 return state;
627}
628
629status_t AudioFlinger::setMasterMute(bool muted)
630{
631 // check calling permissions
632 if (!settingsAllowed()) {
633 return PERMISSION_DENIED;
634 }
635
Eric Laurent93575202011-01-18 18:39:02 -0800636 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 mMasterMute = muted;
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
639 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
640
641 return NO_ERROR;
642}
643
644float AudioFlinger::masterVolume() const
645{
646 return mMasterVolume;
647}
648
649bool AudioFlinger::masterMute() const
650{
651 return mMasterMute;
652}
653
654status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
655{
656 // check calling permissions
657 if (!settingsAllowed()) {
658 return PERMISSION_DENIED;
659 }
660
Dima Zavinfce7a472011-04-19 22:30:36 -0700661 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 return BAD_VALUE;
663 }
664
665 AutoMutex lock(mLock);
666 PlaybackThread *thread = NULL;
667 if (output) {
668 thread = checkPlaybackThread_l(output);
669 if (thread == NULL) {
670 return BAD_VALUE;
671 }
672 }
673
674 mStreamTypes[stream].volume = value;
675
676 if (thread == NULL) {
677 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
678 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
679 }
680 } else {
681 thread->setStreamVolume(stream, value);
682 }
683
684 return NO_ERROR;
685}
686
687status_t AudioFlinger::setStreamMute(int stream, bool muted)
688{
689 // check calling permissions
690 if (!settingsAllowed()) {
691 return PERMISSION_DENIED;
692 }
693
Dima Zavinfce7a472011-04-19 22:30:36 -0700694 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
695 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 return BAD_VALUE;
697 }
698
Eric Laurent93575202011-01-18 18:39:02 -0800699 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700 mStreamTypes[stream].mute = muted;
701 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
702 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
703
704 return NO_ERROR;
705}
706
707float AudioFlinger::streamVolume(int stream, int output) const
708{
Dima Zavinfce7a472011-04-19 22:30:36 -0700709 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 return 0.0f;
711 }
712
713 AutoMutex lock(mLock);
714 float volume;
715 if (output) {
716 PlaybackThread *thread = checkPlaybackThread_l(output);
717 if (thread == NULL) {
718 return 0.0f;
719 }
720 volume = thread->streamVolume(stream);
721 } else {
722 volume = mStreamTypes[stream].volume;
723 }
724
725 return volume;
726}
727
728bool AudioFlinger::streamMute(int stream) const
729{
Dima Zavinfce7a472011-04-19 22:30:36 -0700730 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 return true;
732 }
733
734 return mStreamTypes[stream].mute;
735}
736
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
738{
739 status_t result;
740
Steve Block3856b092011-10-20 11:56:00 +0100741 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
743 // check calling permissions
744 if (!settingsAllowed()) {
745 return PERMISSION_DENIED;
746 }
747
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 // ioHandle == 0 means the parameters are global to the audio hardware interface
749 if (ioHandle == 0) {
750 AutoMutex lock(mHardwareLock);
751 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700752 status_t final_result = NO_ERROR;
753 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
754 audio_hw_device_t *dev = mAudioHwDevs[i];
755 result = dev->set_parameters(dev, keyValuePairs.string());
756 final_result = result ?: final_result;
757 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700759 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
760 AudioParameter param = AudioParameter(keyValuePairs);
761 String8 value;
762 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
763 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700764 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
765 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700766 for (size_t i = 0; i < mRecordThreads.size(); i++) {
767 sp<RecordThread> thread = mRecordThreads.valueAt(i);
768 RecordThread::RecordTrack *track = thread->track();
769 if (track != NULL) {
770 audio_devices_t device = (audio_devices_t)(
771 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700772 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700773 thread->setEffectSuspended(FX_IID_AEC,
774 suspend,
775 track->sessionId());
776 thread->setEffectSuspended(FX_IID_NS,
777 suspend,
778 track->sessionId());
779 }
780 }
Eric Laurentbee53372011-08-29 12:42:48 -0700781 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700782 }
783 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700784 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 }
786
787 // hold a strong ref on thread in case closeOutput() or closeInput() is called
788 // and the thread is exited once the lock is released
789 sp<ThreadBase> thread;
790 {
791 Mutex::Autolock _l(mLock);
792 thread = checkPlaybackThread_l(ioHandle);
793 if (thread == NULL) {
794 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700795 } else if (thread.get() == primaryPlaybackThread_l()) {
796 // indicate output device change to all input threads for pre processing
797 AudioParameter param = AudioParameter(keyValuePairs);
798 int value;
799 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
800 for (size_t i = 0; i < mRecordThreads.size(); i++) {
801 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
802 }
803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805 }
806 if (thread != NULL) {
807 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 return result;
809 }
810 return BAD_VALUE;
811}
812
813String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
814{
Steve Block3856b092011-10-20 11:56:00 +0100815// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
817
818 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700819 String8 out_s8;
820
Dima Zavin799a70e2011-04-18 16:57:27 -0700821 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
822 audio_hw_device_t *dev = mAudioHwDevs[i];
823 char *s = dev->get_parameters(dev, keys.string());
824 out_s8 += String8(s);
825 free(s);
826 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700827 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 }
829
830 Mutex::Autolock _l(mLock);
831
832 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
833 if (playbackThread != NULL) {
834 return playbackThread->getParameters(keys);
835 }
836 RecordThread *recordThread = checkRecordThread_l(ioHandle);
837 if (recordThread != NULL) {
838 return recordThread->getParameters(keys);
839 }
840 return String8("");
841}
842
843size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
844{
Eric Laurenta1884f92011-08-23 08:25:03 -0700845 status_t ret = initCheck();
846 if (ret != NO_ERROR) {
847 return 0;
848 }
849
Dima Zavin799a70e2011-04-18 16:57:27 -0700850 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851}
852
853unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
854{
855 if (ioHandle == 0) {
856 return 0;
857 }
858
859 Mutex::Autolock _l(mLock);
860
861 RecordThread *recordThread = checkRecordThread_l(ioHandle);
862 if (recordThread != NULL) {
863 return recordThread->getInputFramesLost();
864 }
865 return 0;
866}
867
868status_t AudioFlinger::setVoiceVolume(float value)
869{
Eric Laurenta1884f92011-08-23 08:25:03 -0700870 status_t ret = initCheck();
871 if (ret != NO_ERROR) {
872 return ret;
873 }
874
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 // check calling permissions
876 if (!settingsAllowed()) {
877 return PERMISSION_DENIED;
878 }
879
880 AutoMutex lock(mHardwareLock);
881 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700882 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 mHardwareStatus = AUDIO_HW_IDLE;
884
885 return ret;
886}
887
888status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
889{
890 status_t status;
891
892 Mutex::Autolock _l(mLock);
893
894 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
895 if (playbackThread != NULL) {
896 return playbackThread->getRenderPosition(halFrames, dspFrames);
897 }
898
899 return BAD_VALUE;
900}
901
902void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
903{
904
905 Mutex::Autolock _l(mLock);
906
907 int pid = IPCThreadState::self()->getCallingPid();
908 if (mNotificationClients.indexOfKey(pid) < 0) {
909 sp<NotificationClient> notificationClient = new NotificationClient(this,
910 client,
911 pid);
Steve Block3856b092011-10-20 11:56:00 +0100912 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913
914 mNotificationClients.add(pid, notificationClient);
915
916 sp<IBinder> binder = client->asBinder();
917 binder->linkToDeath(notificationClient);
918
919 // the config change is always sent from playback or record threads to avoid deadlock
920 // with AudioSystem::gLock
921 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
922 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
923 }
924
925 for (size_t i = 0; i < mRecordThreads.size(); i++) {
926 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
927 }
928 }
929}
930
931void AudioFlinger::removeNotificationClient(pid_t pid)
932{
933 Mutex::Autolock _l(mLock);
934
935 int index = mNotificationClients.indexOfKey(pid);
936 if (index >= 0) {
937 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100938 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mNotificationClients.removeItem(pid);
940 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700941
Steve Block3856b092011-10-20 11:56:00 +0100942 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700943 int num = mAudioSessionRefs.size();
944 bool removed = false;
945 for (int i = 0; i< num; i++) {
946 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950 mAudioSessionRefs.removeAt(i);
951 delete ref;
952 removed = true;
953 i--;
954 num--;
955 }
956 }
957 if (removed) {
958 purgeStaleEffects_l();
959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960}
961
962// audioConfigChanged_l() must be called with AudioFlinger::mLock held
963void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
964{
965 size_t size = mNotificationClients.size();
966 for (size_t i = 0; i < size; i++) {
967 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
968 }
969}
970
971// removeClient_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::removeClient_l(pid_t pid)
973{
Steve Block3856b092011-10-20 11:56:00 +0100974 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 mClients.removeItem(pid);
976}
977
978
979// ----------------------------------------------------------------------------
980
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700981AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 : Thread(false),
983 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700984 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
985 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700987 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988}
989
990AudioFlinger::ThreadBase::~ThreadBase()
991{
992 mParamCond.broadcast();
993 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700994 // do not lock the mutex in destructor
995 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700996 if (mPowerManager != 0) {
997 sp<IBinder> binder = mPowerManager->asBinder();
998 binder->unlinkToDeath(mDeathRecipient);
999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000}
1001
1002void AudioFlinger::ThreadBase::exit()
1003{
1004 // keep a strong ref on ourself so that we wont get
1005 // destroyed in the middle of requestExitAndWait()
1006 sp <ThreadBase> strongMe = this;
1007
Steve Block3856b092011-10-20 11:56:00 +01001008 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 {
1010 AutoMutex lock(&mLock);
1011 mExiting = true;
1012 requestExit();
1013 mWaitWorkCV.signal();
1014 }
1015 requestExitAndWait();
1016}
1017
1018uint32_t AudioFlinger::ThreadBase::sampleRate() const
1019{
1020 return mSampleRate;
1021}
1022
1023int AudioFlinger::ThreadBase::channelCount() const
1024{
1025 return (int)mChannelCount;
1026}
1027
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001028uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029{
1030 return mFormat;
1031}
1032
1033size_t AudioFlinger::ThreadBase::frameCount() const
1034{
1035 return mFrameCount;
1036}
1037
1038status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1039{
1040 status_t status;
1041
Steve Block3856b092011-10-20 11:56:00 +01001042 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 Mutex::Autolock _l(mLock);
1044
1045 mNewParameters.add(keyValuePairs);
1046 mWaitWorkCV.signal();
1047 // wait condition with timeout in case the thread loop has exited
1048 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001049 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050 status = mParamStatus;
1051 mWaitWorkCV.signal();
1052 } else {
1053 status = TIMED_OUT;
1054 }
1055 return status;
1056}
1057
1058void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1059{
1060 Mutex::Autolock _l(mLock);
1061 sendConfigEvent_l(event, param);
1062}
1063
1064// sendConfigEvent_l() must be called with ThreadBase::mLock held
1065void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1066{
1067 ConfigEvent *configEvent = new ConfigEvent();
1068 configEvent->mEvent = event;
1069 configEvent->mParam = param;
1070 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 mWaitWorkCV.signal();
1073}
1074
1075void AudioFlinger::ThreadBase::processConfigEvents()
1076{
1077 mLock.lock();
1078 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 ConfigEvent *configEvent = mConfigEvents[0];
1081 mConfigEvents.removeAt(0);
1082 // release mLock before locking AudioFlinger mLock: lock order is always
1083 // AudioFlinger then ThreadBase to avoid cross deadlock
1084 mLock.unlock();
1085 mAudioFlinger->mLock.lock();
1086 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1087 mAudioFlinger->mLock.unlock();
1088 delete configEvent;
1089 mLock.lock();
1090 }
1091 mLock.unlock();
1092}
1093
1094status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1095{
1096 const size_t SIZE = 256;
1097 char buffer[SIZE];
1098 String8 result;
1099
1100 bool locked = tryLock(mLock);
1101 if (!locked) {
1102 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1103 write(fd, buffer, strlen(buffer));
1104 }
1105
1106 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1113 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001114 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1115 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1117 result.append(buffer);
1118 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1119 result.append(buffer);
1120
1121 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1122 result.append(buffer);
1123 result.append(" Index Command");
1124 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1125 snprintf(buffer, SIZE, "\n %02d ", i);
1126 result.append(buffer);
1127 result.append(mNewParameters[i]);
1128 }
1129
1130 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, " Index event param\n");
1133 result.append(buffer);
1134 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1135 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1136 result.append(buffer);
1137 }
1138 result.append("\n");
1139
1140 write(fd, result.string(), result.size());
1141
1142 if (locked) {
1143 mLock.unlock();
1144 }
1145 return NO_ERROR;
1146}
1147
Eric Laurent1d2bff02011-07-24 17:49:51 -07001148status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1149{
1150 const size_t SIZE = 256;
1151 char buffer[SIZE];
1152 String8 result;
1153
1154 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1155 write(fd, buffer, strlen(buffer));
1156
1157 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1158 sp<EffectChain> chain = mEffectChains[i];
1159 if (chain != 0) {
1160 chain->dump(fd, args);
1161 }
1162 }
1163 return NO_ERROR;
1164}
1165
Eric Laurentfeb0db62011-07-22 09:04:31 -07001166void AudioFlinger::ThreadBase::acquireWakeLock()
1167{
1168 Mutex::Autolock _l(mLock);
1169 acquireWakeLock_l();
1170}
1171
1172void AudioFlinger::ThreadBase::acquireWakeLock_l()
1173{
1174 if (mPowerManager == 0) {
1175 // use checkService() to avoid blocking if power service is not up yet
1176 sp<IBinder> binder =
1177 defaultServiceManager()->checkService(String16("power"));
1178 if (binder == 0) {
1179 LOGW("Thread %s cannot connect to the power manager service", mName);
1180 } else {
1181 mPowerManager = interface_cast<IPowerManager>(binder);
1182 binder->linkToDeath(mDeathRecipient);
1183 }
1184 }
1185 if (mPowerManager != 0) {
1186 sp<IBinder> binder = new BBinder();
1187 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1188 binder,
1189 String16(mName));
1190 if (status == NO_ERROR) {
1191 mWakeLockToken = binder;
1192 }
Steve Block3856b092011-10-20 11:56:00 +01001193 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001194 }
1195}
1196
1197void AudioFlinger::ThreadBase::releaseWakeLock()
1198{
1199 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001200 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001201}
1202
1203void AudioFlinger::ThreadBase::releaseWakeLock_l()
1204{
1205 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001207 if (mPowerManager != 0) {
1208 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1209 }
1210 mWakeLockToken.clear();
1211 }
1212}
1213
1214void AudioFlinger::ThreadBase::clearPowerManager()
1215{
1216 Mutex::Autolock _l(mLock);
1217 releaseWakeLock_l();
1218 mPowerManager.clear();
1219}
1220
1221void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1222{
1223 sp<ThreadBase> thread = mThread.promote();
1224 if (thread != 0) {
1225 thread->clearPowerManager();
1226 }
1227 LOGW("power manager service died !!!");
1228}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001229
Eric Laurent59255e42011-07-27 19:49:51 -07001230void AudioFlinger::ThreadBase::setEffectSuspended(
1231 const effect_uuid_t *type, bool suspend, int sessionId)
1232{
1233 Mutex::Autolock _l(mLock);
1234 setEffectSuspended_l(type, suspend, sessionId);
1235}
1236
1237void AudioFlinger::ThreadBase::setEffectSuspended_l(
1238 const effect_uuid_t *type, bool suspend, int sessionId)
1239{
1240 sp<EffectChain> chain;
1241 chain = getEffectChain_l(sessionId);
1242 if (chain != 0) {
1243 if (type != NULL) {
1244 chain->setEffectSuspended_l(type, suspend);
1245 } else {
1246 chain->setEffectSuspendedAll_l(suspend);
1247 }
1248 }
1249
1250 updateSuspendedSessions_l(type, suspend, sessionId);
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1254{
1255 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1256 if (index < 0) {
1257 return;
1258 }
1259
1260 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1261 mSuspendedSessions.editValueAt(index);
1262
1263 for (size_t i = 0; i < sessionEffects.size(); i++) {
1264 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1265 for (int j = 0; j < desc->mRefCount; j++) {
1266 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1267 chain->setEffectSuspendedAll_l(true);
1268 } else {
Steve Block3856b092011-10-20 11:56:00 +01001269 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001270 desc->mType.timeLow);
1271 chain->setEffectSuspended_l(&desc->mType, true);
1272 }
1273 }
1274 }
1275}
1276
Eric Laurent59255e42011-07-27 19:49:51 -07001277void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1278 bool suspend,
1279 int sessionId)
1280{
1281 int index = mSuspendedSessions.indexOfKey(sessionId);
1282
1283 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1284
1285 if (suspend) {
1286 if (index >= 0) {
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 } else {
1289 mSuspendedSessions.add(sessionId, sessionEffects);
1290 }
1291 } else {
1292 if (index < 0) {
1293 return;
1294 }
1295 sessionEffects = mSuspendedSessions.editValueAt(index);
1296 }
1297
1298
1299 int key = EffectChain::kKeyForSuspendAll;
1300 if (type != NULL) {
1301 key = type->timeLow;
1302 }
1303 index = sessionEffects.indexOfKey(key);
1304
1305 sp <SuspendedSessionDesc> desc;
1306 if (suspend) {
1307 if (index >= 0) {
1308 desc = sessionEffects.valueAt(index);
1309 } else {
1310 desc = new SuspendedSessionDesc();
1311 if (type != NULL) {
1312 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1313 }
1314 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001316 }
1317 desc->mRefCount++;
1318 } else {
1319 if (index < 0) {
1320 return;
1321 }
1322 desc = sessionEffects.valueAt(index);
1323 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001324 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001325 sessionEffects.removeItemsAt(index);
1326 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001328 sessionId);
1329 mSuspendedSessions.removeItem(sessionId);
1330 }
1331 }
1332 }
1333 if (!sessionEffects.isEmpty()) {
1334 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1335 }
1336}
1337
1338void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1339 bool enabled,
1340 int sessionId)
1341{
1342 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001343 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1344}
Eric Laurent59255e42011-07-27 19:49:51 -07001345
Eric Laurenta85a74a2011-10-19 11:44:54 -07001346void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1347 bool enabled,
1348 int sessionId)
1349{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001350 if (mType != RECORD) {
1351 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1352 // another session. This gives the priority to well behaved effect control panels
1353 // and applications not using global effects.
1354 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1355 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1356 }
1357 }
Eric Laurent59255e42011-07-27 19:49:51 -07001358
1359 sp<EffectChain> chain = getEffectChain_l(sessionId);
1360 if (chain != 0) {
1361 chain->checkSuspendOnEffectEnabled(effect, enabled);
1362 }
1363}
1364
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365// ----------------------------------------------------------------------------
1366
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001367AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1368 AudioStreamOut* output,
1369 int id,
1370 uint32_t device)
1371 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001373 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001375 snprintf(mName, kNameLength, "AudioOut_%d", id);
1376
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 readOutputParameters();
1378
1379 mMasterVolume = mAudioFlinger->masterVolume();
1380 mMasterMute = mAudioFlinger->masterMute();
1381
Dima Zavinfce7a472011-04-19 22:30:36 -07001382 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1384 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001385 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 }
1387}
1388
1389AudioFlinger::PlaybackThread::~PlaybackThread()
1390{
1391 delete [] mMixBuffer;
1392}
1393
1394status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1395{
1396 dumpInternals(fd, args);
1397 dumpTracks(fd, args);
1398 dumpEffectChains(fd, args);
1399 return NO_ERROR;
1400}
1401
1402status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1403{
1404 const size_t SIZE = 256;
1405 char buffer[SIZE];
1406 String8 result;
1407
1408 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1409 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001410 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 -07001411 for (size_t i = 0; i < mTracks.size(); ++i) {
1412 sp<Track> track = mTracks[i];
1413 if (track != 0) {
1414 track->dump(buffer, SIZE);
1415 result.append(buffer);
1416 }
1417 }
1418
1419 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1420 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001421 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 -07001422 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1423 wp<Track> wTrack = mActiveTracks[i];
1424 if (wTrack != 0) {
1425 sp<Track> track = wTrack.promote();
1426 if (track != 0) {
1427 track->dump(buffer, SIZE);
1428 result.append(buffer);
1429 }
1430 }
1431 }
1432 write(fd, result.string(), result.size());
1433 return NO_ERROR;
1434}
1435
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1437{
1438 const size_t SIZE = 256;
1439 char buffer[SIZE];
1440 String8 result;
1441
1442 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1455 result.append(buffer);
1456 write(fd, result.string(), result.size());
1457
1458 dumpBase(fd, args);
1459
1460 return NO_ERROR;
1461}
1462
1463// Thread virtuals
1464status_t AudioFlinger::PlaybackThread::readyToRun()
1465{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001466 status_t status = initCheck();
1467 if (status == NO_ERROR) {
1468 LOGI("AudioFlinger's thread %p ready to run", this);
1469 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001472 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473}
1474
1475void AudioFlinger::PlaybackThread::onFirstRef()
1476{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001477 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478}
1479
1480// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1481sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1482 const sp<AudioFlinger::Client>& client,
1483 int streamType,
1484 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001485 uint32_t format,
1486 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 int frameCount,
1488 const sp<IMemory>& sharedBuffer,
1489 int sessionId,
1490 status_t *status)
1491{
1492 sp<Track> track;
1493 status_t lStatus;
1494
1495 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001496 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1497 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1498 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1499 "for output %p with format %d",
1500 sampleRate, format, channelMask, mOutput, mFormat);
1501 lStatus = BAD_VALUE;
1502 goto Exit;
1503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 }
1505 } else {
1506 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1507 if (sampleRate > mSampleRate*2) {
1508 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1509 lStatus = BAD_VALUE;
1510 goto Exit;
1511 }
1512 }
1513
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001514 lStatus = initCheck();
1515 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 goto Exit;
1518 }
1519
1520 { // scope for mLock
1521 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001522
1523 // all tracks in same audio session must share the same routing strategy otherwise
1524 // conflicts will happen when tracks are moved from one output to another by audio policy
1525 // manager
1526 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001527 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001528 for (size_t i = 0; i < mTracks.size(); ++i) {
1529 sp<Track> t = mTracks[i];
1530 if (t != 0) {
1531 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001532 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536 }
1537 }
1538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001540 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 if (track->getCblk() == NULL || track->name() < 0) {
1542 lStatus = NO_MEMORY;
1543 goto Exit;
1544 }
1545 mTracks.add(track);
1546
1547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001549 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001551 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001552 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001554
1555 // invalidate track immediately if the stream type was moved to another thread since
1556 // createTrack() was called by the client process.
1557 if (!mStreamTypes[streamType].valid) {
1558 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1559 this, streamType);
1560 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1561 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 }
1563 lStatus = NO_ERROR;
1564
1565Exit:
1566 if(status) {
1567 *status = lStatus;
1568 }
1569 return track;
1570}
1571
1572uint32_t AudioFlinger::PlaybackThread::latency() const
1573{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001574 Mutex::Autolock _l(mLock);
1575 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001576 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001577 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 return 0;
1579 }
1580}
1581
1582status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1583{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 mMasterVolume = value;
1585 return NO_ERROR;
1586}
1587
1588status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 mMasterMute = muted;
1591 return NO_ERROR;
1592}
1593
1594float AudioFlinger::PlaybackThread::masterVolume() const
1595{
1596 return mMasterVolume;
1597}
1598
1599bool AudioFlinger::PlaybackThread::masterMute() const
1600{
1601 return mMasterMute;
1602}
1603
1604status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1605{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 mStreamTypes[stream].volume = value;
1607 return NO_ERROR;
1608}
1609
1610status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1611{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 mStreamTypes[stream].mute = muted;
1613 return NO_ERROR;
1614}
1615
1616float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1617{
1618 return mStreamTypes[stream].volume;
1619}
1620
1621bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1622{
1623 return mStreamTypes[stream].mute;
1624}
1625
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626// addTrack_l() must be called with ThreadBase::mLock held
1627status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1628{
1629 status_t status = ALREADY_EXISTS;
1630
1631 // set retry count for buffer fill
1632 track->mRetryCount = kMaxTrackStartupRetries;
1633 if (mActiveTracks.indexOf(track) < 0) {
1634 // the track is newly added, make sure it fills up all its
1635 // buffers before playing. This is to ensure the client will
1636 // effectively get the latency it requested.
1637 track->mFillingUpStatus = Track::FS_FILLING;
1638 track->mResetDone = false;
1639 mActiveTracks.add(track);
1640 if (track->mainBuffer() != mMixBuffer) {
1641 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1642 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001643 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001644 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 }
1646 }
1647
1648 status = NO_ERROR;
1649 }
1650
Steve Block3856b092011-10-20 11:56:00 +01001651 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 mWaitWorkCV.broadcast();
1653
1654 return status;
1655}
1656
1657// destroyTrack_l() must be called with ThreadBase::mLock held
1658void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1659{
1660 track->mState = TrackBase::TERMINATED;
1661 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001662 removeTrack_l(track);
1663 }
1664}
1665
1666void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1667{
1668 mTracks.remove(track);
1669 deleteTrackName_l(track->name());
1670 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1671 if (chain != 0) {
1672 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 }
1674}
1675
1676String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1677{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001678 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001679 char *s;
1680
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681 Mutex::Autolock _l(mLock);
1682 if (initCheck() != NO_ERROR) {
1683 return out_s8;
1684 }
1685
Dima Zavin799a70e2011-04-18 16:57:27 -07001686 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001687 out_s8 = String8(s);
1688 free(s);
1689 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690}
1691
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001692// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1694 AudioSystem::OutputDescriptor desc;
1695 void *param2 = 0;
1696
Steve Block3856b092011-10-20 11:56:00 +01001697 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698
1699 switch (event) {
1700 case AudioSystem::OUTPUT_OPENED:
1701 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001702 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 desc.samplingRate = mSampleRate;
1704 desc.format = mFormat;
1705 desc.frameCount = mFrameCount;
1706 desc.latency = latency();
1707 param2 = &desc;
1708 break;
1709
1710 case AudioSystem::STREAM_CONFIG_CHANGED:
1711 param2 = &param;
1712 case AudioSystem::OUTPUT_CLOSED:
1713 default:
1714 break;
1715 }
1716 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1717}
1718
1719void AudioFlinger::PlaybackThread::readOutputParameters()
1720{
Dima Zavin799a70e2011-04-18 16:57:27 -07001721 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001722 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1723 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001724 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1725 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1726 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727
1728 // FIXME - Current mixer implementation only supports stereo output: Always
1729 // Allocate a stereo buffer even if HW output is mono.
1730 if (mMixBuffer != NULL) delete[] mMixBuffer;
1731 mMixBuffer = new int16_t[mFrameCount * 2];
1732 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1733
Eric Laurentde070132010-07-13 04:45:46 -07001734 // force reconfiguration of effect chains and engines to take new buffer size and audio
1735 // parameters into account
1736 // Note that mLock is not held when readOutputParameters() is called from the constructor
1737 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1738 // matter.
1739 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1740 Vector< sp<EffectChain> > effectChains = mEffectChains;
1741 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001742 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744}
1745
1746status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1747{
1748 if (halFrames == 0 || dspFrames == 0) {
1749 return BAD_VALUE;
1750 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001751 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001752 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 return INVALID_OPERATION;
1754 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001755 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756
Dima Zavin799a70e2011-04-18 16:57:27 -07001757 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758}
1759
Eric Laurent39e94f82010-07-28 01:32:47 -07001760uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761{
1762 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001763 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001765 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 }
1767
1768 for (size_t i = 0; i < mTracks.size(); ++i) {
1769 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001770 if (sessionId == track->sessionId() &&
1771 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001772 result |= TRACK_SESSION;
1773 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774 }
1775 }
1776
Eric Laurent39e94f82010-07-28 01:32:47 -07001777 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778}
1779
Eric Laurentde070132010-07-13 04:45:46 -07001780uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1781{
Dima Zavinfce7a472011-04-19 22:30:36 -07001782 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001783 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001784 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1785 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001786 }
1787 for (size_t i = 0; i < mTracks.size(); i++) {
1788 sp<Track> track = mTracks[i];
1789 if (sessionId == track->sessionId() &&
1790 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001791 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001792 }
1793 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001794 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001795}
1796
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001798AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1799{
1800 Mutex::Autolock _l(mLock);
1801 return mOutput;
1802}
1803
1804AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1805{
1806 Mutex::Autolock _l(mLock);
1807 AudioStreamOut *output = mOutput;
1808 mOutput = NULL;
1809 return output;
1810}
1811
1812// this method must always be called either with ThreadBase mLock held or inside the thread loop
1813audio_stream_t* AudioFlinger::PlaybackThread::stream()
1814{
1815 if (mOutput == NULL) {
1816 return NULL;
1817 }
1818 return &mOutput->stream->common;
1819}
1820
Eric Laurent162b40b2011-12-05 09:47:19 -08001821uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1822{
1823 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1824 // decoding and transfer time. So sleeping for half of the latency would likely cause
1825 // underruns
1826 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1827 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1828 } else {
1829 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1830 }
1831}
1832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833// ----------------------------------------------------------------------------
1834
Dima Zavin799a70e2011-04-18 16:57:27 -07001835AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 : PlaybackThread(audioFlinger, output, id, device),
1837 mAudioMixer(0)
1838{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001839 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1841
1842 // FIXME - Current mixer implementation only supports stereo output
1843 if (mChannelCount == 1) {
1844 LOGE("Invalid audio hardware channel count");
1845 }
1846}
1847
1848AudioFlinger::MixerThread::~MixerThread()
1849{
1850 delete mAudioMixer;
1851}
1852
1853bool AudioFlinger::MixerThread::threadLoop()
1854{
1855 Vector< sp<Track> > tracksToRemove;
1856 uint32_t mixerStatus = MIXER_IDLE;
1857 nsecs_t standbyTime = systemTime();
1858 size_t mixBufferSize = mFrameCount * mFrameSize;
1859 // FIXME: Relaxed timing because of a certain device that can't meet latency
1860 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001861 // increase threshold again due to low power audio mode. The way this warning threshold is
1862 // calculated and its usefulness should be reconsidered anyway.
1863 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 nsecs_t lastWarning = 0;
1865 bool longStandbyExit = false;
1866 uint32_t activeSleepTime = activeSleepTimeUs();
1867 uint32_t idleSleepTime = idleSleepTimeUs();
1868 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001869 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001871#ifdef DEBUG_CPU_USAGE
1872 ThreadCpuUsage cpu;
1873 const CentralTendencyStatistics& stats = cpu.statistics();
1874#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875
Eric Laurentfeb0db62011-07-22 09:04:31 -07001876 acquireWakeLock();
1877
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 while (!exitPending())
1879 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001880#ifdef DEBUG_CPU_USAGE
1881 cpu.sampleAndEnable();
1882 unsigned n = stats.n();
1883 // cpu.elapsed() is expensive, so don't call it every loop
1884 if ((n & 127) == 1) {
1885 long long elapsed = cpu.elapsed();
1886 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1887 double perLoop = elapsed / (double) n;
1888 double perLoop100 = perLoop * 0.01;
1889 double mean = stats.mean();
1890 double stddev = stats.stddev();
1891 double minimum = stats.minimum();
1892 double maximum = stats.maximum();
1893 cpu.resetStatistics();
1894 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",
1895 elapsed * .000000001, n, perLoop * .000001,
1896 mean * .001,
1897 stddev * .001,
1898 minimum * .001,
1899 maximum * .001,
1900 mean / perLoop100,
1901 stddev / perLoop100,
1902 minimum / perLoop100,
1903 maximum / perLoop100);
1904 }
1905 }
1906#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 processConfigEvents();
1908
1909 mixerStatus = MIXER_IDLE;
1910 { // scope for mLock
1911
1912 Mutex::Autolock _l(mLock);
1913
1914 if (checkForNewParameters_l()) {
1915 mixBufferSize = mFrameCount * mFrameSize;
1916 // FIXME: Relaxed timing because of a certain device that can't meet latency
1917 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001918 // increase threshold again due to low power audio mode. The way this warning
1919 // threshold is calculated and its usefulness should be reconsidered anyway.
1920 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 activeSleepTime = activeSleepTimeUs();
1922 idleSleepTime = idleSleepTimeUs();
1923 }
1924
1925 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1926
1927 // put audio hardware into standby after short delay
1928 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1929 mSuspended) {
1930 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001931 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001932 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 mStandby = true;
1934 mBytesWritten = 0;
1935 }
1936
1937 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1938 // we're about to wait, flush the binder command buffer
1939 IPCThreadState::self()->flushCommands();
1940
1941 if (exitPending()) break;
1942
Eric Laurentfeb0db62011-07-22 09:04:31 -07001943 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001945 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001947 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001948 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949
1950 if (mMasterMute == false) {
1951 char value[PROPERTY_VALUE_MAX];
1952 property_get("ro.audio.silent", value, "0");
1953 if (atoi(value)) {
1954 LOGD("Silence is golden");
1955 setMasterMute(true);
1956 }
1957 }
1958
1959 standbyTime = systemTime() + kStandbyTimeInNsecs;
1960 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001961 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 continue;
1963 }
1964 }
1965
1966 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1967
1968 // prevent any changes in effect chain list and in each effect chain
1969 // during mixing and effect process as the audio buffers could be deleted
1970 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001971 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973
1974 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1975 // mix buffers...
1976 mAudioMixer->process();
1977 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001978 // increase sleep time progressively when application underrun condition clears
1979 if (sleepTimeShift > 0) {
1980 sleepTimeShift--;
1981 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 standbyTime = systemTime() + kStandbyTimeInNsecs;
1983 //TODO: delay standby when effects have a tail
1984 } else {
1985 // If no tracks are ready, sleep once for the duration of an output
1986 // buffer size, then write 0s to the output
1987 if (sleepTime == 0) {
1988 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001989 sleepTime = activeSleepTime >> sleepTimeShift;
1990 if (sleepTime < kMinThreadSleepTimeUs) {
1991 sleepTime = kMinThreadSleepTimeUs;
1992 }
1993 // reduce sleep time in case of consecutive application underruns to avoid
1994 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1995 // duration we would end up writing less data than needed by the audio HAL if
1996 // the condition persists.
1997 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1998 sleepTimeShift++;
1999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 } else {
2001 sleepTime = idleSleepTime;
2002 }
2003 } else if (mBytesWritten != 0 ||
2004 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2005 memset (mMixBuffer, 0, mixBufferSize);
2006 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002007 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 }
2009 // TODO add standby time extension fct of effect tail
2010 }
2011
2012 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002013 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 }
2015 // sleepTime == 0 means we must write to audio hardware
2016 if (sleepTime == 0) {
2017 for (size_t i = 0; i < effectChains.size(); i ++) {
2018 effectChains[i]->process_l();
2019 }
2020 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002021 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 mLastWriteTime = systemTime();
2023 mInWrite = true;
2024 mBytesWritten += mixBufferSize;
2025
Dima Zavin799a70e2011-04-18 16:57:27 -07002026 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2028 mNumWrites++;
2029 mInWrite = false;
2030 nsecs_t now = systemTime();
2031 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002032 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 mNumDelayedWrites++;
2034 if ((now - lastWarning) > kWarningThrottle) {
2035 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2036 ns2ms(delta), mNumDelayedWrites, this);
2037 lastWarning = now;
2038 }
2039 if (mStandby) {
2040 longStandbyExit = true;
2041 }
2042 }
2043 mStandby = false;
2044 } else {
2045 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002046 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 usleep(sleepTime);
2048 }
2049
2050 // finally let go of all our tracks, without the lock held
2051 // since we can't guarantee the destructors won't acquire that
2052 // same lock.
2053 tracksToRemove.clear();
2054
2055 // Effect chains will be actually deleted here if they were removed from
2056 // mEffectChains list during mixing or effects processing
2057 effectChains.clear();
2058 }
2059
2060 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 }
2063
Eric Laurentfeb0db62011-07-22 09:04:31 -07002064 releaseWakeLock();
2065
Steve Block3856b092011-10-20 11:56:00 +01002066 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 return false;
2068}
2069
2070// prepareTracks_l() must be called with ThreadBase::mLock held
2071uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2072{
2073
2074 uint32_t mixerStatus = MIXER_IDLE;
2075 // find out which tracks need to be processed
2076 size_t count = activeTracks.size();
2077 size_t mixedTracks = 0;
2078 size_t tracksWithEffect = 0;
2079
2080 float masterVolume = mMasterVolume;
2081 bool masterMute = mMasterMute;
2082
Eric Laurent571d49c2010-08-11 05:20:11 -07002083 if (masterMute) {
2084 masterVolume = 0;
2085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002087 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002089 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002090 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 masterVolume = (float)((v + (1 << 23)) >> 24);
2092 chain.clear();
2093 }
2094
2095 for (size_t i=0 ; i<count ; i++) {
2096 sp<Track> t = activeTracks[i].promote();
2097 if (t == 0) continue;
2098
2099 Track* const track = t.get();
2100 audio_track_cblk_t* cblk = track->cblk();
2101
2102 // The first time a track is added we wait
2103 // for all its buffers to be filled before processing it
2104 mAudioMixer->setActiveTrack(track->name());
Eric Laurenta47b69c2011-11-08 18:10:16 -08002105 // make sure that we have enough frames to mix one full buffer.
2106 // enforce this condition only once to enable draining the buffer in case the client
2107 // app does not call stop() and relies on underrun to stop:
2108 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2109 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002110 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002111 if (!track->isStopped() && !track->isPausing() &&
2112 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002113 if (t->sampleRate() == (int)mSampleRate) {
2114 minFrames = mFrameCount;
2115 } else {
2116 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2117 }
2118 }
2119 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 !track->isPaused() && !track->isTerminated())
2121 {
Steve Block3856b092011-10-20 11:56:00 +01002122 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123
2124 mixedTracks++;
2125
2126 // track->mainBuffer() != mMixBuffer means there is an effect chain
2127 // connected to the track
2128 chain.clear();
2129 if (track->mainBuffer() != mMixBuffer) {
2130 chain = getEffectChain_l(track->sessionId());
2131 // Delegate volume control to effect in track effect chain if needed
2132 if (chain != 0) {
2133 tracksWithEffect++;
2134 } else {
2135 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2136 track->name(), track->sessionId());
2137 }
2138 }
2139
2140
2141 int param = AudioMixer::VOLUME;
2142 if (track->mFillingUpStatus == Track::FS_FILLED) {
2143 // no ramp for the first volume setting
2144 track->mFillingUpStatus = Track::FS_ACTIVE;
2145 if (track->mState == TrackBase::RESUMING) {
2146 track->mState = TrackBase::ACTIVE;
2147 param = AudioMixer::RAMP_VOLUME;
2148 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002149 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 } else if (cblk->server != 0) {
2151 // If the track is stopped before the first frame was mixed,
2152 // do not apply ramp
2153 param = AudioMixer::RAMP_VOLUME;
2154 }
2155
2156 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002157 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002158 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002160 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 if (track->isPausing()) {
2162 track->setPaused();
2163 }
2164 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002165
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 // read original volumes with volume control
2167 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002169 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2170 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171
Eric Laurente0aed6d2010-09-10 17:44:44 -07002172 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002174 // Delegate volume control to effect in track effect chain if needed
2175 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2176 // Do not ramp volume if volume is controlled by effect
2177 param = AudioMixer::VOLUME;
2178 track->mHasVolumeController = true;
2179 } else {
2180 // force no volume ramp when volume controller was just disabled or removed
2181 // from effect chain to avoid volume spike
2182 if (track->mHasVolumeController) {
2183 param = AudioMixer::VOLUME;
2184 }
2185 track->mHasVolumeController = false;
2186 }
2187
2188 // Convert volumes from 8.24 to 4.12 format
2189 int16_t left, right, aux;
2190 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2191 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2192 left = int16_t(v_clamped);
2193 v_clamped = (vr + (1 << 11)) >> 12;
2194 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2195 right = int16_t(v_clamped);
2196
2197 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2198 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 // XXX: these things DON'T need to be done each time
2201 mAudioMixer->setBufferProvider(track);
2202 mAudioMixer->enable(AudioMixer::MIXING);
2203
2204 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2205 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2206 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2207 mAudioMixer->setParameter(
2208 AudioMixer::TRACK,
2209 AudioMixer::FORMAT, (void *)track->format());
2210 mAudioMixer->setParameter(
2211 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002212 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213 mAudioMixer->setParameter(
2214 AudioMixer::RESAMPLE,
2215 AudioMixer::SAMPLE_RATE,
2216 (void *)(cblk->sampleRate));
2217 mAudioMixer->setParameter(
2218 AudioMixer::TRACK,
2219 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2220 mAudioMixer->setParameter(
2221 AudioMixer::TRACK,
2222 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2223
2224 // reset retry count
2225 track->mRetryCount = kMaxTrackRetries;
2226 mixerStatus = MIXER_TRACKS_READY;
2227 } else {
Steve Block3856b092011-10-20 11:56:00 +01002228 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 if (track->isStopped()) {
2230 track->reset();
2231 }
2232 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2233 // We have consumed all the buffers of this track.
2234 // Remove it from the list of active tracks.
2235 tracksToRemove->add(track);
2236 } else {
2237 // No buffers for this track. Give it a few chances to
2238 // fill a buffer, then remove it from active list.
2239 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002240 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002242 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002243 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 } else if (mixerStatus != MIXER_TRACKS_READY) {
2245 mixerStatus = MIXER_TRACKS_ENABLED;
2246 }
2247 }
2248 mAudioMixer->disable(AudioMixer::MIXING);
2249 }
2250 }
2251
2252 // remove all the tracks that need to be...
2253 count = tracksToRemove->size();
2254 if (UNLIKELY(count)) {
2255 for (size_t i=0 ; i<count ; i++) {
2256 const sp<Track>& track = tracksToRemove->itemAt(i);
2257 mActiveTracks.remove(track);
2258 if (track->mainBuffer() != mMixBuffer) {
2259 chain = getEffectChain_l(track->sessionId());
2260 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002261 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002262 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 }
2264 }
2265 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002266 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 }
2268 }
2269 }
2270
2271 // mix buffer must be cleared if all tracks are connected to an
2272 // effect chain as in this case the mixer will not write to
2273 // mix buffer and track effects will accumulate into it
2274 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2275 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2276 }
2277
2278 return mixerStatus;
2279}
2280
2281void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2282{
Steve Block3856b092011-10-20 11:56:00 +01002283 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002284 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002286
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 size_t size = mTracks.size();
2288 for (size_t i = 0; i < size; i++) {
2289 sp<Track> t = mTracks[i];
2290 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002291 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 }
2294 }
2295}
2296
Eric Laurent9f6530f2011-08-30 10:18:54 -07002297void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2298{
Steve Block3856b092011-10-20 11:56:00 +01002299 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002300 this, streamType, valid);
2301 Mutex::Autolock _l(mLock);
2302
2303 mStreamTypes[streamType].valid = valid;
2304}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305
2306// getTrackName_l() must be called with ThreadBase::mLock held
2307int AudioFlinger::MixerThread::getTrackName_l()
2308{
2309 return mAudioMixer->getTrackName();
2310}
2311
2312// deleteTrackName_l() must be called with ThreadBase::mLock held
2313void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2314{
Steve Block3856b092011-10-20 11:56:00 +01002315 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 mAudioMixer->deleteTrackName(name);
2317}
2318
2319// checkForNewParameters_l() must be called with ThreadBase::mLock held
2320bool AudioFlinger::MixerThread::checkForNewParameters_l()
2321{
2322 bool reconfig = false;
2323
2324 while (!mNewParameters.isEmpty()) {
2325 status_t status = NO_ERROR;
2326 String8 keyValuePair = mNewParameters[0];
2327 AudioParameter param = AudioParameter(keyValuePair);
2328 int value;
2329
2330 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2331 reconfig = true;
2332 }
2333 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002334 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 status = BAD_VALUE;
2336 } else {
2337 reconfig = true;
2338 }
2339 }
2340 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002341 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 status = BAD_VALUE;
2343 } else {
2344 reconfig = true;
2345 }
2346 }
2347 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2348 // do not accept frame count changes if tracks are open as the track buffer
2349 // size depends on frame count and correct behavior would not be garantied
2350 // if frame count is changed after track creation
2351 if (!mTracks.isEmpty()) {
2352 status = INVALID_OPERATION;
2353 } else {
2354 reconfig = true;
2355 }
2356 }
2357 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002358 // when changing the audio output device, call addBatteryData to notify
2359 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002360 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002361 uint32_t params = 0;
2362 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002363 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002364 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2365 }
2366
2367 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002368 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002369 // check if any other device (except speaker) is on
2370 if (value & deviceWithoutSpeaker ) {
2371 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2372 }
2373
2374 if (params != 0) {
2375 addBatteryData(params);
2376 }
2377 }
2378
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 // forward device change to effects that have requested to be
2380 // aware of attached audio device.
2381 mDevice = (uint32_t)value;
2382 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002383 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 }
2385 }
2386
2387 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002388 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002389 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002391 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 mStandby = true;
2393 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002394 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002395 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 }
2397 if (status == NO_ERROR && reconfig) {
2398 delete mAudioMixer;
2399 readOutputParameters();
2400 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2401 for (size_t i = 0; i < mTracks.size() ; i++) {
2402 int name = getTrackName_l();
2403 if (name < 0) break;
2404 mTracks[i]->mName = name;
2405 // limit track sample rate to 2 x new output sample rate
2406 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2407 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2408 }
2409 }
2410 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2411 }
2412 }
2413
2414 mNewParameters.removeAt(0);
2415
2416 mParamStatus = status;
2417 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002418 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2419 // already timed out waiting for the status and will never signal the condition.
2420 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 }
2422 return reconfig;
2423}
2424
2425status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2426{
2427 const size_t SIZE = 256;
2428 char buffer[SIZE];
2429 String8 result;
2430
2431 PlaybackThread::dumpInternals(fd, args);
2432
2433 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2434 result.append(buffer);
2435 write(fd, result.string(), result.size());
2436 return NO_ERROR;
2437}
2438
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2440{
Eric Laurent60e18242010-07-29 06:50:24 -07002441 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442}
2443
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002444uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2445{
2446 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2447}
2448
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002450AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 : PlaybackThread(audioFlinger, output, id, device)
2452{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002453 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454}
2455
2456AudioFlinger::DirectOutputThread::~DirectOutputThread()
2457{
2458}
2459
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460static inline
2461int32_t mul(int16_t in, int16_t v)
2462{
2463#if defined(__arm__) && !defined(__thumb__)
2464 int32_t out;
2465 asm( "smulbb %[out], %[in], %[v] \n"
2466 : [out]"=r"(out)
2467 : [in]"%r"(in), [v]"r"(v)
2468 : );
2469 return out;
2470#else
2471 return in * int32_t(v);
2472#endif
2473}
2474
2475void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2476{
2477 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002478 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002479 return;
2480 }
2481
2482 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002483 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 size_t count = mFrameCount * mChannelCount;
2485 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2486 int16_t *dst = mMixBuffer + count-1;
2487 while(count--) {
2488 *dst-- = (int16_t)(*src--^0x80) << 8;
2489 }
2490 }
2491
2492 size_t frameCount = mFrameCount;
2493 int16_t *out = mMixBuffer;
2494 if (ramp) {
2495 if (mChannelCount == 1) {
2496 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2497 int32_t vlInc = d / (int32_t)frameCount;
2498 int32_t vl = ((int32_t)mLeftVolShort << 16);
2499 do {
2500 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2501 out++;
2502 vl += vlInc;
2503 } while (--frameCount);
2504
2505 } else {
2506 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2507 int32_t vlInc = d / (int32_t)frameCount;
2508 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2509 int32_t vrInc = d / (int32_t)frameCount;
2510 int32_t vl = ((int32_t)mLeftVolShort << 16);
2511 int32_t vr = ((int32_t)mRightVolShort << 16);
2512 do {
2513 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2514 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2515 out += 2;
2516 vl += vlInc;
2517 vr += vrInc;
2518 } while (--frameCount);
2519 }
2520 } else {
2521 if (mChannelCount == 1) {
2522 do {
2523 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2524 out++;
2525 } while (--frameCount);
2526 } else {
2527 do {
2528 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2529 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2530 out += 2;
2531 } while (--frameCount);
2532 }
2533 }
2534
2535 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002536 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002537 size_t count = mFrameCount * mChannelCount;
2538 int16_t *src = mMixBuffer;
2539 uint8_t *dst = (uint8_t *)mMixBuffer;
2540 while(count--) {
2541 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2542 }
2543 }
2544
2545 mLeftVolShort = leftVol;
2546 mRightVolShort = rightVol;
2547}
2548
2549bool AudioFlinger::DirectOutputThread::threadLoop()
2550{
2551 uint32_t mixerStatus = MIXER_IDLE;
2552 sp<Track> trackToRemove;
2553 sp<Track> activeTrack;
2554 nsecs_t standbyTime = systemTime();
2555 int8_t *curBuf;
2556 size_t mixBufferSize = mFrameCount*mFrameSize;
2557 uint32_t activeSleepTime = activeSleepTimeUs();
2558 uint32_t idleSleepTime = idleSleepTimeUs();
2559 uint32_t sleepTime = idleSleepTime;
2560 // use shorter standby delay as on normal output to release
2561 // hardware resources as soon as possible
2562 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2563
Eric Laurentfeb0db62011-07-22 09:04:31 -07002564 acquireWakeLock();
2565
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 while (!exitPending())
2567 {
2568 bool rampVolume;
2569 uint16_t leftVol;
2570 uint16_t rightVol;
2571 Vector< sp<EffectChain> > effectChains;
2572
2573 processConfigEvents();
2574
2575 mixerStatus = MIXER_IDLE;
2576
2577 { // scope for the mLock
2578
2579 Mutex::Autolock _l(mLock);
2580
2581 if (checkForNewParameters_l()) {
2582 mixBufferSize = mFrameCount*mFrameSize;
2583 activeSleepTime = activeSleepTimeUs();
2584 idleSleepTime = idleSleepTimeUs();
2585 standbyDelay = microseconds(activeSleepTime*2);
2586 }
2587
2588 // put audio hardware into standby after short delay
2589 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2590 mSuspended) {
2591 // wait until we have something to do...
2592 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002593 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002594 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002595 mStandby = true;
2596 mBytesWritten = 0;
2597 }
2598
2599 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2600 // we're about to wait, flush the binder command buffer
2601 IPCThreadState::self()->flushCommands();
2602
2603 if (exitPending()) break;
2604
Eric Laurentfeb0db62011-07-22 09:04:31 -07002605 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002606 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002607 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002608 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002609 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002610
2611 if (mMasterMute == false) {
2612 char value[PROPERTY_VALUE_MAX];
2613 property_get("ro.audio.silent", value, "0");
2614 if (atoi(value)) {
2615 LOGD("Silence is golden");
2616 setMasterMute(true);
2617 }
2618 }
2619
2620 standbyTime = systemTime() + standbyDelay;
2621 sleepTime = idleSleepTime;
2622 continue;
2623 }
2624 }
2625
2626 effectChains = mEffectChains;
2627
2628 // find out which tracks need to be processed
2629 if (mActiveTracks.size() != 0) {
2630 sp<Track> t = mActiveTracks[0].promote();
2631 if (t == 0) continue;
2632
2633 Track* const track = t.get();
2634 audio_track_cblk_t* cblk = track->cblk();
2635
2636 // The first time a track is added we wait
2637 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002638 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002639 !track->isPaused() && !track->isTerminated())
2640 {
Steve Block3856b092011-10-20 11:56:00 +01002641 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002642
2643 if (track->mFillingUpStatus == Track::FS_FILLED) {
2644 track->mFillingUpStatus = Track::FS_ACTIVE;
2645 mLeftVolFloat = mRightVolFloat = 0;
2646 mLeftVolShort = mRightVolShort = 0;
2647 if (track->mState == TrackBase::RESUMING) {
2648 track->mState = TrackBase::ACTIVE;
2649 rampVolume = true;
2650 }
2651 } else if (cblk->server != 0) {
2652 // If the track is stopped before the first frame was mixed,
2653 // do not apply ramp
2654 rampVolume = true;
2655 }
2656 // compute volume for this track
2657 float left, right;
2658 if (track->isMuted() || mMasterMute || track->isPausing() ||
2659 mStreamTypes[track->type()].mute) {
2660 left = right = 0;
2661 if (track->isPausing()) {
2662 track->setPaused();
2663 }
2664 } else {
2665 float typeVolume = mStreamTypes[track->type()].volume;
2666 float v = mMasterVolume * typeVolume;
2667 float v_clamped = v * cblk->volume[0];
2668 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2669 left = v_clamped/MAX_GAIN;
2670 v_clamped = v * cblk->volume[1];
2671 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2672 right = v_clamped/MAX_GAIN;
2673 }
2674
2675 if (left != mLeftVolFloat || right != mRightVolFloat) {
2676 mLeftVolFloat = left;
2677 mRightVolFloat = right;
2678
2679 // If audio HAL implements volume control,
2680 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002681 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 left = 1.0f;
2683 right = 1.0f;
2684 }
2685
2686 // Convert volumes from float to 8.24
2687 uint32_t vl = (uint32_t)(left * (1 << 24));
2688 uint32_t vr = (uint32_t)(right * (1 << 24));
2689
2690 // Delegate volume control to effect in track effect chain if needed
2691 // only one effect chain can be present on DirectOutputThread, so if
2692 // there is one, the track is connected to it
2693 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002694 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002695 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 rampVolume = false;
2697 }
2698 }
2699
2700 // Convert volumes from 8.24 to 4.12 format
2701 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2702 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2703 leftVol = (uint16_t)v_clamped;
2704 v_clamped = (vr + (1 << 11)) >> 12;
2705 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2706 rightVol = (uint16_t)v_clamped;
2707 } else {
2708 leftVol = mLeftVolShort;
2709 rightVol = mRightVolShort;
2710 rampVolume = false;
2711 }
2712
2713 // reset retry count
2714 track->mRetryCount = kMaxTrackRetriesDirect;
2715 activeTrack = t;
2716 mixerStatus = MIXER_TRACKS_READY;
2717 } else {
Steve Block3856b092011-10-20 11:56:00 +01002718 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002719 if (track->isStopped()) {
2720 track->reset();
2721 }
2722 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2723 // We have consumed all the buffers of this track.
2724 // Remove it from the list of active tracks.
2725 trackToRemove = track;
2726 } else {
2727 // No buffers for this track. Give it a few chances to
2728 // fill a buffer, then remove it from active list.
2729 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002730 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002731 trackToRemove = track;
2732 } else {
2733 mixerStatus = MIXER_TRACKS_ENABLED;
2734 }
2735 }
2736 }
2737 }
2738
2739 // remove all the tracks that need to be...
2740 if (UNLIKELY(trackToRemove != 0)) {
2741 mActiveTracks.remove(trackToRemove);
2742 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002743 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002744 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002745 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002746 }
2747 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002748 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002749 }
2750 }
2751
Eric Laurentde070132010-07-13 04:45:46 -07002752 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 }
2754
2755 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2756 AudioBufferProvider::Buffer buffer;
2757 size_t frameCount = mFrameCount;
2758 curBuf = (int8_t *)mMixBuffer;
2759 // output audio to hardware
2760 while (frameCount) {
2761 buffer.frameCount = frameCount;
2762 activeTrack->getNextBuffer(&buffer);
2763 if (UNLIKELY(buffer.raw == 0)) {
2764 memset(curBuf, 0, frameCount * mFrameSize);
2765 break;
2766 }
2767 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2768 frameCount -= buffer.frameCount;
2769 curBuf += buffer.frameCount * mFrameSize;
2770 activeTrack->releaseBuffer(&buffer);
2771 }
2772 sleepTime = 0;
2773 standbyTime = systemTime() + standbyDelay;
2774 } else {
2775 if (sleepTime == 0) {
2776 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2777 sleepTime = activeSleepTime;
2778 } else {
2779 sleepTime = idleSleepTime;
2780 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002781 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002782 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2783 sleepTime = 0;
2784 }
2785 }
2786
2787 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002788 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 }
2790 // sleepTime == 0 means we must write to audio hardware
2791 if (sleepTime == 0) {
2792 if (mixerStatus == MIXER_TRACKS_READY) {
2793 applyVolume(leftVol, rightVol, rampVolume);
2794 }
2795 for (size_t i = 0; i < effectChains.size(); i ++) {
2796 effectChains[i]->process_l();
2797 }
Eric Laurentde070132010-07-13 04:45:46 -07002798 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002799
2800 mLastWriteTime = systemTime();
2801 mInWrite = true;
2802 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002803 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002804 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2805 mNumWrites++;
2806 mInWrite = false;
2807 mStandby = false;
2808 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002809 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 usleep(sleepTime);
2811 }
2812
2813 // finally let go of removed track, without the lock held
2814 // since we can't guarantee the destructors won't acquire that
2815 // same lock.
2816 trackToRemove.clear();
2817 activeTrack.clear();
2818
2819 // Effect chains will be actually deleted here if they were removed from
2820 // mEffectChains list during mixing or effects processing
2821 effectChains.clear();
2822 }
2823
2824 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002825 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 }
2827
Eric Laurentfeb0db62011-07-22 09:04:31 -07002828 releaseWakeLock();
2829
Steve Block3856b092011-10-20 11:56:00 +01002830 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002831 return false;
2832}
2833
2834// getTrackName_l() must be called with ThreadBase::mLock held
2835int AudioFlinger::DirectOutputThread::getTrackName_l()
2836{
2837 return 0;
2838}
2839
2840// deleteTrackName_l() must be called with ThreadBase::mLock held
2841void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2842{
2843}
2844
2845// checkForNewParameters_l() must be called with ThreadBase::mLock held
2846bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2847{
2848 bool reconfig = false;
2849
2850 while (!mNewParameters.isEmpty()) {
2851 status_t status = NO_ERROR;
2852 String8 keyValuePair = mNewParameters[0];
2853 AudioParameter param = AudioParameter(keyValuePair);
2854 int value;
2855
2856 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2857 // do not accept frame count changes if tracks are open as the track buffer
2858 // size depends on frame count and correct behavior would not be garantied
2859 // if frame count is changed after track creation
2860 if (!mTracks.isEmpty()) {
2861 status = INVALID_OPERATION;
2862 } else {
2863 reconfig = true;
2864 }
2865 }
2866 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002867 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002868 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002869 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002870 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002871 mStandby = true;
2872 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002873 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002874 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002875 }
2876 if (status == NO_ERROR && reconfig) {
2877 readOutputParameters();
2878 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2879 }
2880 }
2881
2882 mNewParameters.removeAt(0);
2883
2884 mParamStatus = status;
2885 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002886 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2887 // already timed out waiting for the status and will never signal the condition.
2888 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 }
2890 return reconfig;
2891}
2892
2893uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2894{
2895 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002896 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002897 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 } else {
2899 time = 10000;
2900 }
2901 return time;
2902}
2903
2904uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2905{
2906 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002907 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002908 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 } else {
2910 time = 10000;
2911 }
2912 return time;
2913}
2914
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002915uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2916{
2917 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002918 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002919 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2920 } else {
2921 time = 10000;
2922 }
2923 return time;
2924}
2925
2926
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927// ----------------------------------------------------------------------------
2928
2929AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2930 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2931{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002932 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933 addOutputTrack(mainThread);
2934}
2935
2936AudioFlinger::DuplicatingThread::~DuplicatingThread()
2937{
2938 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2939 mOutputTracks[i]->destroy();
2940 }
2941 mOutputTracks.clear();
2942}
2943
2944bool AudioFlinger::DuplicatingThread::threadLoop()
2945{
2946 Vector< sp<Track> > tracksToRemove;
2947 uint32_t mixerStatus = MIXER_IDLE;
2948 nsecs_t standbyTime = systemTime();
2949 size_t mixBufferSize = mFrameCount*mFrameSize;
2950 SortedVector< sp<OutputTrack> > outputTracks;
2951 uint32_t writeFrames = 0;
2952 uint32_t activeSleepTime = activeSleepTimeUs();
2953 uint32_t idleSleepTime = idleSleepTimeUs();
2954 uint32_t sleepTime = idleSleepTime;
2955 Vector< sp<EffectChain> > effectChains;
2956
Eric Laurentfeb0db62011-07-22 09:04:31 -07002957 acquireWakeLock();
2958
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 while (!exitPending())
2960 {
2961 processConfigEvents();
2962
2963 mixerStatus = MIXER_IDLE;
2964 { // scope for the mLock
2965
2966 Mutex::Autolock _l(mLock);
2967
2968 if (checkForNewParameters_l()) {
2969 mixBufferSize = mFrameCount*mFrameSize;
2970 updateWaitTime();
2971 activeSleepTime = activeSleepTimeUs();
2972 idleSleepTime = idleSleepTimeUs();
2973 }
2974
2975 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2976
2977 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2978 outputTracks.add(mOutputTracks[i]);
2979 }
2980
2981 // put audio hardware into standby after short delay
2982 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2983 mSuspended) {
2984 if (!mStandby) {
2985 for (size_t i = 0; i < outputTracks.size(); i++) {
2986 outputTracks[i]->stop();
2987 }
2988 mStandby = true;
2989 mBytesWritten = 0;
2990 }
2991
2992 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2993 // we're about to wait, flush the binder command buffer
2994 IPCThreadState::self()->flushCommands();
2995 outputTracks.clear();
2996
2997 if (exitPending()) break;
2998
Eric Laurentfeb0db62011-07-22 09:04:31 -07002999 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003000 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003002 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003003 acquireWakeLock_l();
3004
Mathias Agopian65ab4712010-07-14 17:59:35 -07003005 if (mMasterMute == false) {
3006 char value[PROPERTY_VALUE_MAX];
3007 property_get("ro.audio.silent", value, "0");
3008 if (atoi(value)) {
3009 LOGD("Silence is golden");
3010 setMasterMute(true);
3011 }
3012 }
3013
3014 standbyTime = systemTime() + kStandbyTimeInNsecs;
3015 sleepTime = idleSleepTime;
3016 continue;
3017 }
3018 }
3019
3020 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3021
3022 // prevent any changes in effect chain list and in each effect chain
3023 // during mixing and effect process as the audio buffers could be deleted
3024 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003025 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 }
3027
3028 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3029 // mix buffers...
3030 if (outputsReady(outputTracks)) {
3031 mAudioMixer->process();
3032 } else {
3033 memset(mMixBuffer, 0, mixBufferSize);
3034 }
3035 sleepTime = 0;
3036 writeFrames = mFrameCount;
3037 } else {
3038 if (sleepTime == 0) {
3039 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3040 sleepTime = activeSleepTime;
3041 } else {
3042 sleepTime = idleSleepTime;
3043 }
3044 } else if (mBytesWritten != 0) {
3045 // flush remaining overflow buffers in output tracks
3046 for (size_t i = 0; i < outputTracks.size(); i++) {
3047 if (outputTracks[i]->isActive()) {
3048 sleepTime = 0;
3049 writeFrames = 0;
3050 memset(mMixBuffer, 0, mixBufferSize);
3051 break;
3052 }
3053 }
3054 }
3055 }
3056
3057 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003058 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003059 }
3060 // sleepTime == 0 means we must write to audio hardware
3061 if (sleepTime == 0) {
3062 for (size_t i = 0; i < effectChains.size(); i ++) {
3063 effectChains[i]->process_l();
3064 }
3065 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003066 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003067
3068 standbyTime = systemTime() + kStandbyTimeInNsecs;
3069 for (size_t i = 0; i < outputTracks.size(); i++) {
3070 outputTracks[i]->write(mMixBuffer, writeFrames);
3071 }
3072 mStandby = false;
3073 mBytesWritten += mixBufferSize;
3074 } else {
3075 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003076 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003077 usleep(sleepTime);
3078 }
3079
3080 // finally let go of all our tracks, without the lock held
3081 // since we can't guarantee the destructors won't acquire that
3082 // same lock.
3083 tracksToRemove.clear();
3084 outputTracks.clear();
3085
3086 // Effect chains will be actually deleted here if they were removed from
3087 // mEffectChains list during mixing or effects processing
3088 effectChains.clear();
3089 }
3090
Eric Laurentfeb0db62011-07-22 09:04:31 -07003091 releaseWakeLock();
3092
Mathias Agopian65ab4712010-07-14 17:59:35 -07003093 return false;
3094}
3095
3096void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3097{
3098 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3099 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3100 this,
3101 mSampleRate,
3102 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003103 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 frameCount);
3105 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003106 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003108 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 updateWaitTime();
3110 }
3111}
3112
3113void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3114{
3115 Mutex::Autolock _l(mLock);
3116 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3117 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3118 mOutputTracks[i]->destroy();
3119 mOutputTracks.removeAt(i);
3120 updateWaitTime();
3121 return;
3122 }
3123 }
Steve Block3856b092011-10-20 11:56:00 +01003124 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125}
3126
3127void AudioFlinger::DuplicatingThread::updateWaitTime()
3128{
3129 mWaitTimeMs = UINT_MAX;
3130 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3131 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3132 if (strong != NULL) {
3133 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3134 if (waitTimeMs < mWaitTimeMs) {
3135 mWaitTimeMs = waitTimeMs;
3136 }
3137 }
3138 }
3139}
3140
3141
3142bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3143{
3144 for (size_t i = 0; i < outputTracks.size(); i++) {
3145 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3146 if (thread == 0) {
3147 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3148 return false;
3149 }
3150 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3151 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003152 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 return false;
3154 }
3155 }
3156 return true;
3157}
3158
3159uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3160{
3161 return (mWaitTimeMs * 1000) / 2;
3162}
3163
3164// ----------------------------------------------------------------------------
3165
3166// TrackBase constructor must be called with AudioFlinger::mLock held
3167AudioFlinger::ThreadBase::TrackBase::TrackBase(
3168 const wp<ThreadBase>& thread,
3169 const sp<Client>& client,
3170 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003171 uint32_t format,
3172 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003173 int frameCount,
3174 uint32_t flags,
3175 const sp<IMemory>& sharedBuffer,
3176 int sessionId)
3177 : RefBase(),
3178 mThread(thread),
3179 mClient(client),
3180 mCblk(0),
3181 mFrameCount(0),
3182 mState(IDLE),
3183 mClientTid(-1),
3184 mFormat(format),
3185 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3186 mSessionId(sessionId)
3187{
Steve Block3856b092011-10-20 11:56:00 +01003188 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003189
3190 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3191 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003192 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3194 if (sharedBuffer == 0) {
3195 size += bufferSize;
3196 }
3197
3198 if (client != NULL) {
3199 mCblkMemory = client->heap()->allocate(size);
3200 if (mCblkMemory != 0) {
3201 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3202 if (mCblk) { // construct the shared structure in-place.
3203 new(mCblk) audio_track_cblk_t();
3204 // clear all buffers
3205 mCblk->frameCount = frameCount;
3206 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003207 mChannelCount = channelCount;
3208 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003209 if (sharedBuffer == 0) {
3210 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3211 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3212 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003213 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 mCblk->flags = CBLK_UNDERRUN_ON;
3215 } else {
3216 mBuffer = sharedBuffer->pointer();
3217 }
3218 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3219 }
3220 } else {
3221 LOGE("not enough memory for AudioTrack size=%u", size);
3222 client->heap()->dump("AudioTrack");
3223 return;
3224 }
3225 } else {
3226 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3227 if (mCblk) { // construct the shared structure in-place.
3228 new(mCblk) audio_track_cblk_t();
3229 // clear all buffers
3230 mCblk->frameCount = frameCount;
3231 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003232 mChannelCount = channelCount;
3233 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003234 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3235 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3236 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003237 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 mCblk->flags = CBLK_UNDERRUN_ON;
3239 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3240 }
3241 }
3242}
3243
3244AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3245{
3246 if (mCblk) {
3247 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3248 if (mClient == NULL) {
3249 delete mCblk;
3250 }
3251 }
3252 mCblkMemory.clear(); // and free the shared memory
3253 if (mClient != NULL) {
3254 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3255 mClient.clear();
3256 }
3257}
3258
3259void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3260{
3261 buffer->raw = 0;
3262 mFrameCount = buffer->frameCount;
3263 step();
3264 buffer->frameCount = 0;
3265}
3266
3267bool AudioFlinger::ThreadBase::TrackBase::step() {
3268 bool result;
3269 audio_track_cblk_t* cblk = this->cblk();
3270
3271 result = cblk->stepServer(mFrameCount);
3272 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003273 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003274 mFlags |= STEPSERVER_FAILED;
3275 }
3276 return result;
3277}
3278
3279void AudioFlinger::ThreadBase::TrackBase::reset() {
3280 audio_track_cblk_t* cblk = this->cblk();
3281
3282 cblk->user = 0;
3283 cblk->server = 0;
3284 cblk->userBase = 0;
3285 cblk->serverBase = 0;
3286 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003287 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003288}
3289
3290sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3291{
3292 return mCblkMemory;
3293}
3294
3295int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3296 return (int)mCblk->sampleRate;
3297}
3298
3299int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003300 return (const int)mChannelCount;
3301}
3302
3303uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3304 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003305}
3306
3307void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3308 audio_track_cblk_t* cblk = this->cblk();
3309 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3310 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3311
3312 // Check validity of returned pointer in case the track control block would have been corrupted.
3313 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3314 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3315 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 -07003316 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003317 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003318 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003319 return 0;
3320 }
3321
3322 return bufferStart;
3323}
3324
3325// ----------------------------------------------------------------------------
3326
3327// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3328AudioFlinger::PlaybackThread::Track::Track(
3329 const wp<ThreadBase>& thread,
3330 const sp<Client>& client,
3331 int streamType,
3332 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003333 uint32_t format,
3334 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 int frameCount,
3336 const sp<IMemory>& sharedBuffer,
3337 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003338 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003339 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3340 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341{
3342 if (mCblk != NULL) {
3343 sp<ThreadBase> baseThread = thread.promote();
3344 if (baseThread != 0) {
3345 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3346 mName = playbackThread->getTrackName_l();
3347 mMainBuffer = playbackThread->mixBuffer();
3348 }
Steve Block3856b092011-10-20 11:56:00 +01003349 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003350 if (mName < 0) {
3351 LOGE("no more track names available");
3352 }
3353 mVolume[0] = 1.0f;
3354 mVolume[1] = 1.0f;
3355 mStreamType = streamType;
3356 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3357 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003358 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003359 }
3360}
3361
3362AudioFlinger::PlaybackThread::Track::~Track()
3363{
Steve Block3856b092011-10-20 11:56:00 +01003364 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 sp<ThreadBase> thread = mThread.promote();
3366 if (thread != 0) {
3367 Mutex::Autolock _l(thread->mLock);
3368 mState = TERMINATED;
3369 }
3370}
3371
3372void AudioFlinger::PlaybackThread::Track::destroy()
3373{
3374 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3375 // by removing it from mTracks vector, so there is a risk that this Tracks's
3376 // desctructor is called. As the destructor needs to lock mLock,
3377 // we must acquire a strong reference on this Track before locking mLock
3378 // here so that the destructor is called only when exiting this function.
3379 // On the other hand, as long as Track::destroy() is only called by
3380 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3381 // this Track with its member mTrack.
3382 sp<Track> keep(this);
3383 { // scope for mLock
3384 sp<ThreadBase> thread = mThread.promote();
3385 if (thread != 0) {
3386 if (!isOutputTrack()) {
3387 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003388 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003389 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003390 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003391
3392 // to track the speaker usage
3393 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003394 }
3395 AudioSystem::releaseOutput(thread->id());
3396 }
3397 Mutex::Autolock _l(thread->mLock);
3398 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3399 playbackThread->destroyTrack_l(this);
3400 }
3401 }
3402}
3403
3404void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3405{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003406 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 -07003407 mName - AudioMixer::TRACK0,
3408 (mClient == NULL) ? getpid() : mClient->pid(),
3409 mStreamType,
3410 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003411 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412 mSessionId,
3413 mFrameCount,
3414 mState,
3415 mMute,
3416 mFillingUpStatus,
3417 mCblk->sampleRate,
3418 mCblk->volume[0],
3419 mCblk->volume[1],
3420 mCblk->server,
3421 mCblk->user,
3422 (int)mMainBuffer,
3423 (int)mAuxBuffer);
3424}
3425
3426status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3427{
3428 audio_track_cblk_t* cblk = this->cblk();
3429 uint32_t framesReady;
3430 uint32_t framesReq = buffer->frameCount;
3431
3432 // Check if last stepServer failed, try to step now
3433 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3434 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003435 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3437 }
3438
3439 framesReady = cblk->framesReady();
3440
3441 if (LIKELY(framesReady)) {
3442 uint32_t s = cblk->server;
3443 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3444
3445 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3446 if (framesReq > framesReady) {
3447 framesReq = framesReady;
3448 }
3449 if (s + framesReq > bufferEnd) {
3450 framesReq = bufferEnd - s;
3451 }
3452
3453 buffer->raw = getBuffer(s, framesReq);
3454 if (buffer->raw == 0) goto getNextBuffer_exit;
3455
3456 buffer->frameCount = framesReq;
3457 return NO_ERROR;
3458 }
3459
3460getNextBuffer_exit:
3461 buffer->raw = 0;
3462 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003463 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003464 return NOT_ENOUGH_DATA;
3465}
3466
3467bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003468 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003469
3470 if (mCblk->framesReady() >= mCblk->frameCount ||
3471 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3472 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003473 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003474 return true;
3475 }
3476 return false;
3477}
3478
3479status_t AudioFlinger::PlaybackThread::Track::start()
3480{
3481 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003482 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003483 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003484 sp<ThreadBase> thread = mThread.promote();
3485 if (thread != 0) {
3486 Mutex::Autolock _l(thread->mLock);
3487 int state = mState;
3488 // here the track could be either new, or restarted
3489 // in both cases "unstop" the track
3490 if (mState == PAUSED) {
3491 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003492 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493 } else {
3494 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003495 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 }
3497
3498 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3499 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003500 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003501 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003502 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003503 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003504
3505 // to track the speaker usage
3506 if (status == NO_ERROR) {
3507 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3508 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 }
3510 if (status == NO_ERROR) {
3511 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3512 playbackThread->addTrack_l(this);
3513 } else {
3514 mState = state;
3515 }
3516 } else {
3517 status = BAD_VALUE;
3518 }
3519 return status;
3520}
3521
3522void AudioFlinger::PlaybackThread::Track::stop()
3523{
Steve Block3856b092011-10-20 11:56:00 +01003524 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525 sp<ThreadBase> thread = mThread.promote();
3526 if (thread != 0) {
3527 Mutex::Autolock _l(thread->mLock);
3528 int state = mState;
3529 if (mState > STOPPED) {
3530 mState = STOPPED;
3531 // If the track is not active (PAUSED and buffers full), flush buffers
3532 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3533 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3534 reset();
3535 }
Steve Block3856b092011-10-20 11:56:00 +01003536 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537 }
3538 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3539 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003540 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003541 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003542 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003543 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003544
3545 // to track the speaker usage
3546 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 }
3548 }
3549}
3550
3551void AudioFlinger::PlaybackThread::Track::pause()
3552{
Steve Block3856b092011-10-20 11:56:00 +01003553 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 sp<ThreadBase> thread = mThread.promote();
3555 if (thread != 0) {
3556 Mutex::Autolock _l(thread->mLock);
3557 if (mState == ACTIVE || mState == RESUMING) {
3558 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003559 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 if (!isOutputTrack()) {
3561 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003562 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003563 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003564 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003566
3567 // to track the speaker usage
3568 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 }
3570 }
3571 }
3572}
3573
3574void AudioFlinger::PlaybackThread::Track::flush()
3575{
Steve Block3856b092011-10-20 11:56:00 +01003576 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 sp<ThreadBase> thread = mThread.promote();
3578 if (thread != 0) {
3579 Mutex::Autolock _l(thread->mLock);
3580 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3581 return;
3582 }
3583 // No point remaining in PAUSED state after a flush => go to
3584 // STOPPED state
3585 mState = STOPPED;
3586
Eric Laurent38ccae22011-03-28 18:37:07 -07003587 // do not reset the track if it is still in the process of being stopped or paused.
3588 // this will be done by prepareTracks_l() when the track is stopped.
3589 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3590 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3591 reset();
3592 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 }
3594}
3595
3596void AudioFlinger::PlaybackThread::Track::reset()
3597{
3598 // Do not reset twice to avoid discarding data written just after a flush and before
3599 // the audioflinger thread detects the track is stopped.
3600 if (!mResetDone) {
3601 TrackBase::reset();
3602 // Force underrun condition to avoid false underrun callback until first data is
3603 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003604 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3605 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606 mFillingUpStatus = FS_FILLING;
3607 mResetDone = true;
3608 }
3609}
3610
3611void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3612{
3613 mMute = muted;
3614}
3615
3616void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3617{
3618 mVolume[0] = left;
3619 mVolume[1] = right;
3620}
3621
3622status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3623{
3624 status_t status = DEAD_OBJECT;
3625 sp<ThreadBase> thread = mThread.promote();
3626 if (thread != 0) {
3627 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3628 status = playbackThread->attachAuxEffect(this, EffectId);
3629 }
3630 return status;
3631}
3632
3633void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3634{
3635 mAuxEffectId = EffectId;
3636 mAuxBuffer = buffer;
3637}
3638
3639// ----------------------------------------------------------------------------
3640
3641// RecordTrack constructor must be called with AudioFlinger::mLock held
3642AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3643 const wp<ThreadBase>& thread,
3644 const sp<Client>& client,
3645 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003646 uint32_t format,
3647 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003648 int frameCount,
3649 uint32_t flags,
3650 int sessionId)
3651 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003652 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653 mOverflow(false)
3654{
3655 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003656 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003657 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003658 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003659 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003660 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 } else {
3662 mCblk->frameSize = sizeof(int8_t);
3663 }
3664 }
3665}
3666
3667AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3668{
3669 sp<ThreadBase> thread = mThread.promote();
3670 if (thread != 0) {
3671 AudioSystem::releaseInput(thread->id());
3672 }
3673}
3674
3675status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3676{
3677 audio_track_cblk_t* cblk = this->cblk();
3678 uint32_t framesAvail;
3679 uint32_t framesReq = buffer->frameCount;
3680
3681 // Check if last stepServer failed, try to step now
3682 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3683 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003684 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003685 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3686 }
3687
3688 framesAvail = cblk->framesAvailable_l();
3689
3690 if (LIKELY(framesAvail)) {
3691 uint32_t s = cblk->server;
3692 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3693
3694 if (framesReq > framesAvail) {
3695 framesReq = framesAvail;
3696 }
3697 if (s + framesReq > bufferEnd) {
3698 framesReq = bufferEnd - s;
3699 }
3700
3701 buffer->raw = getBuffer(s, framesReq);
3702 if (buffer->raw == 0) goto getNextBuffer_exit;
3703
3704 buffer->frameCount = framesReq;
3705 return NO_ERROR;
3706 }
3707
3708getNextBuffer_exit:
3709 buffer->raw = 0;
3710 buffer->frameCount = 0;
3711 return NOT_ENOUGH_DATA;
3712}
3713
3714status_t AudioFlinger::RecordThread::RecordTrack::start()
3715{
3716 sp<ThreadBase> thread = mThread.promote();
3717 if (thread != 0) {
3718 RecordThread *recordThread = (RecordThread *)thread.get();
3719 return recordThread->start(this);
3720 } else {
3721 return BAD_VALUE;
3722 }
3723}
3724
3725void AudioFlinger::RecordThread::RecordTrack::stop()
3726{
3727 sp<ThreadBase> thread = mThread.promote();
3728 if (thread != 0) {
3729 RecordThread *recordThread = (RecordThread *)thread.get();
3730 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003731 TrackBase::reset();
3732 // Force overerrun condition to avoid false overrun callback until first data is
3733 // read from buffer
3734 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735 }
3736}
3737
3738void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3739{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003740 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003741 (mClient == NULL) ? getpid() : mClient->pid(),
3742 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003743 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744 mSessionId,
3745 mFrameCount,
3746 mState,
3747 mCblk->sampleRate,
3748 mCblk->server,
3749 mCblk->user);
3750}
3751
3752
3753// ----------------------------------------------------------------------------
3754
3755AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3756 const wp<ThreadBase>& thread,
3757 DuplicatingThread *sourceThread,
3758 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003759 uint32_t format,
3760 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003761 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003762 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003763 mActive(false), mSourceThread(sourceThread)
3764{
3765
3766 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3767 if (mCblk != NULL) {
3768 mCblk->flags |= CBLK_DIRECTION_OUT;
3769 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3770 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3771 mOutBuffer.frameCount = 0;
3772 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003773 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003774 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3775 mCblk, mBuffer, mCblk->buffers,
3776 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003777 } else {
3778 LOGW("Error creating output track on thread %p", playbackThread);
3779 }
3780}
3781
3782AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3783{
3784 clearBufferQueue();
3785}
3786
3787status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3788{
3789 status_t status = Track::start();
3790 if (status != NO_ERROR) {
3791 return status;
3792 }
3793
3794 mActive = true;
3795 mRetryCount = 127;
3796 return status;
3797}
3798
3799void AudioFlinger::PlaybackThread::OutputTrack::stop()
3800{
3801 Track::stop();
3802 clearBufferQueue();
3803 mOutBuffer.frameCount = 0;
3804 mActive = false;
3805}
3806
3807bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3808{
3809 Buffer *pInBuffer;
3810 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003811 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 bool outputBufferFull = false;
3813 inBuffer.frameCount = frames;
3814 inBuffer.i16 = data;
3815
3816 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3817
3818 if (!mActive && frames != 0) {
3819 start();
3820 sp<ThreadBase> thread = mThread.promote();
3821 if (thread != 0) {
3822 MixerThread *mixerThread = (MixerThread *)thread.get();
3823 if (mCblk->frameCount > frames){
3824 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3825 uint32_t startFrames = (mCblk->frameCount - frames);
3826 pInBuffer = new Buffer;
3827 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3828 pInBuffer->frameCount = startFrames;
3829 pInBuffer->i16 = pInBuffer->mBuffer;
3830 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3831 mBufferQueue.add(pInBuffer);
3832 } else {
3833 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3834 }
3835 }
3836 }
3837 }
3838
3839 while (waitTimeLeftMs) {
3840 // First write pending buffers, then new data
3841 if (mBufferQueue.size()) {
3842 pInBuffer = mBufferQueue.itemAt(0);
3843 } else {
3844 pInBuffer = &inBuffer;
3845 }
3846
3847 if (pInBuffer->frameCount == 0) {
3848 break;
3849 }
3850
3851 if (mOutBuffer.frameCount == 0) {
3852 mOutBuffer.frameCount = pInBuffer->frameCount;
3853 nsecs_t startTime = systemTime();
3854 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003855 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003856 outputBufferFull = true;
3857 break;
3858 }
3859 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3860 if (waitTimeLeftMs >= waitTimeMs) {
3861 waitTimeLeftMs -= waitTimeMs;
3862 } else {
3863 waitTimeLeftMs = 0;
3864 }
3865 }
3866
3867 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3868 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3869 mCblk->stepUser(outFrames);
3870 pInBuffer->frameCount -= outFrames;
3871 pInBuffer->i16 += outFrames * channelCount;
3872 mOutBuffer.frameCount -= outFrames;
3873 mOutBuffer.i16 += outFrames * channelCount;
3874
3875 if (pInBuffer->frameCount == 0) {
3876 if (mBufferQueue.size()) {
3877 mBufferQueue.removeAt(0);
3878 delete [] pInBuffer->mBuffer;
3879 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003880 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003881 } else {
3882 break;
3883 }
3884 }
3885 }
3886
3887 // If we could not write all frames, allocate a buffer and queue it for next time.
3888 if (inBuffer.frameCount) {
3889 sp<ThreadBase> thread = mThread.promote();
3890 if (thread != 0 && !thread->standby()) {
3891 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3892 pInBuffer = new Buffer;
3893 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3894 pInBuffer->frameCount = inBuffer.frameCount;
3895 pInBuffer->i16 = pInBuffer->mBuffer;
3896 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3897 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003898 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899 } else {
3900 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3901 }
3902 }
3903 }
3904
3905 // Calling write() with a 0 length buffer, means that no more data will be written:
3906 // If no more buffers are pending, fill output track buffer to make sure it is started
3907 // by output mixer.
3908 if (frames == 0 && mBufferQueue.size() == 0) {
3909 if (mCblk->user < mCblk->frameCount) {
3910 frames = mCblk->frameCount - mCblk->user;
3911 pInBuffer = new Buffer;
3912 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3913 pInBuffer->frameCount = frames;
3914 pInBuffer->i16 = pInBuffer->mBuffer;
3915 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3916 mBufferQueue.add(pInBuffer);
3917 } else if (mActive) {
3918 stop();
3919 }
3920 }
3921
3922 return outputBufferFull;
3923}
3924
3925status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3926{
3927 int active;
3928 status_t result;
3929 audio_track_cblk_t* cblk = mCblk;
3930 uint32_t framesReq = buffer->frameCount;
3931
Steve Block3856b092011-10-20 11:56:00 +01003932// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003933 buffer->frameCount = 0;
3934
3935 uint32_t framesAvail = cblk->framesAvailable();
3936
3937
3938 if (framesAvail == 0) {
3939 Mutex::Autolock _l(cblk->lock);
3940 goto start_loop_here;
3941 while (framesAvail == 0) {
3942 active = mActive;
3943 if (UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003944 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 return AudioTrack::NO_MORE_BUFFERS;
3946 }
3947 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3948 if (result != NO_ERROR) {
3949 return AudioTrack::NO_MORE_BUFFERS;
3950 }
3951 // read the server count again
3952 start_loop_here:
3953 framesAvail = cblk->framesAvailable_l();
3954 }
3955 }
3956
3957// if (framesAvail < framesReq) {
3958// return AudioTrack::NO_MORE_BUFFERS;
3959// }
3960
3961 if (framesReq > framesAvail) {
3962 framesReq = framesAvail;
3963 }
3964
3965 uint32_t u = cblk->user;
3966 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3967
3968 if (u + framesReq > bufferEnd) {
3969 framesReq = bufferEnd - u;
3970 }
3971
3972 buffer->frameCount = framesReq;
3973 buffer->raw = (void *)cblk->buffer(u);
3974 return NO_ERROR;
3975}
3976
3977
3978void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3979{
3980 size_t size = mBufferQueue.size();
3981 Buffer *pBuffer;
3982
3983 for (size_t i = 0; i < size; i++) {
3984 pBuffer = mBufferQueue.itemAt(i);
3985 delete [] pBuffer->mBuffer;
3986 delete pBuffer;
3987 }
3988 mBufferQueue.clear();
3989}
3990
3991// ----------------------------------------------------------------------------
3992
3993AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3994 : RefBase(),
3995 mAudioFlinger(audioFlinger),
3996 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3997 mPid(pid)
3998{
3999 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4000}
4001
4002// Client destructor must be called with AudioFlinger::mLock held
4003AudioFlinger::Client::~Client()
4004{
4005 mAudioFlinger->removeClient_l(mPid);
4006}
4007
4008const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4009{
4010 return mMemoryDealer;
4011}
4012
4013// ----------------------------------------------------------------------------
4014
4015AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4016 const sp<IAudioFlingerClient>& client,
4017 pid_t pid)
4018 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4019{
4020}
4021
4022AudioFlinger::NotificationClient::~NotificationClient()
4023{
4024 mClient.clear();
4025}
4026
4027void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4028{
4029 sp<NotificationClient> keep(this);
4030 {
4031 mAudioFlinger->removeNotificationClient(mPid);
4032 }
4033}
4034
4035// ----------------------------------------------------------------------------
4036
4037AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4038 : BnAudioTrack(),
4039 mTrack(track)
4040{
4041}
4042
4043AudioFlinger::TrackHandle::~TrackHandle() {
4044 // just stop the track on deletion, associated resources
4045 // will be freed from the main thread once all pending buffers have
4046 // been played. Unless it's not in the active track list, in which
4047 // case we free everything now...
4048 mTrack->destroy();
4049}
4050
4051status_t AudioFlinger::TrackHandle::start() {
4052 return mTrack->start();
4053}
4054
4055void AudioFlinger::TrackHandle::stop() {
4056 mTrack->stop();
4057}
4058
4059void AudioFlinger::TrackHandle::flush() {
4060 mTrack->flush();
4061}
4062
4063void AudioFlinger::TrackHandle::mute(bool e) {
4064 mTrack->mute(e);
4065}
4066
4067void AudioFlinger::TrackHandle::pause() {
4068 mTrack->pause();
4069}
4070
4071void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4072 mTrack->setVolume(left, right);
4073}
4074
4075sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4076 return mTrack->getCblk();
4077}
4078
4079status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4080{
4081 return mTrack->attachAuxEffect(EffectId);
4082}
4083
4084status_t AudioFlinger::TrackHandle::onTransact(
4085 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4086{
4087 return BnAudioTrack::onTransact(code, data, reply, flags);
4088}
4089
4090// ----------------------------------------------------------------------------
4091
4092sp<IAudioRecord> AudioFlinger::openRecord(
4093 pid_t pid,
4094 int input,
4095 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004096 uint32_t format,
4097 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 int frameCount,
4099 uint32_t flags,
4100 int *sessionId,
4101 status_t *status)
4102{
4103 sp<RecordThread::RecordTrack> recordTrack;
4104 sp<RecordHandle> recordHandle;
4105 sp<Client> client;
4106 wp<Client> wclient;
4107 status_t lStatus;
4108 RecordThread *thread;
4109 size_t inFrameCount;
4110 int lSessionId;
4111
4112 // check calling permissions
4113 if (!recordingAllowed()) {
4114 lStatus = PERMISSION_DENIED;
4115 goto Exit;
4116 }
4117
4118 // add client to list
4119 { // scope for mLock
4120 Mutex::Autolock _l(mLock);
4121 thread = checkRecordThread_l(input);
4122 if (thread == NULL) {
4123 lStatus = BAD_VALUE;
4124 goto Exit;
4125 }
4126
4127 wclient = mClients.valueFor(pid);
4128 if (wclient != NULL) {
4129 client = wclient.promote();
4130 } else {
4131 client = new Client(this, pid);
4132 mClients.add(pid, client);
4133 }
4134
4135 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004136 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 lSessionId = *sessionId;
4138 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004139 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004140 if (sessionId != NULL) {
4141 *sessionId = lSessionId;
4142 }
4143 }
4144 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004145 recordTrack = thread->createRecordTrack_l(client,
4146 sampleRate,
4147 format,
4148 channelMask,
4149 frameCount,
4150 flags,
4151 lSessionId,
4152 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004154 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004155 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4156 // destructor is called by the TrackBase destructor with mLock held
4157 client.clear();
4158 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 goto Exit;
4160 }
4161
4162 // return to handle to client
4163 recordHandle = new RecordHandle(recordTrack);
4164 lStatus = NO_ERROR;
4165
4166Exit:
4167 if (status) {
4168 *status = lStatus;
4169 }
4170 return recordHandle;
4171}
4172
4173// ----------------------------------------------------------------------------
4174
4175AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4176 : BnAudioRecord(),
4177 mRecordTrack(recordTrack)
4178{
4179}
4180
4181AudioFlinger::RecordHandle::~RecordHandle() {
4182 stop();
4183}
4184
4185status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004186 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004187 return mRecordTrack->start();
4188}
4189
4190void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004191 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 mRecordTrack->stop();
4193}
4194
4195sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4196 return mRecordTrack->getCblk();
4197}
4198
4199status_t AudioFlinger::RecordHandle::onTransact(
4200 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4201{
4202 return BnAudioRecord::onTransact(code, data, reply, flags);
4203}
4204
4205// ----------------------------------------------------------------------------
4206
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004207AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4208 AudioStreamIn *input,
4209 uint32_t sampleRate,
4210 uint32_t channels,
4211 int id,
4212 uint32_t device) :
4213 ThreadBase(audioFlinger, id, device),
4214 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004216 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004217
4218 snprintf(mName, kNameLength, "AudioIn_%d", id);
4219
Dima Zavinfce7a472011-04-19 22:30:36 -07004220 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004221 mReqSampleRate = sampleRate;
4222 readInputParameters();
4223}
4224
4225
4226AudioFlinger::RecordThread::~RecordThread()
4227{
4228 delete[] mRsmpInBuffer;
4229 if (mResampler != 0) {
4230 delete mResampler;
4231 delete[] mRsmpOutBuffer;
4232 }
4233}
4234
4235void AudioFlinger::RecordThread::onFirstRef()
4236{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004237 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004238}
4239
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004240status_t AudioFlinger::RecordThread::readyToRun()
4241{
4242 status_t status = initCheck();
4243 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4244 return status;
4245}
4246
Mathias Agopian65ab4712010-07-14 17:59:35 -07004247bool AudioFlinger::RecordThread::threadLoop()
4248{
4249 AudioBufferProvider::Buffer buffer;
4250 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004251 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252
Eric Laurent44d98482010-09-30 16:12:31 -07004253 nsecs_t lastWarning = 0;
4254
Eric Laurentfeb0db62011-07-22 09:04:31 -07004255 acquireWakeLock();
4256
Mathias Agopian65ab4712010-07-14 17:59:35 -07004257 // start recording
4258 while (!exitPending()) {
4259
4260 processConfigEvents();
4261
4262 { // scope for mLock
4263 Mutex::Autolock _l(mLock);
4264 checkForNewParameters_l();
4265 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4266 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004267 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 mStandby = true;
4269 }
4270
4271 if (exitPending()) break;
4272
Eric Laurentfeb0db62011-07-22 09:04:31 -07004273 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004274 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004275 // go to sleep
4276 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004277 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004278 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 continue;
4280 }
4281 if (mActiveTrack != 0) {
4282 if (mActiveTrack->mState == TrackBase::PAUSING) {
4283 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004284 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 mStandby = true;
4286 }
4287 mActiveTrack.clear();
4288 mStartStopCond.broadcast();
4289 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4290 if (mReqChannelCount != mActiveTrack->channelCount()) {
4291 mActiveTrack.clear();
4292 mStartStopCond.broadcast();
4293 } else if (mBytesRead != 0) {
4294 // record start succeeds only if first read from audio input
4295 // succeeds
4296 if (mBytesRead > 0) {
4297 mActiveTrack->mState = TrackBase::ACTIVE;
4298 } else {
4299 mActiveTrack.clear();
4300 }
4301 mStartStopCond.broadcast();
4302 }
4303 mStandby = false;
4304 }
4305 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004306 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004307 }
4308
4309 if (mActiveTrack != 0) {
4310 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4311 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004312 unlockEffectChains(effectChains);
4313 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 continue;
4315 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004316 for (size_t i = 0; i < effectChains.size(); i ++) {
4317 effectChains[i]->process_l();
4318 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004319
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 buffer.frameCount = mFrameCount;
4321 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4322 size_t framesOut = buffer.frameCount;
4323 if (mResampler == 0) {
4324 // no resampling
4325 while (framesOut) {
4326 size_t framesIn = mFrameCount - mRsmpInIndex;
4327 if (framesIn) {
4328 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4329 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4330 if (framesIn > framesOut)
4331 framesIn = framesOut;
4332 mRsmpInIndex += framesIn;
4333 framesOut -= framesIn;
4334 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004335 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 memcpy(dst, src, framesIn * mFrameSize);
4337 } else {
4338 int16_t *src16 = (int16_t *)src;
4339 int16_t *dst16 = (int16_t *)dst;
4340 if (mChannelCount == 1) {
4341 while (framesIn--) {
4342 *dst16++ = *src16;
4343 *dst16++ = *src16++;
4344 }
4345 } else {
4346 while (framesIn--) {
4347 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4348 src16 += 2;
4349 }
4350 }
4351 }
4352 }
4353 if (framesOut && mFrameCount == mRsmpInIndex) {
4354 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004355 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004356 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004357 framesOut = 0;
4358 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004359 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 mRsmpInIndex = 0;
4361 }
4362 if (mBytesRead < 0) {
4363 LOGE("Error reading audio input");
4364 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4365 // Force input into standby so that it tries to
4366 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004367 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004368 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004369 }
4370 mRsmpInIndex = mFrameCount;
4371 framesOut = 0;
4372 buffer.frameCount = 0;
4373 }
4374 }
4375 }
4376 } else {
4377 // resampling
4378
4379 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4380 // alter output frame count as if we were expecting stereo samples
4381 if (mChannelCount == 1 && mReqChannelCount == 1) {
4382 framesOut >>= 1;
4383 }
4384 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4385 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4386 // are 32 bit aligned which should be always true.
4387 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004388 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004389 // the resampler always outputs stereo samples: do post stereo to mono conversion
4390 int16_t *src = (int16_t *)mRsmpOutBuffer;
4391 int16_t *dst = buffer.i16;
4392 while (framesOut--) {
4393 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4394 src += 2;
4395 }
4396 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004397 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004398 }
4399
4400 }
4401 mActiveTrack->releaseBuffer(&buffer);
4402 mActiveTrack->overflow();
4403 }
4404 // client isn't retrieving buffers fast enough
4405 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004406 if (!mActiveTrack->setOverflow()) {
4407 nsecs_t now = systemTime();
4408 if ((now - lastWarning) > kWarningThrottle) {
4409 LOGW("RecordThread: buffer overflow");
4410 lastWarning = now;
4411 }
4412 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413 // Release the processor for a while before asking for a new buffer.
4414 // This will give the application more chance to read from the buffer and
4415 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004416 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004417 }
4418 }
Eric Laurentec437d82011-07-26 20:54:46 -07004419 // enable changes in effect chain
4420 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004421 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423
4424 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004425 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 }
4427 mActiveTrack.clear();
4428
4429 mStartStopCond.broadcast();
4430
Eric Laurentfeb0db62011-07-22 09:04:31 -07004431 releaseWakeLock();
4432
Steve Block3856b092011-10-20 11:56:00 +01004433 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 return false;
4435}
4436
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004437
4438sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4439 const sp<AudioFlinger::Client>& client,
4440 uint32_t sampleRate,
4441 int format,
4442 int channelMask,
4443 int frameCount,
4444 uint32_t flags,
4445 int sessionId,
4446 status_t *status)
4447{
4448 sp<RecordTrack> track;
4449 status_t lStatus;
4450
4451 lStatus = initCheck();
4452 if (lStatus != NO_ERROR) {
4453 LOGE("Audio driver not initialized.");
4454 goto Exit;
4455 }
4456
4457 { // scope for mLock
4458 Mutex::Autolock _l(mLock);
4459
4460 track = new RecordTrack(this, client, sampleRate,
4461 format, channelMask, frameCount, flags, sessionId);
4462
4463 if (track->getCblk() == NULL) {
4464 lStatus = NO_MEMORY;
4465 goto Exit;
4466 }
4467
4468 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004469 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4470 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004471 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004472 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4473 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004474 }
4475 lStatus = NO_ERROR;
4476
4477Exit:
4478 if (status) {
4479 *status = lStatus;
4480 }
4481 return track;
4482}
4483
Mathias Agopian65ab4712010-07-14 17:59:35 -07004484status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4485{
Steve Block3856b092011-10-20 11:56:00 +01004486 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004487 sp <ThreadBase> strongMe = this;
4488 status_t status = NO_ERROR;
4489 {
4490 AutoMutex lock(&mLock);
4491 if (mActiveTrack != 0) {
4492 if (recordTrack != mActiveTrack.get()) {
4493 status = -EBUSY;
4494 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4495 mActiveTrack->mState = TrackBase::ACTIVE;
4496 }
4497 return status;
4498 }
4499
4500 recordTrack->mState = TrackBase::IDLE;
4501 mActiveTrack = recordTrack;
4502 mLock.unlock();
4503 status_t status = AudioSystem::startInput(mId);
4504 mLock.lock();
4505 if (status != NO_ERROR) {
4506 mActiveTrack.clear();
4507 return status;
4508 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004509 mRsmpInIndex = mFrameCount;
4510 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004511 if (mResampler != NULL) {
4512 mResampler->reset();
4513 }
4514 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004515 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004516 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 mWaitWorkCV.signal();
4518 // do not wait for mStartStopCond if exiting
4519 if (mExiting) {
4520 mActiveTrack.clear();
4521 status = INVALID_OPERATION;
4522 goto startError;
4523 }
4524 mStartStopCond.wait(mLock);
4525 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004526 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004527 status = BAD_VALUE;
4528 goto startError;
4529 }
Steve Block3856b092011-10-20 11:56:00 +01004530 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 return status;
4532 }
4533startError:
4534 AudioSystem::stopInput(mId);
4535 return status;
4536}
4537
4538void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004539 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 sp <ThreadBase> strongMe = this;
4541 {
4542 AutoMutex lock(&mLock);
4543 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4544 mActiveTrack->mState = TrackBase::PAUSING;
4545 // do not wait for mStartStopCond if exiting
4546 if (mExiting) {
4547 return;
4548 }
4549 mStartStopCond.wait(mLock);
4550 // if we have been restarted, recordTrack == mActiveTrack.get() here
4551 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4552 mLock.unlock();
4553 AudioSystem::stopInput(mId);
4554 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004555 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004556 }
4557 }
4558 }
4559}
4560
4561status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4562{
4563 const size_t SIZE = 256;
4564 char buffer[SIZE];
4565 String8 result;
4566 pid_t pid = 0;
4567
4568 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4569 result.append(buffer);
4570
4571 if (mActiveTrack != 0) {
4572 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004573 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004574 mActiveTrack->dump(buffer, SIZE);
4575 result.append(buffer);
4576
4577 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4578 result.append(buffer);
4579 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4580 result.append(buffer);
4581 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4582 result.append(buffer);
4583 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4584 result.append(buffer);
4585 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4586 result.append(buffer);
4587
4588
4589 } else {
4590 result.append("No record client\n");
4591 }
4592 write(fd, result.string(), result.size());
4593
4594 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004595 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004596
4597 return NO_ERROR;
4598}
4599
4600status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4601{
4602 size_t framesReq = buffer->frameCount;
4603 size_t framesReady = mFrameCount - mRsmpInIndex;
4604 int channelCount;
4605
4606 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004607 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 if (mBytesRead < 0) {
4609 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4610 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4611 // Force input into standby so that it tries to
4612 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004613 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004614 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004615 }
4616 buffer->raw = 0;
4617 buffer->frameCount = 0;
4618 return NOT_ENOUGH_DATA;
4619 }
4620 mRsmpInIndex = 0;
4621 framesReady = mFrameCount;
4622 }
4623
4624 if (framesReq > framesReady) {
4625 framesReq = framesReady;
4626 }
4627
4628 if (mChannelCount == 1 && mReqChannelCount == 2) {
4629 channelCount = 1;
4630 } else {
4631 channelCount = 2;
4632 }
4633 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4634 buffer->frameCount = framesReq;
4635 return NO_ERROR;
4636}
4637
4638void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4639{
4640 mRsmpInIndex += buffer->frameCount;
4641 buffer->frameCount = 0;
4642}
4643
4644bool AudioFlinger::RecordThread::checkForNewParameters_l()
4645{
4646 bool reconfig = false;
4647
4648 while (!mNewParameters.isEmpty()) {
4649 status_t status = NO_ERROR;
4650 String8 keyValuePair = mNewParameters[0];
4651 AudioParameter param = AudioParameter(keyValuePair);
4652 int value;
4653 int reqFormat = mFormat;
4654 int reqSamplingRate = mReqSampleRate;
4655 int reqChannelCount = mReqChannelCount;
4656
4657 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4658 reqSamplingRate = value;
4659 reconfig = true;
4660 }
4661 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4662 reqFormat = value;
4663 reconfig = true;
4664 }
4665 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004666 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 reconfig = true;
4668 }
4669 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4670 // do not accept frame count changes if tracks are open as the track buffer
4671 // size depends on frame count and correct behavior would not be garantied
4672 // if frame count is changed after track creation
4673 if (mActiveTrack != 0) {
4674 status = INVALID_OPERATION;
4675 } else {
4676 reconfig = true;
4677 }
4678 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004679 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4680 // forward device change to effects that have requested to be
4681 // aware of attached audio device.
4682 for (size_t i = 0; i < mEffectChains.size(); i++) {
4683 mEffectChains[i]->setDevice_l(value);
4684 }
4685 // store input device and output device but do not forward output device to audio HAL.
4686 // Note that status is ignored by the caller for output device
4687 // (see AudioFlinger::setParameters()
4688 if (value & AUDIO_DEVICE_OUT_ALL) {
4689 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4690 status = BAD_VALUE;
4691 } else {
4692 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004693 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4694 if (mTrack != NULL) {
4695 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004696 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004697 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4698 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4699 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004700 }
4701 mDevice |= (uint32_t)value;
4702 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004703 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004704 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004706 mInput->stream->common.standby(&mInput->stream->common);
4707 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004708 }
4709 if (reconfig) {
4710 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004711 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004712 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004713 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4714 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004715 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 status = NO_ERROR;
4717 }
4718 if (status == NO_ERROR) {
4719 readInputParameters();
4720 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4721 }
4722 }
4723 }
4724
4725 mNewParameters.removeAt(0);
4726
4727 mParamStatus = status;
4728 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004729 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4730 // already timed out waiting for the status and will never signal the condition.
4731 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732 }
4733 return reconfig;
4734}
4735
4736String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4737{
Dima Zavinfce7a472011-04-19 22:30:36 -07004738 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004739 String8 out_s8 = String8();
4740
4741 Mutex::Autolock _l(mLock);
4742 if (initCheck() != NO_ERROR) {
4743 return out_s8;
4744 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004745
Dima Zavin799a70e2011-04-18 16:57:27 -07004746 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004747 out_s8 = String8(s);
4748 free(s);
4749 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750}
4751
4752void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4753 AudioSystem::OutputDescriptor desc;
4754 void *param2 = 0;
4755
4756 switch (event) {
4757 case AudioSystem::INPUT_OPENED:
4758 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004759 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004760 desc.samplingRate = mSampleRate;
4761 desc.format = mFormat;
4762 desc.frameCount = mFrameCount;
4763 desc.latency = 0;
4764 param2 = &desc;
4765 break;
4766
4767 case AudioSystem::INPUT_CLOSED:
4768 default:
4769 break;
4770 }
4771 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4772}
4773
4774void AudioFlinger::RecordThread::readInputParameters()
4775{
4776 if (mRsmpInBuffer) delete mRsmpInBuffer;
4777 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4778 if (mResampler) delete mResampler;
4779 mResampler = 0;
4780
Dima Zavin799a70e2011-04-18 16:57:27 -07004781 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004782 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4783 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004784 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4785 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4786 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787 mFrameCount = mInputBytes / mFrameSize;
4788 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4789
4790 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4791 {
4792 int channelCount;
4793 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4794 // stereo to mono post process as the resampler always outputs stereo.
4795 if (mChannelCount == 1 && mReqChannelCount == 2) {
4796 channelCount = 1;
4797 } else {
4798 channelCount = 2;
4799 }
4800 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4801 mResampler->setSampleRate(mSampleRate);
4802 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4803 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4804
4805 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4806 if (mChannelCount == 1 && mReqChannelCount == 1) {
4807 mFrameCount >>= 1;
4808 }
4809
4810 }
4811 mRsmpInIndex = mFrameCount;
4812}
4813
4814unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4815{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004816 Mutex::Autolock _l(mLock);
4817 if (initCheck() != NO_ERROR) {
4818 return 0;
4819 }
4820
Dima Zavin799a70e2011-04-18 16:57:27 -07004821 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822}
4823
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004824uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4825{
4826 Mutex::Autolock _l(mLock);
4827 uint32_t result = 0;
4828 if (getEffectChain_l(sessionId) != 0) {
4829 result = EFFECT_SESSION;
4830 }
4831
4832 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4833 result |= TRACK_SESSION;
4834 }
4835
4836 return result;
4837}
4838
Eric Laurent59bd0da2011-08-01 09:52:20 -07004839AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4840{
4841 Mutex::Autolock _l(mLock);
4842 return mTrack;
4843}
4844
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004845AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4846{
4847 Mutex::Autolock _l(mLock);
4848 return mInput;
4849}
4850
4851AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4852{
4853 Mutex::Autolock _l(mLock);
4854 AudioStreamIn *input = mInput;
4855 mInput = NULL;
4856 return input;
4857}
4858
4859// this method must always be called either with ThreadBase mLock held or inside the thread loop
4860audio_stream_t* AudioFlinger::RecordThread::stream()
4861{
4862 if (mInput == NULL) {
4863 return NULL;
4864 }
4865 return &mInput->stream->common;
4866}
4867
4868
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869// ----------------------------------------------------------------------------
4870
4871int AudioFlinger::openOutput(uint32_t *pDevices,
4872 uint32_t *pSamplingRate,
4873 uint32_t *pFormat,
4874 uint32_t *pChannels,
4875 uint32_t *pLatencyMs,
4876 uint32_t flags)
4877{
4878 status_t status;
4879 PlaybackThread *thread = NULL;
4880 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4881 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4882 uint32_t format = pFormat ? *pFormat : 0;
4883 uint32_t channels = pChannels ? *pChannels : 0;
4884 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004885 audio_stream_out_t *outStream;
4886 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004887
Steve Block3856b092011-10-20 11:56:00 +01004888 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 pDevices ? *pDevices : 0,
4890 samplingRate,
4891 format,
4892 channels,
4893 flags);
4894
4895 if (pDevices == NULL || *pDevices == 0) {
4896 return 0;
4897 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004898
Mathias Agopian65ab4712010-07-14 17:59:35 -07004899 Mutex::Autolock _l(mLock);
4900
Dima Zavin799a70e2011-04-18 16:57:27 -07004901 outHwDev = findSuitableHwDev_l(*pDevices);
4902 if (outHwDev == NULL)
4903 return 0;
4904
4905 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4906 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004907 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004908 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004909 samplingRate,
4910 format,
4911 channels,
4912 status);
4913
4914 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004915 if (outStream != NULL) {
4916 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004917 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004918
Dima Zavinfce7a472011-04-19 22:30:36 -07004919 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4920 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4921 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004923 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004924 } else {
4925 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004926 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004927 }
4928 mPlaybackThreads.add(id, thread);
4929
4930 if (pSamplingRate) *pSamplingRate = samplingRate;
4931 if (pFormat) *pFormat = format;
4932 if (pChannels) *pChannels = channels;
4933 if (pLatencyMs) *pLatencyMs = thread->latency();
4934
4935 // notify client processes of the new output creation
4936 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4937 return id;
4938 }
4939
4940 return 0;
4941}
4942
4943int AudioFlinger::openDuplicateOutput(int output1, int output2)
4944{
4945 Mutex::Autolock _l(mLock);
4946 MixerThread *thread1 = checkMixerThread_l(output1);
4947 MixerThread *thread2 = checkMixerThread_l(output2);
4948
4949 if (thread1 == NULL || thread2 == NULL) {
4950 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4951 return 0;
4952 }
4953
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004954 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004955 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4956 thread->addOutputTrack(thread2);
4957 mPlaybackThreads.add(id, thread);
4958 // notify client processes of the new output creation
4959 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4960 return id;
4961}
4962
4963status_t AudioFlinger::closeOutput(int output)
4964{
4965 // keep strong reference on the playback thread so that
4966 // it is not destroyed while exit() is executed
4967 sp <PlaybackThread> thread;
4968 {
4969 Mutex::Autolock _l(mLock);
4970 thread = checkPlaybackThread_l(output);
4971 if (thread == NULL) {
4972 return BAD_VALUE;
4973 }
4974
Steve Block3856b092011-10-20 11:56:00 +01004975 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004976
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004977 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004978 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004979 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004980 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4981 dupThread->removeOutputTrack((MixerThread *)thread.get());
4982 }
4983 }
4984 }
4985 void *param2 = 0;
4986 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4987 mPlaybackThreads.removeItem(output);
4988 }
4989 thread->exit();
4990
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004991 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004992 AudioStreamOut *out = thread->clearOutput();
4993 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07004994 out->hwDev->close_output_stream(out->hwDev, out->stream);
4995 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 }
4997 return NO_ERROR;
4998}
4999
5000status_t AudioFlinger::suspendOutput(int output)
5001{
5002 Mutex::Autolock _l(mLock);
5003 PlaybackThread *thread = checkPlaybackThread_l(output);
5004
5005 if (thread == NULL) {
5006 return BAD_VALUE;
5007 }
5008
Steve Block3856b092011-10-20 11:56:00 +01005009 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 thread->suspend();
5011
5012 return NO_ERROR;
5013}
5014
5015status_t AudioFlinger::restoreOutput(int output)
5016{
5017 Mutex::Autolock _l(mLock);
5018 PlaybackThread *thread = checkPlaybackThread_l(output);
5019
5020 if (thread == NULL) {
5021 return BAD_VALUE;
5022 }
5023
Steve Block3856b092011-10-20 11:56:00 +01005024 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025
5026 thread->restore();
5027
5028 return NO_ERROR;
5029}
5030
5031int AudioFlinger::openInput(uint32_t *pDevices,
5032 uint32_t *pSamplingRate,
5033 uint32_t *pFormat,
5034 uint32_t *pChannels,
5035 uint32_t acoustics)
5036{
5037 status_t status;
5038 RecordThread *thread = NULL;
5039 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5040 uint32_t format = pFormat ? *pFormat : 0;
5041 uint32_t channels = pChannels ? *pChannels : 0;
5042 uint32_t reqSamplingRate = samplingRate;
5043 uint32_t reqFormat = format;
5044 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005045 audio_stream_in_t *inStream;
5046 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005047
5048 if (pDevices == NULL || *pDevices == 0) {
5049 return 0;
5050 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005051
Mathias Agopian65ab4712010-07-14 17:59:35 -07005052 Mutex::Autolock _l(mLock);
5053
Dima Zavin799a70e2011-04-18 16:57:27 -07005054 inHwDev = findSuitableHwDev_l(*pDevices);
5055 if (inHwDev == NULL)
5056 return 0;
5057
5058 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5059 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005060 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005061 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005062 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005063 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005064 samplingRate,
5065 format,
5066 channels,
5067 acoustics,
5068 status);
5069
5070 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5071 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5072 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005073 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005074 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005076 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005077 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005078 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5079 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005080 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 }
5083
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 if (inStream != NULL) {
5085 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5086
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005087 int id = nextUniqueId();
5088 // Start record thread
5089 // RecorThread require both input and output device indication to forward to audio
5090 // pre processing modules
5091 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5092 thread = new RecordThread(this,
5093 input,
5094 reqSamplingRate,
5095 reqChannels,
5096 id,
5097 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005099 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5101 if (pFormat) *pFormat = format;
5102 if (pChannels) *pChannels = reqChannels;
5103
Dima Zavin799a70e2011-04-18 16:57:27 -07005104 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105
5106 // notify client processes of the new input creation
5107 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5108 return id;
5109 }
5110
5111 return 0;
5112}
5113
5114status_t AudioFlinger::closeInput(int input)
5115{
5116 // keep strong reference on the record thread so that
5117 // it is not destroyed while exit() is executed
5118 sp <RecordThread> thread;
5119 {
5120 Mutex::Autolock _l(mLock);
5121 thread = checkRecordThread_l(input);
5122 if (thread == NULL) {
5123 return BAD_VALUE;
5124 }
5125
Steve Block3856b092011-10-20 11:56:00 +01005126 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005127 void *param2 = 0;
5128 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5129 mRecordThreads.removeItem(input);
5130 }
5131 thread->exit();
5132
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005133 AudioStreamIn *in = thread->clearInput();
5134 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005135 in->hwDev->close_input_stream(in->hwDev, in->stream);
5136 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005137
5138 return NO_ERROR;
5139}
5140
5141status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5142{
5143 Mutex::Autolock _l(mLock);
5144 MixerThread *dstThread = checkMixerThread_l(output);
5145 if (dstThread == NULL) {
5146 LOGW("setStreamOutput() bad output id %d", output);
5147 return BAD_VALUE;
5148 }
5149
Steve Block3856b092011-10-20 11:56:00 +01005150 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005151 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5152
Eric Laurent9f6530f2011-08-30 10:18:54 -07005153 dstThread->setStreamValid(stream, true);
5154
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5156 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5157 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005158 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005160 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005161 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 }
Eric Laurentde070132010-07-13 04:45:46 -07005163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164
5165 return NO_ERROR;
5166}
5167
5168
5169int AudioFlinger::newAudioSessionId()
5170{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005171 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172}
5173
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005174void AudioFlinger::acquireAudioSessionId(int audioSession)
5175{
5176 Mutex::Autolock _l(mLock);
5177 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005178 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005179 int num = mAudioSessionRefs.size();
5180 for (int i = 0; i< num; i++) {
5181 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5182 if (ref->sessionid == audioSession && ref->pid == caller) {
5183 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005184 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005185 return;
5186 }
5187 }
5188 AudioSessionRef *ref = new AudioSessionRef();
5189 ref->sessionid = audioSession;
5190 ref->pid = caller;
5191 ref->cnt = 1;
5192 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005193 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005194}
5195
5196void AudioFlinger::releaseAudioSessionId(int audioSession)
5197{
5198 Mutex::Autolock _l(mLock);
5199 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005200 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005201 int num = mAudioSessionRefs.size();
5202 for (int i = 0; i< num; i++) {
5203 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5204 if (ref->sessionid == audioSession && ref->pid == caller) {
5205 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005206 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005207 if (ref->cnt == 0) {
5208 mAudioSessionRefs.removeAt(i);
5209 delete ref;
5210 purgeStaleEffects_l();
5211 }
5212 return;
5213 }
5214 }
5215 LOGW("session id %d not found for pid %d", audioSession, caller);
5216}
5217
5218void AudioFlinger::purgeStaleEffects_l() {
5219
Steve Block3856b092011-10-20 11:56:00 +01005220 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005221
5222 Vector< sp<EffectChain> > chains;
5223
5224 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5225 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5226 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5227 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005228 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5229 chains.push(ec);
5230 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005231 }
5232 }
5233 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5234 sp<RecordThread> t = mRecordThreads.valueAt(i);
5235 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5236 sp<EffectChain> ec = t->mEffectChains[j];
5237 chains.push(ec);
5238 }
5239 }
5240
5241 for (size_t i = 0; i < chains.size(); i++) {
5242 sp<EffectChain> ec = chains[i];
5243 int sessionid = ec->sessionId();
5244 sp<ThreadBase> t = ec->mThread.promote();
5245 if (t == 0) {
5246 continue;
5247 }
5248 size_t numsessionrefs = mAudioSessionRefs.size();
5249 bool found = false;
5250 for (size_t k = 0; k < numsessionrefs; k++) {
5251 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5252 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005253 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005254 sessionid, ref->pid, ref->cnt);
5255 found = true;
5256 break;
5257 }
5258 }
5259 if (!found) {
5260 // remove all effects from the chain
5261 while (ec->mEffects.size()) {
5262 sp<EffectModule> effect = ec->mEffects[0];
5263 effect->unPin();
5264 Mutex::Autolock _l (t->mLock);
5265 t->removeEffect_l(effect);
5266 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5267 sp<EffectHandle> handle = effect->mHandles[j].promote();
5268 if (handle != 0) {
5269 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005270 if (handle->mHasControl && handle->mEnabled) {
5271 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5272 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005273 }
5274 }
5275 AudioSystem::unregisterEffect(effect->id());
5276 }
5277 }
5278 }
5279 return;
5280}
5281
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5283AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5284{
5285 PlaybackThread *thread = NULL;
5286 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5287 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5288 }
5289 return thread;
5290}
5291
5292// checkMixerThread_l() must be called with AudioFlinger::mLock held
5293AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5294{
5295 PlaybackThread *thread = checkPlaybackThread_l(output);
5296 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005297 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005298 thread = NULL;
5299 }
5300 }
5301 return (MixerThread *)thread;
5302}
5303
5304// checkRecordThread_l() must be called with AudioFlinger::mLock held
5305AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5306{
5307 RecordThread *thread = NULL;
5308 if (mRecordThreads.indexOfKey(input) >= 0) {
5309 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5310 }
5311 return thread;
5312}
5313
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005314uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005316 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317}
5318
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005319AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5320{
5321 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5322 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005323 AudioStreamOut *output = thread->getOutput();
5324 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005325 return thread;
5326 }
5327 }
5328 return NULL;
5329}
5330
5331uint32_t AudioFlinger::primaryOutputDevice_l()
5332{
5333 PlaybackThread *thread = primaryPlaybackThread_l();
5334
5335 if (thread == NULL) {
5336 return 0;
5337 }
5338
5339 return thread->device();
5340}
5341
5342
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343// ----------------------------------------------------------------------------
5344// Effect management
5345// ----------------------------------------------------------------------------
5346
5347
Mathias Agopian65ab4712010-07-14 17:59:35 -07005348status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5349{
5350 Mutex::Autolock _l(mLock);
5351 return EffectQueryNumberEffects(numEffects);
5352}
5353
5354status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5355{
5356 Mutex::Autolock _l(mLock);
5357 return EffectQueryEffect(index, descriptor);
5358}
5359
5360status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5361{
5362 Mutex::Autolock _l(mLock);
5363 return EffectGetDescriptor(pUuid, descriptor);
5364}
5365
5366
Mathias Agopian65ab4712010-07-14 17:59:35 -07005367sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5368 effect_descriptor_t *pDesc,
5369 const sp<IEffectClient>& effectClient,
5370 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005371 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005372 int sessionId,
5373 status_t *status,
5374 int *id,
5375 int *enabled)
5376{
5377 status_t lStatus = NO_ERROR;
5378 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 effect_descriptor_t desc;
5380 sp<Client> client;
5381 wp<Client> wclient;
5382
Steve Block3856b092011-10-20 11:56:00 +01005383 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005384 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385
5386 if (pDesc == NULL) {
5387 lStatus = BAD_VALUE;
5388 goto Exit;
5389 }
5390
Eric Laurent84e9a102010-09-23 16:10:16 -07005391 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005392 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005393 lStatus = PERMISSION_DENIED;
5394 goto Exit;
5395 }
5396
Dima Zavinfce7a472011-04-19 22:30:36 -07005397 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005398 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005399 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005400 lStatus = PERMISSION_DENIED;
5401 goto Exit;
5402 }
5403
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005404 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005406 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005407 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005408 lStatus = BAD_VALUE;
5409 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005410 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005411 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005413 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005414 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005415 }
5416 }
5417
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 {
5419 Mutex::Autolock _l(mLock);
5420
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421
5422 if (!EffectIsNullUuid(&pDesc->uuid)) {
5423 // if uuid is specified, request effect descriptor
5424 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5425 if (lStatus < 0) {
5426 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5427 goto Exit;
5428 }
5429 } else {
5430 // if uuid is not specified, look for an available implementation
5431 // of the required type in effect factory
5432 if (EffectIsNullUuid(&pDesc->type)) {
5433 LOGW("createEffect() no effect type");
5434 lStatus = BAD_VALUE;
5435 goto Exit;
5436 }
5437 uint32_t numEffects = 0;
5438 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005439 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005440 bool found = false;
5441
5442 lStatus = EffectQueryNumberEffects(&numEffects);
5443 if (lStatus < 0) {
5444 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5445 goto Exit;
5446 }
5447 for (uint32_t i = 0; i < numEffects; i++) {
5448 lStatus = EffectQueryEffect(i, &desc);
5449 if (lStatus < 0) {
5450 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5451 continue;
5452 }
5453 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5454 // If matching type found save effect descriptor. If the session is
5455 // 0 and the effect is not auxiliary, continue enumeration in case
5456 // an auxiliary version of this effect type is available
5457 found = true;
5458 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005459 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005460 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5461 break;
5462 }
5463 }
5464 }
5465 if (!found) {
5466 lStatus = BAD_VALUE;
5467 LOGW("createEffect() effect not found");
5468 goto Exit;
5469 }
5470 // For same effect type, chose auxiliary version over insert version if
5471 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005472 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5474 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5475 }
5476 }
5477
5478 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005479 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5481 lStatus = INVALID_OPERATION;
5482 goto Exit;
5483 }
5484
Eric Laurent59255e42011-07-27 19:49:51 -07005485 // check recording permission for visualizer
5486 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5487 !recordingAllowed()) {
5488 lStatus = PERMISSION_DENIED;
5489 goto Exit;
5490 }
5491
Mathias Agopian65ab4712010-07-14 17:59:35 -07005492 // return effect descriptor
5493 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5494
5495 // If output is not specified try to find a matching audio session ID in one of the
5496 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005497 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5498 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005499 // Note: io is never 0 when creating an effect on an input
5500 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005501 // look for the thread where the specified audio session is present
5502 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5503 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005504 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005505 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005508 if (io == 0) {
5509 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5510 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5511 io = mRecordThreads.keyAt(i);
5512 break;
5513 }
5514 }
5515 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005516 // If no output thread contains the requested session ID, default to
5517 // first output. The effect chain will be moved to the correct output
5518 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005519 if (io == 0 && mPlaybackThreads.size()) {
5520 io = mPlaybackThreads.keyAt(0);
5521 }
Steve Block3856b092011-10-20 11:56:00 +01005522 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005523 }
5524 ThreadBase *thread = checkRecordThread_l(io);
5525 if (thread == NULL) {
5526 thread = checkPlaybackThread_l(io);
5527 if (thread == NULL) {
5528 LOGE("createEffect() unknown output thread");
5529 lStatus = BAD_VALUE;
5530 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005531 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005533
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 wclient = mClients.valueFor(pid);
5535
5536 if (wclient != NULL) {
5537 client = wclient.promote();
5538 } else {
5539 client = new Client(this, pid);
5540 mClients.add(pid, client);
5541 }
5542
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005543 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005544 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5545 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005546 if (handle != 0 && id != NULL) {
5547 *id = handle->id();
5548 }
5549 }
5550
5551Exit:
5552 if(status) {
5553 *status = lStatus;
5554 }
5555 return handle;
5556}
5557
Eric Laurent59255e42011-07-27 19:49:51 -07005558status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005559{
Steve Block3856b092011-10-20 11:56:00 +01005560 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005561 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005562 Mutex::Autolock _l(mLock);
5563 if (srcOutput == dstOutput) {
5564 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5565 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005566 }
Eric Laurentde070132010-07-13 04:45:46 -07005567 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5568 if (srcThread == NULL) {
5569 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5570 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 }
Eric Laurentde070132010-07-13 04:45:46 -07005572 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5573 if (dstThread == NULL) {
5574 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5575 return BAD_VALUE;
5576 }
5577
5578 Mutex::Autolock _dl(dstThread->mLock);
5579 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005580 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005581
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 return NO_ERROR;
5583}
5584
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005585// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005586status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005587 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005588 AudioFlinger::PlaybackThread *dstThread,
5589 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005590{
Steve Block3856b092011-10-20 11:56:00 +01005591 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005592 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005593
Eric Laurent59255e42011-07-27 19:49:51 -07005594 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005595 if (chain == 0) {
5596 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005597 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005598 return INVALID_OPERATION;
5599 }
5600
Eric Laurent39e94f82010-07-28 01:32:47 -07005601 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005602 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005603 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005604 // removed.
5605 srcThread->removeEffectChain_l(chain);
5606
5607 // transfer all effects one by one so that new effect chain is created on new thread with
5608 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005609 int dstOutput = dstThread->id();
5610 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005611 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005612 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5613 while (effect != 0) {
5614 srcThread->removeEffect_l(effect);
5615 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005616 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5617 if (effect->state() == EffectModule::ACTIVE ||
5618 effect->state() == EffectModule::STOPPING) {
5619 effect->start();
5620 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005621 // if the move request is not received from audio policy manager, the effect must be
5622 // re-registered with the new strategy and output
5623 if (dstChain == 0) {
5624 dstChain = effect->chain().promote();
5625 if (dstChain == 0) {
5626 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5627 srcThread->addEffect_l(effect);
5628 return NO_INIT;
5629 }
5630 strategy = dstChain->strategy();
5631 }
5632 if (reRegister) {
5633 AudioSystem::unregisterEffect(effect->id());
5634 AudioSystem::registerEffect(&effect->desc(),
5635 dstOutput,
5636 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005637 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005638 effect->id());
5639 }
Eric Laurentde070132010-07-13 04:45:46 -07005640 effect = chain->getEffectFromId_l(0);
5641 }
5642
5643 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644}
5645
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005646
Mathias Agopian65ab4712010-07-14 17:59:35 -07005647// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005648sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005649 const sp<AudioFlinger::Client>& client,
5650 const sp<IEffectClient>& effectClient,
5651 int32_t priority,
5652 int sessionId,
5653 effect_descriptor_t *desc,
5654 int *enabled,
5655 status_t *status
5656 )
5657{
5658 sp<EffectModule> effect;
5659 sp<EffectHandle> handle;
5660 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005662 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005663 bool effectCreated = false;
5664 bool effectRegistered = false;
5665
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005666 lStatus = initCheck();
5667 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 goto Exit;
5670 }
5671
5672 // Do not allow effects with session ID 0 on direct output or duplicating threads
5673 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005674 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005675 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5676 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 lStatus = BAD_VALUE;
5678 goto Exit;
5679 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005680 // Only Pre processor effects are allowed on input threads and only on input threads
5681 if ((mType == RECORD &&
5682 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5683 (mType != RECORD &&
5684 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5685 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5686 desc->name, desc->flags, mType);
5687 lStatus = BAD_VALUE;
5688 goto Exit;
5689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690
Steve Block3856b092011-10-20 11:56:00 +01005691 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005692
5693 { // scope for mLock
5694 Mutex::Autolock _l(mLock);
5695
5696 // check for existing effect chain with the requested audio session
5697 chain = getEffectChain_l(sessionId);
5698 if (chain == 0) {
5699 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005700 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701 chain = new EffectChain(this, sessionId);
5702 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005703 chain->setStrategy(getStrategyForSession_l(sessionId));
5704 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005706 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005707 }
5708
Steve Block3856b092011-10-20 11:56:00 +01005709 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005710
5711 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005712 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005714 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 if (lStatus != NO_ERROR) {
5716 goto Exit;
5717 }
5718 effectRegistered = true;
5719 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005720 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 lStatus = effect->status();
5722 if (lStatus != NO_ERROR) {
5723 goto Exit;
5724 }
Eric Laurentcab11242010-07-15 12:50:15 -07005725 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 if (lStatus != NO_ERROR) {
5727 goto Exit;
5728 }
5729 effectCreated = true;
5730
5731 effect->setDevice(mDevice);
5732 effect->setMode(mAudioFlinger->getMode());
5733 }
5734 // create effect handle and connect it to effect module
5735 handle = new EffectHandle(effect, client, effectClient, priority);
5736 lStatus = effect->addHandle(handle);
5737 if (enabled) {
5738 *enabled = (int)effect->isEnabled();
5739 }
5740 }
5741
5742Exit:
5743 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005744 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005745 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005746 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005747 }
5748 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005749 AudioSystem::unregisterEffect(effect->id());
5750 }
5751 if (chainCreated) {
5752 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753 }
5754 handle.clear();
5755 }
5756
5757 if(status) {
5758 *status = lStatus;
5759 }
5760 return handle;
5761}
5762
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005763sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5764{
5765 sp<EffectModule> effect;
5766
5767 sp<EffectChain> chain = getEffectChain_l(sessionId);
5768 if (chain != 0) {
5769 effect = chain->getEffectFromId_l(effectId);
5770 }
5771 return effect;
5772}
5773
Eric Laurentde070132010-07-13 04:45:46 -07005774// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5775// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005776status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005777{
5778 // check for existing effect chain with the requested audio session
5779 int sessionId = effect->sessionId();
5780 sp<EffectChain> chain = getEffectChain_l(sessionId);
5781 bool chainCreated = false;
5782
5783 if (chain == 0) {
5784 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005785 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005786 chain = new EffectChain(this, sessionId);
5787 addEffectChain_l(chain);
5788 chain->setStrategy(getStrategyForSession_l(sessionId));
5789 chainCreated = true;
5790 }
Steve Block3856b092011-10-20 11:56:00 +01005791 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005792
5793 if (chain->getEffectFromId_l(effect->id()) != 0) {
5794 LOGW("addEffect_l() %p effect %s already present in chain %p",
5795 this, effect->desc().name, chain.get());
5796 return BAD_VALUE;
5797 }
5798
5799 status_t status = chain->addEffect_l(effect);
5800 if (status != NO_ERROR) {
5801 if (chainCreated) {
5802 removeEffectChain_l(chain);
5803 }
5804 return status;
5805 }
5806
5807 effect->setDevice(mDevice);
5808 effect->setMode(mAudioFlinger->getMode());
5809 return NO_ERROR;
5810}
5811
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005812void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005813
Steve Block3856b092011-10-20 11:56:00 +01005814 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005815 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005816 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5817 detachAuxEffect_l(effect->id());
5818 }
5819
5820 sp<EffectChain> chain = effect->chain().promote();
5821 if (chain != 0) {
5822 // remove effect chain if removing last effect
5823 if (chain->removeEffect_l(effect) == 0) {
5824 removeEffectChain_l(chain);
5825 }
5826 } else {
5827 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5828 }
5829}
5830
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005831void AudioFlinger::ThreadBase::lockEffectChains_l(
5832 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5833{
5834 effectChains = mEffectChains;
5835 for (size_t i = 0; i < mEffectChains.size(); i++) {
5836 mEffectChains[i]->lock();
5837 }
5838}
5839
5840void AudioFlinger::ThreadBase::unlockEffectChains(
5841 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5842{
5843 for (size_t i = 0; i < effectChains.size(); i++) {
5844 effectChains[i]->unlock();
5845 }
5846}
5847
5848sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5849{
5850 Mutex::Autolock _l(mLock);
5851 return getEffectChain_l(sessionId);
5852}
5853
5854sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5855{
5856 sp<EffectChain> chain;
5857
5858 size_t size = mEffectChains.size();
5859 for (size_t i = 0; i < size; i++) {
5860 if (mEffectChains[i]->sessionId() == sessionId) {
5861 chain = mEffectChains[i];
5862 break;
5863 }
5864 }
5865 return chain;
5866}
5867
5868void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5869{
5870 Mutex::Autolock _l(mLock);
5871 size_t size = mEffectChains.size();
5872 for (size_t i = 0; i < size; i++) {
5873 mEffectChains[i]->setMode_l(mode);
5874 }
5875}
5876
5877void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005878 const wp<EffectHandle>& handle,
5879 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005880
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005882 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005883 // delete the effect module if removing last handle on it
5884 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005885 if (!effect->isPinned() || unpiniflast) {
5886 removeEffect_l(effect);
5887 AudioSystem::unregisterEffect(effect->id());
5888 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 }
5890}
5891
5892status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5893{
5894 int session = chain->sessionId();
5895 int16_t *buffer = mMixBuffer;
5896 bool ownsBuffer = false;
5897
Steve Block3856b092011-10-20 11:56:00 +01005898 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 if (session > 0) {
5900 // Only one effect chain can be present in direct output thread and it uses
5901 // the mix buffer as input
5902 if (mType != DIRECT) {
5903 size_t numSamples = mFrameCount * mChannelCount;
5904 buffer = new int16_t[numSamples];
5905 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 ownsBuffer = true;
5908 }
5909
5910 // Attach all tracks with same session ID to this chain.
5911 for (size_t i = 0; i < mTracks.size(); ++i) {
5912 sp<Track> track = mTracks[i];
5913 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005916 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005917 }
5918 }
5919
5920 // indicate all active tracks in the chain
5921 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5922 sp<Track> track = mActiveTracks[i].promote();
5923 if (track == 0) continue;
5924 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005926 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 }
5928 }
5929 }
5930
5931 chain->setInBuffer(buffer, ownsBuffer);
5932 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005933 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005934 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005935 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5936 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005938 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5939 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005940 // Effect chain for other sessions are inserted at beginning of effect
5941 // chains list to be processed before output mix effects. Relative order between other
5942 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005943 size_t size = mEffectChains.size();
5944 size_t i = 0;
5945 for (i = 0; i < size; i++) {
5946 if (mEffectChains[i]->sessionId() < session) break;
5947 }
5948 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005949 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950
5951 return NO_ERROR;
5952}
5953
5954size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5955{
5956 int session = chain->sessionId();
5957
Steve Block3856b092011-10-20 11:56:00 +01005958 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959
5960 for (size_t i = 0; i < mEffectChains.size(); i++) {
5961 if (chain == mEffectChains[i]) {
5962 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005963 // detach all active tracks from the chain
5964 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5965 sp<Track> track = mActiveTracks[i].promote();
5966 if (track == 0) continue;
5967 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005968 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005969 chain.get(), session);
5970 chain->decActiveTrackCnt();
5971 }
5972 }
5973
Mathias Agopian65ab4712010-07-14 17:59:35 -07005974 // detach all tracks with same session ID from this chain
5975 for (size_t i = 0; i < mTracks.size(); ++i) {
5976 sp<Track> track = mTracks[i];
5977 if (session == track->sessionId()) {
5978 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005979 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005980 }
5981 }
Eric Laurentde070132010-07-13 04:45:46 -07005982 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005983 }
5984 }
5985 return mEffectChains.size();
5986}
5987
Eric Laurentde070132010-07-13 04:45:46 -07005988status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5989 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005990{
5991 Mutex::Autolock _l(mLock);
5992 return attachAuxEffect_l(track, EffectId);
5993}
5994
Eric Laurentde070132010-07-13 04:45:46 -07005995status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5996 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005997{
5998 status_t status = NO_ERROR;
5999
6000 if (EffectId == 0) {
6001 track->setAuxBuffer(0, NULL);
6002 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006003 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6004 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005 if (effect != 0) {
6006 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6007 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6008 } else {
6009 status = INVALID_OPERATION;
6010 }
6011 } else {
6012 status = BAD_VALUE;
6013 }
6014 }
6015 return status;
6016}
6017
6018void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6019{
6020 for (size_t i = 0; i < mTracks.size(); ++i) {
6021 sp<Track> track = mTracks[i];
6022 if (track->auxEffectId() == effectId) {
6023 attachAuxEffect_l(track, 0);
6024 }
6025 }
6026}
6027
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006028status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6029{
6030 // only one chain per input thread
6031 if (mEffectChains.size() != 0) {
6032 return INVALID_OPERATION;
6033 }
Steve Block3856b092011-10-20 11:56:00 +01006034 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006035
6036 chain->setInBuffer(NULL);
6037 chain->setOutBuffer(NULL);
6038
Eric Laurent59255e42011-07-27 19:49:51 -07006039 checkSuspendOnAddEffectChain_l(chain);
6040
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041 mEffectChains.add(chain);
6042
6043 return NO_ERROR;
6044}
6045
6046size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6047{
Steve Block3856b092011-10-20 11:56:00 +01006048 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049 LOGW_IF(mEffectChains.size() != 1,
6050 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6051 chain.get(), mEffectChains.size(), this);
6052 if (mEffectChains.size() == 1) {
6053 mEffectChains.removeAt(0);
6054 }
6055 return 0;
6056}
6057
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058// ----------------------------------------------------------------------------
6059// EffectModule implementation
6060// ----------------------------------------------------------------------------
6061
6062#undef LOG_TAG
6063#define LOG_TAG "AudioFlinger::EffectModule"
6064
6065AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6066 const wp<AudioFlinger::EffectChain>& chain,
6067 effect_descriptor_t *desc,
6068 int id,
6069 int sessionId)
6070 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006071 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006072{
Steve Block3856b092011-10-20 11:56:00 +01006073 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 int lStatus;
6075 sp<ThreadBase> thread = mThread.promote();
6076 if (thread == 0) {
6077 return;
6078 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079
6080 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6081
6082 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006083 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006084
6085 if (mStatus != NO_ERROR) {
6086 return;
6087 }
6088 lStatus = init();
6089 if (lStatus < 0) {
6090 mStatus = lStatus;
6091 goto Error;
6092 }
6093
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006094 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6095 mPinned = true;
6096 }
Steve Block3856b092011-10-20 11:56:00 +01006097 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 return;
6099Error:
6100 EffectRelease(mEffectInterface);
6101 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006102 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103}
6104
6105AudioFlinger::EffectModule::~EffectModule()
6106{
Steve Block3856b092011-10-20 11:56:00 +01006107 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006109 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6110 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6111 sp<ThreadBase> thread = mThread.promote();
6112 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006113 audio_stream_t *stream = thread->stream();
6114 if (stream != NULL) {
6115 stream->remove_audio_effect(stream, mEffectInterface);
6116 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 }
6118 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 // release effect engine
6120 EffectRelease(mEffectInterface);
6121 }
6122}
6123
6124status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6125{
6126 status_t status;
6127
6128 Mutex::Autolock _l(mLock);
6129 // First handle in mHandles has highest priority and controls the effect module
6130 int priority = handle->priority();
6131 size_t size = mHandles.size();
6132 sp<EffectHandle> h;
6133 size_t i;
6134 for (i = 0; i < size; i++) {
6135 h = mHandles[i].promote();
6136 if (h == 0) continue;
6137 if (h->priority() <= priority) break;
6138 }
6139 // if inserted in first place, move effect control from previous owner to this handle
6140 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006141 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006142 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006143 enabled = h->enabled();
6144 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006145 }
Eric Laurent59255e42011-07-27 19:49:51 -07006146 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006147 status = NO_ERROR;
6148 } else {
6149 status = ALREADY_EXISTS;
6150 }
Steve Block3856b092011-10-20 11:56:00 +01006151 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152 mHandles.insertAt(handle, i);
6153 return status;
6154}
6155
6156size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6157{
6158 Mutex::Autolock _l(mLock);
6159 size_t size = mHandles.size();
6160 size_t i;
6161 for (i = 0; i < size; i++) {
6162 if (mHandles[i] == handle) break;
6163 }
6164 if (i == size) {
6165 return size;
6166 }
Steve Block3856b092011-10-20 11:56:00 +01006167 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006168
6169 bool enabled = false;
6170 EffectHandle *hdl = handle.unsafe_get();
6171 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006172 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006173 enabled = hdl->enabled();
6174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006175 mHandles.removeAt(i);
6176 size = mHandles.size();
6177 // if removed from first place, move effect control from this handle to next in line
6178 if (i == 0 && size != 0) {
6179 sp<EffectHandle> h = mHandles[0].promote();
6180 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006181 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006182 }
6183 }
6184
Eric Laurentec437d82011-07-26 20:54:46 -07006185 // Prevent calls to process() and other functions on effect interface from now on.
6186 // The effect engine will be released by the destructor when the last strong reference on
6187 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006188 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006189 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006190 }
6191
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 return size;
6193}
6194
Eric Laurent59255e42011-07-27 19:49:51 -07006195sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6196{
6197 Mutex::Autolock _l(mLock);
6198 sp<EffectHandle> handle;
6199 if (mHandles.size() != 0) {
6200 handle = mHandles[0].promote();
6201 }
6202 return handle;
6203}
6204
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006205void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206{
Steve Block3856b092011-10-20 11:56:00 +01006207 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 // keep a strong reference on this EffectModule to avoid calling the
6209 // destructor before we exit
6210 sp<EffectModule> keep(this);
6211 {
6212 sp<ThreadBase> thread = mThread.promote();
6213 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006214 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006215 }
6216 }
6217}
6218
6219void AudioFlinger::EffectModule::updateState() {
6220 Mutex::Autolock _l(mLock);
6221
6222 switch (mState) {
6223 case RESTART:
6224 reset_l();
6225 // FALL THROUGH
6226
6227 case STARTING:
6228 // clear auxiliary effect input buffer for next accumulation
6229 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6230 memset(mConfig.inputCfg.buffer.raw,
6231 0,
6232 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6233 }
6234 start_l();
6235 mState = ACTIVE;
6236 break;
6237 case STOPPING:
6238 stop_l();
6239 mDisableWaitCnt = mMaxDisableWaitCnt;
6240 mState = STOPPED;
6241 break;
6242 case STOPPED:
6243 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6244 // turn off sequence.
6245 if (--mDisableWaitCnt == 0) {
6246 reset_l();
6247 mState = IDLE;
6248 }
6249 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006250 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006251 break;
6252 }
6253}
6254
6255void AudioFlinger::EffectModule::process()
6256{
6257 Mutex::Autolock _l(mLock);
6258
Eric Laurentec437d82011-07-26 20:54:46 -07006259 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006260 mConfig.inputCfg.buffer.raw == NULL ||
6261 mConfig.outputCfg.buffer.raw == NULL) {
6262 return;
6263 }
6264
Eric Laurent8f45bd72010-08-31 13:50:07 -07006265 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006266 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6267 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006268 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006270 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 }
6272
6273 // do the actual processing in the effect engine
6274 int ret = (*mEffectInterface)->process(mEffectInterface,
6275 &mConfig.inputCfg.buffer,
6276 &mConfig.outputCfg.buffer);
6277
6278 // force transition to IDLE state when engine is ready
6279 if (mState == STOPPED && ret == -ENODATA) {
6280 mDisableWaitCnt = 1;
6281 }
6282
6283 // clear auxiliary effect input buffer for next accumulation
6284 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006285 memset(mConfig.inputCfg.buffer.raw, 0,
6286 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 }
6288 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006289 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6290 // If an insert effect is idle and input buffer is different from output buffer,
6291 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006292 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006293 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006294 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6295 int16_t *in = mConfig.inputCfg.buffer.s16;
6296 int16_t *out = mConfig.outputCfg.buffer.s16;
6297 for (size_t i = 0; i < frameCnt; i++) {
6298 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 }
6301 }
6302}
6303
6304void AudioFlinger::EffectModule::reset_l()
6305{
6306 if (mEffectInterface == NULL) {
6307 return;
6308 }
6309 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6310}
6311
6312status_t AudioFlinger::EffectModule::configure()
6313{
6314 uint32_t channels;
6315 if (mEffectInterface == NULL) {
6316 return NO_INIT;
6317 }
6318
6319 sp<ThreadBase> thread = mThread.promote();
6320 if (thread == 0) {
6321 return DEAD_OBJECT;
6322 }
6323
6324 // TODO: handle configuration of effects replacing track process
6325 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006326 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006328 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006329 }
6330
6331 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006332 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333 } else {
6334 mConfig.inputCfg.channels = channels;
6335 }
6336 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006337 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6338 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339 mConfig.inputCfg.samplingRate = thread->sampleRate();
6340 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6341 mConfig.inputCfg.bufferProvider.cookie = NULL;
6342 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6343 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6344 mConfig.outputCfg.bufferProvider.cookie = NULL;
6345 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6346 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6347 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6348 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006349 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006350 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351 // - in other sessions:
6352 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6353 // other effect: overwrites output buffer: input buffer == output buffer
6354 // Auxiliary effect:
6355 // accumulates in output buffer: input buffer != output buffer
6356 // Therefore: accumulate <=> input buffer != output buffer
6357 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6358 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6359 } else {
6360 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6361 }
6362 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6363 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6364 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6365 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6366
Steve Block3856b092011-10-20 11:56:00 +01006367 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006368 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6369
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006371 uint32_t size = sizeof(int);
6372 status_t status = (*mEffectInterface)->command(mEffectInterface,
6373 EFFECT_CMD_CONFIGURE,
6374 sizeof(effect_config_t),
6375 &mConfig,
6376 &size,
6377 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 if (status == 0) {
6379 status = cmdStatus;
6380 }
6381
6382 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6383 (1000 * mConfig.outputCfg.buffer.frameCount);
6384
6385 return status;
6386}
6387
6388status_t AudioFlinger::EffectModule::init()
6389{
6390 Mutex::Autolock _l(mLock);
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_INIT,
6398 0,
6399 NULL,
6400 &size,
6401 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 if (status == 0) {
6403 status = cmdStatus;
6404 }
6405 return status;
6406}
6407
Eric Laurentec35a142011-10-05 17:42:25 -07006408status_t AudioFlinger::EffectModule::start()
6409{
6410 Mutex::Autolock _l(mLock);
6411 return start_l();
6412}
6413
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414status_t AudioFlinger::EffectModule::start_l()
6415{
6416 if (mEffectInterface == NULL) {
6417 return NO_INIT;
6418 }
6419 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006420 uint32_t size = sizeof(status_t);
6421 status_t status = (*mEffectInterface)->command(mEffectInterface,
6422 EFFECT_CMD_ENABLE,
6423 0,
6424 NULL,
6425 &size,
6426 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427 if (status == 0) {
6428 status = cmdStatus;
6429 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006430 if (status == 0 &&
6431 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6432 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6433 sp<ThreadBase> thread = mThread.promote();
6434 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006435 audio_stream_t *stream = thread->stream();
6436 if (stream != NULL) {
6437 stream->add_audio_effect(stream, mEffectInterface);
6438 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006439 }
6440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441 return status;
6442}
6443
Eric Laurentec437d82011-07-26 20:54:46 -07006444status_t AudioFlinger::EffectModule::stop()
6445{
6446 Mutex::Autolock _l(mLock);
6447 return stop_l();
6448}
6449
Mathias Agopian65ab4712010-07-14 17:59:35 -07006450status_t AudioFlinger::EffectModule::stop_l()
6451{
6452 if (mEffectInterface == NULL) {
6453 return NO_INIT;
6454 }
6455 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006456 uint32_t size = sizeof(status_t);
6457 status_t status = (*mEffectInterface)->command(mEffectInterface,
6458 EFFECT_CMD_DISABLE,
6459 0,
6460 NULL,
6461 &size,
6462 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463 if (status == 0) {
6464 status = cmdStatus;
6465 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006466 if (status == 0 &&
6467 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6468 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6469 sp<ThreadBase> thread = mThread.promote();
6470 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006471 audio_stream_t *stream = thread->stream();
6472 if (stream != NULL) {
6473 stream->remove_audio_effect(stream, mEffectInterface);
6474 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006475 }
6476 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477 return status;
6478}
6479
Eric Laurent25f43952010-07-28 05:40:18 -07006480status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6481 uint32_t cmdSize,
6482 void *pCmdData,
6483 uint32_t *replySize,
6484 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485{
6486 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006487// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488
Eric Laurentec437d82011-07-26 20:54:46 -07006489 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 return NO_INIT;
6491 }
Eric Laurent25f43952010-07-28 05:40:18 -07006492 status_t status = (*mEffectInterface)->command(mEffectInterface,
6493 cmdCode,
6494 cmdSize,
6495 pCmdData,
6496 replySize,
6497 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006499 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006500 for (size_t i = 1; i < mHandles.size(); i++) {
6501 sp<EffectHandle> h = mHandles[i].promote();
6502 if (h != 0) {
6503 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6504 }
6505 }
6506 }
6507 return status;
6508}
6509
6510status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6511{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006512
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006514 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006515
6516 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006517 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6518 if (enabled && status != NO_ERROR) {
6519 return status;
6520 }
6521
Mathias Agopian65ab4712010-07-14 17:59:35 -07006522 switch (mState) {
6523 // going from disabled to enabled
6524 case IDLE:
6525 mState = STARTING;
6526 break;
6527 case STOPPED:
6528 mState = RESTART;
6529 break;
6530 case STOPPING:
6531 mState = ACTIVE;
6532 break;
6533
6534 // going from enabled to disabled
6535 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006536 mState = STOPPED;
6537 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 case STARTING:
6539 mState = IDLE;
6540 break;
6541 case ACTIVE:
6542 mState = STOPPING;
6543 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006544 case DESTROYED:
6545 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 }
6547 for (size_t i = 1; i < mHandles.size(); i++) {
6548 sp<EffectHandle> h = mHandles[i].promote();
6549 if (h != 0) {
6550 h->setEnabled(enabled);
6551 }
6552 }
6553 }
6554 return NO_ERROR;
6555}
6556
6557bool AudioFlinger::EffectModule::isEnabled()
6558{
6559 switch (mState) {
6560 case RESTART:
6561 case STARTING:
6562 case ACTIVE:
6563 return true;
6564 case IDLE:
6565 case STOPPING:
6566 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006567 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006568 default:
6569 return false;
6570 }
6571}
6572
Eric Laurent8f45bd72010-08-31 13:50:07 -07006573bool AudioFlinger::EffectModule::isProcessEnabled()
6574{
6575 switch (mState) {
6576 case RESTART:
6577 case ACTIVE:
6578 case STOPPING:
6579 case STOPPED:
6580 return true;
6581 case IDLE:
6582 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006583 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006584 default:
6585 return false;
6586 }
6587}
6588
Mathias Agopian65ab4712010-07-14 17:59:35 -07006589status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6590{
6591 Mutex::Autolock _l(mLock);
6592 status_t status = NO_ERROR;
6593
6594 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6595 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006596 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006597 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6598 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006599 status_t cmdStatus;
6600 uint32_t volume[2];
6601 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006602 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006603 volume[0] = *left;
6604 volume[1] = *right;
6605 if (controller) {
6606 pVolume = volume;
6607 }
Eric Laurent25f43952010-07-28 05:40:18 -07006608 status = (*mEffectInterface)->command(mEffectInterface,
6609 EFFECT_CMD_SET_VOLUME,
6610 size,
6611 volume,
6612 &size,
6613 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6615 *left = volume[0];
6616 *right = volume[1];
6617 }
6618 }
6619 return status;
6620}
6621
6622status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6623{
6624 Mutex::Autolock _l(mLock);
6625 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006626 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6627 // audio pre processing modules on RecordThread can receive both output and
6628 // input device indication in the same call
6629 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6630 if (dev) {
6631 status_t cmdStatus;
6632 uint32_t size = sizeof(status_t);
6633
6634 status = (*mEffectInterface)->command(mEffectInterface,
6635 EFFECT_CMD_SET_DEVICE,
6636 sizeof(uint32_t),
6637 &dev,
6638 &size,
6639 &cmdStatus);
6640 if (status == NO_ERROR) {
6641 status = cmdStatus;
6642 }
6643 }
6644 dev = device & AUDIO_DEVICE_IN_ALL;
6645 if (dev) {
6646 status_t cmdStatus;
6647 uint32_t size = sizeof(status_t);
6648
6649 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6650 EFFECT_CMD_SET_INPUT_DEVICE,
6651 sizeof(uint32_t),
6652 &dev,
6653 &size,
6654 &cmdStatus);
6655 if (status2 == NO_ERROR) {
6656 status2 = cmdStatus;
6657 }
6658 if (status == NO_ERROR) {
6659 status = status2;
6660 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 }
6662 }
6663 return status;
6664}
6665
6666status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6667{
6668 Mutex::Autolock _l(mLock);
6669 status_t status = NO_ERROR;
6670 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006671 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006672 uint32_t size = sizeof(status_t);
6673 status = (*mEffectInterface)->command(mEffectInterface,
6674 EFFECT_CMD_SET_AUDIO_MODE,
6675 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006676 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006677 &size,
6678 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679 if (status == NO_ERROR) {
6680 status = cmdStatus;
6681 }
6682 }
6683 return status;
6684}
6685
Eric Laurent59255e42011-07-27 19:49:51 -07006686void AudioFlinger::EffectModule::setSuspended(bool suspended)
6687{
6688 Mutex::Autolock _l(mLock);
6689 mSuspended = suspended;
6690}
6691bool AudioFlinger::EffectModule::suspended()
6692{
6693 Mutex::Autolock _l(mLock);
6694 return mSuspended;
6695}
6696
Mathias Agopian65ab4712010-07-14 17:59:35 -07006697status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6698{
6699 const size_t SIZE = 256;
6700 char buffer[SIZE];
6701 String8 result;
6702
6703 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6704 result.append(buffer);
6705
6706 bool locked = tryLock(mLock);
6707 // failed to lock - AudioFlinger is probably deadlocked
6708 if (!locked) {
6709 result.append("\t\tCould not lock Fx mutex:\n");
6710 }
6711
6712 result.append("\t\tSession Status State Engine:\n");
6713 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6714 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6715 result.append(buffer);
6716
6717 result.append("\t\tDescriptor:\n");
6718 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6719 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6720 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6721 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6722 result.append(buffer);
6723 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6724 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6725 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6726 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6727 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006728 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006729 mDescriptor.apiVersion,
6730 mDescriptor.flags);
6731 result.append(buffer);
6732 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6733 mDescriptor.name);
6734 result.append(buffer);
6735 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6736 mDescriptor.implementor);
6737 result.append(buffer);
6738
6739 result.append("\t\t- Input configuration:\n");
6740 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6741 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6742 (uint32_t)mConfig.inputCfg.buffer.raw,
6743 mConfig.inputCfg.buffer.frameCount,
6744 mConfig.inputCfg.samplingRate,
6745 mConfig.inputCfg.channels,
6746 mConfig.inputCfg.format);
6747 result.append(buffer);
6748
6749 result.append("\t\t- Output configuration:\n");
6750 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6751 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6752 (uint32_t)mConfig.outputCfg.buffer.raw,
6753 mConfig.outputCfg.buffer.frameCount,
6754 mConfig.outputCfg.samplingRate,
6755 mConfig.outputCfg.channels,
6756 mConfig.outputCfg.format);
6757 result.append(buffer);
6758
6759 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6760 result.append(buffer);
6761 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6762 for (size_t i = 0; i < mHandles.size(); ++i) {
6763 sp<EffectHandle> handle = mHandles[i].promote();
6764 if (handle != 0) {
6765 handle->dump(buffer, SIZE);
6766 result.append(buffer);
6767 }
6768 }
6769
6770 result.append("\n");
6771
6772 write(fd, result.string(), result.length());
6773
6774 if (locked) {
6775 mLock.unlock();
6776 }
6777
6778 return NO_ERROR;
6779}
6780
6781// ----------------------------------------------------------------------------
6782// EffectHandle implementation
6783// ----------------------------------------------------------------------------
6784
6785#undef LOG_TAG
6786#define LOG_TAG "AudioFlinger::EffectHandle"
6787
6788AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6789 const sp<AudioFlinger::Client>& client,
6790 const sp<IEffectClient>& effectClient,
6791 int32_t priority)
6792 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006793 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006794 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006795{
Steve Block3856b092011-10-20 11:56:00 +01006796 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006797
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006798 if (client == 0) {
6799 return;
6800 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6802 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6803 if (mCblkMemory != 0) {
6804 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6805
6806 if (mCblk) {
6807 new(mCblk) effect_param_cblk_t();
6808 mBuffer = (uint8_t *)mCblk + bufOffset;
6809 }
6810 } else {
6811 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6812 return;
6813 }
6814}
6815
6816AudioFlinger::EffectHandle::~EffectHandle()
6817{
Steve Block3856b092011-10-20 11:56:00 +01006818 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006819 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006820 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006821}
6822
6823status_t AudioFlinger::EffectHandle::enable()
6824{
Steve Block3856b092011-10-20 11:56:00 +01006825 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 if (!mHasControl) return INVALID_OPERATION;
6827 if (mEffect == 0) return DEAD_OBJECT;
6828
Eric Laurentdb7c0792011-08-10 10:37:50 -07006829 if (mEnabled) {
6830 return NO_ERROR;
6831 }
6832
Eric Laurent59255e42011-07-27 19:49:51 -07006833 mEnabled = true;
6834
6835 sp<ThreadBase> thread = mEffect->thread().promote();
6836 if (thread != 0) {
6837 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6838 }
6839
6840 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6841 if (mEffect->suspended()) {
6842 return NO_ERROR;
6843 }
6844
Eric Laurentdb7c0792011-08-10 10:37:50 -07006845 status_t status = mEffect->setEnabled(true);
6846 if (status != NO_ERROR) {
6847 if (thread != 0) {
6848 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6849 }
6850 mEnabled = false;
6851 }
6852 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853}
6854
6855status_t AudioFlinger::EffectHandle::disable()
6856{
Steve Block3856b092011-10-20 11:56:00 +01006857 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006859 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860
Eric Laurentdb7c0792011-08-10 10:37:50 -07006861 if (!mEnabled) {
6862 return NO_ERROR;
6863 }
Eric Laurent59255e42011-07-27 19:49:51 -07006864 mEnabled = false;
6865
6866 if (mEffect->suspended()) {
6867 return NO_ERROR;
6868 }
6869
6870 status_t status = mEffect->setEnabled(false);
6871
6872 sp<ThreadBase> thread = mEffect->thread().promote();
6873 if (thread != 0) {
6874 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6875 }
6876
6877 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006878}
6879
6880void AudioFlinger::EffectHandle::disconnect()
6881{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006882 disconnect(true);
6883}
6884
6885void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6886{
Steve Block3856b092011-10-20 11:56:00 +01006887 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006888 if (mEffect == 0) {
6889 return;
6890 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006891 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006892
Eric Laurenta85a74a2011-10-19 11:44:54 -07006893 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006894 sp<ThreadBase> thread = mEffect->thread().promote();
6895 if (thread != 0) {
6896 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6897 }
Eric Laurent59255e42011-07-27 19:49:51 -07006898 }
6899
Mathias Agopian65ab4712010-07-14 17:59:35 -07006900 // release sp on module => module destructor can be called now
6901 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006902 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006903 if (mCblk) {
6904 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6905 }
6906 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6908 mClient.clear();
6909 }
6910}
6911
Eric Laurent25f43952010-07-28 05:40:18 -07006912status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6913 uint32_t cmdSize,
6914 void *pCmdData,
6915 uint32_t *replySize,
6916 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006917{
Steve Block3856b092011-10-20 11:56:00 +01006918// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006919// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920
6921 // only get parameter command is permitted for applications not controlling the effect
6922 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6923 return INVALID_OPERATION;
6924 }
6925 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006926 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927
6928 // handle commands that are not forwarded transparently to effect engine
6929 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6930 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6931 // no risk to block the whole media server process or mixer threads is we are stuck here
6932 Mutex::Autolock _l(mCblk->lock);
6933 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6934 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6935 mCblk->serverIndex = 0;
6936 mCblk->clientIndex = 0;
6937 return BAD_VALUE;
6938 }
6939 status_t status = NO_ERROR;
6940 while (mCblk->serverIndex < mCblk->clientIndex) {
6941 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006942 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 int *p = (int *)(mBuffer + mCblk->serverIndex);
6944 int size = *p++;
6945 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6946 LOGW("command(): invalid parameter block size");
6947 break;
6948 }
6949 effect_param_t *param = (effect_param_t *)p;
6950 if (param->psize == 0 || param->vsize == 0) {
6951 LOGW("command(): null parameter or value size");
6952 mCblk->serverIndex += size;
6953 continue;
6954 }
Eric Laurent25f43952010-07-28 05:40:18 -07006955 uint32_t psize = sizeof(effect_param_t) +
6956 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6957 param->vsize;
6958 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6959 psize,
6960 p,
6961 &rsize,
6962 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006963 // stop at first error encountered
6964 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006965 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006966 *(int *)pReplyData = reply;
6967 break;
6968 } else if (reply != NO_ERROR) {
6969 *(int *)pReplyData = reply;
6970 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 }
6972 mCblk->serverIndex += size;
6973 }
6974 mCblk->serverIndex = 0;
6975 mCblk->clientIndex = 0;
6976 return status;
6977 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006978 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 return enable();
6980 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006981 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 return disable();
6983 }
6984
6985 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6986}
6987
6988sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6989 return mCblkMemory;
6990}
6991
Eric Laurent59255e42011-07-27 19:49:51 -07006992void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993{
Steve Block3856b092011-10-20 11:56:00 +01006994 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995
6996 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006997 mEnabled = enabled;
6998
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999 if (signal && mEffectClient != 0) {
7000 mEffectClient->controlStatusChanged(hasControl);
7001 }
7002}
7003
Eric Laurent25f43952010-07-28 05:40:18 -07007004void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7005 uint32_t cmdSize,
7006 void *pCmdData,
7007 uint32_t replySize,
7008 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009{
7010 if (mEffectClient != 0) {
7011 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7012 }
7013}
7014
7015
7016
7017void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7018{
7019 if (mEffectClient != 0) {
7020 mEffectClient->enableStatusChanged(enabled);
7021 }
7022}
7023
7024status_t AudioFlinger::EffectHandle::onTransact(
7025 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7026{
7027 return BnEffect::onTransact(code, data, reply, flags);
7028}
7029
7030
7031void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7032{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007033 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007034
7035 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7036 (mClient == NULL) ? getpid() : mClient->pid(),
7037 mPriority,
7038 mHasControl,
7039 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007040 mCblk ? mCblk->clientIndex : 0,
7041 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042 );
7043
7044 if (locked) {
7045 mCblk->lock.unlock();
7046 }
7047}
7048
7049#undef LOG_TAG
7050#define LOG_TAG "AudioFlinger::EffectChain"
7051
7052AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7053 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007054 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007055 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7056 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007057{
Dima Zavinfce7a472011-04-19 22:30:36 -07007058 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007059 sp<ThreadBase> thread = mThread.promote();
7060 if (thread == 0) {
7061 return;
7062 }
7063 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7064 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065}
7066
7067AudioFlinger::EffectChain::~EffectChain()
7068{
7069 if (mOwnInBuffer) {
7070 delete mInBuffer;
7071 }
7072
7073}
7074
Eric Laurent59255e42011-07-27 19:49:51 -07007075// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007076sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077{
7078 sp<EffectModule> effect;
7079 size_t size = mEffects.size();
7080
7081 for (size_t i = 0; i < size; i++) {
7082 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7083 effect = mEffects[i];
7084 break;
7085 }
7086 }
7087 return effect;
7088}
7089
Eric Laurent59255e42011-07-27 19:49:51 -07007090// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007091sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092{
7093 sp<EffectModule> effect;
7094 size_t size = mEffects.size();
7095
7096 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007097 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7098 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007099 effect = mEffects[i];
7100 break;
7101 }
7102 }
7103 return effect;
7104}
7105
Eric Laurent59255e42011-07-27 19:49:51 -07007106// getEffectFromType_l() must be called with ThreadBase::mLock held
7107sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7108 const effect_uuid_t *type)
7109{
7110 sp<EffectModule> effect;
7111 size_t size = mEffects.size();
7112
7113 for (size_t i = 0; i < size; i++) {
7114 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7115 effect = mEffects[i];
7116 break;
7117 }
7118 }
7119 return effect;
7120}
7121
Mathias Agopian65ab4712010-07-14 17:59:35 -07007122// Must be called with EffectChain::mLock locked
7123void AudioFlinger::EffectChain::process_l()
7124{
Eric Laurentdac69112010-09-28 14:09:57 -07007125 sp<ThreadBase> thread = mThread.promote();
7126 if (thread == 0) {
7127 LOGW("process_l(): cannot promote mixer thread");
7128 return;
7129 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007130 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7131 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007132 // always process effects unless no more tracks are on the session and the effect tail
7133 // has been rendered
7134 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007135 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007136 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007137
Eric Laurent544fe9b2011-11-11 15:42:52 -08007138 if (!tracksOnSession && mTailBufferCount == 0) {
7139 doProcess = false;
7140 }
7141
7142 if (activeTrackCnt() == 0) {
7143 // if no track is active and the effect tail has not been rendered,
7144 // the input buffer must be cleared here as the mixer process will not do it
7145 if (tracksOnSession || mTailBufferCount > 0) {
7146 size_t numSamples = thread->frameCount() * thread->channelCount();
7147 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7148 if (mTailBufferCount > 0) {
7149 mTailBufferCount--;
7150 }
7151 }
7152 }
Eric Laurentdac69112010-09-28 14:09:57 -07007153 }
7154
Mathias Agopian65ab4712010-07-14 17:59:35 -07007155 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007156 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007157 for (size_t i = 0; i < size; i++) {
7158 mEffects[i]->process();
7159 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 }
7161 for (size_t i = 0; i < size; i++) {
7162 mEffects[i]->updateState();
7163 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007164}
7165
Eric Laurentcab11242010-07-15 12:50:15 -07007166// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007167status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168{
7169 effect_descriptor_t desc = effect->desc();
7170 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7171
7172 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007173 effect->setChain(this);
7174 sp<ThreadBase> thread = mThread.promote();
7175 if (thread == 0) {
7176 return NO_INIT;
7177 }
7178 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179
7180 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7181 // Auxiliary effects are inserted at the beginning of mEffects vector as
7182 // they are processed first and accumulated in chain input buffer
7183 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007184
Mathias Agopian65ab4712010-07-14 17:59:35 -07007185 // the input buffer for auxiliary effect contains mono samples in
7186 // 32 bit format. This is to avoid saturation in AudoMixer
7187 // accumulation stage. Saturation is done in EffectModule::process() before
7188 // calling the process in effect engine
7189 size_t numSamples = thread->frameCount();
7190 int32_t *buffer = new int32_t[numSamples];
7191 memset(buffer, 0, numSamples * sizeof(int32_t));
7192 effect->setInBuffer((int16_t *)buffer);
7193 // auxiliary effects output samples to chain input buffer for further processing
7194 // by insert effects
7195 effect->setOutBuffer(mInBuffer);
7196 } else {
7197 // Insert effects are inserted at the end of mEffects vector as they are processed
7198 // after track and auxiliary effects.
7199 // Insert effect order as a function of indicated preference:
7200 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7201 // another effect is present
7202 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7203 // last effect claiming first position
7204 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7205 // first effect claiming last position
7206 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7207 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7208 // already present
7209
7210 int size = (int)mEffects.size();
7211 int idx_insert = size;
7212 int idx_insert_first = -1;
7213 int idx_insert_last = -1;
7214
7215 for (int i = 0; i < size; i++) {
7216 effect_descriptor_t d = mEffects[i]->desc();
7217 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7218 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7219 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7220 // check invalid effect chaining combinations
7221 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7222 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007223 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007224 return INVALID_OPERATION;
7225 }
7226 // remember position of first insert effect and by default
7227 // select this as insert position for new effect
7228 if (idx_insert == size) {
7229 idx_insert = i;
7230 }
7231 // remember position of last insert effect claiming
7232 // first position
7233 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7234 idx_insert_first = i;
7235 }
7236 // remember position of first insert effect claiming
7237 // last position
7238 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7239 idx_insert_last == -1) {
7240 idx_insert_last = i;
7241 }
7242 }
7243 }
7244
7245 // modify idx_insert from first position if needed
7246 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7247 if (idx_insert_last != -1) {
7248 idx_insert = idx_insert_last;
7249 } else {
7250 idx_insert = size;
7251 }
7252 } else {
7253 if (idx_insert_first != -1) {
7254 idx_insert = idx_insert_first + 1;
7255 }
7256 }
7257
7258 // always read samples from chain input buffer
7259 effect->setInBuffer(mInBuffer);
7260
7261 // if last effect in the chain, output samples to chain
7262 // output buffer, otherwise to chain input buffer
7263 if (idx_insert == size) {
7264 if (idx_insert != 0) {
7265 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7266 mEffects[idx_insert-1]->configure();
7267 }
7268 effect->setOutBuffer(mOutBuffer);
7269 } else {
7270 effect->setOutBuffer(mInBuffer);
7271 }
7272 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007273
Steve Block3856b092011-10-20 11:56:00 +01007274 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007275 }
7276 effect->configure();
7277 return NO_ERROR;
7278}
7279
Eric Laurentcab11242010-07-15 12:50:15 -07007280// removeEffect_l() must be called with PlaybackThread::mLock held
7281size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282{
7283 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284 int size = (int)mEffects.size();
7285 int i;
7286 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7287
7288 for (i = 0; i < size; i++) {
7289 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007290 // calling stop here will remove pre-processing effect from the audio HAL.
7291 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7292 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007293 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7294 mEffects[i]->state() == EffectModule::STOPPING) {
7295 mEffects[i]->stop();
7296 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7298 delete[] effect->inBuffer();
7299 } else {
7300 if (i == size - 1 && i != 0) {
7301 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7302 mEffects[i - 1]->configure();
7303 }
7304 }
7305 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007306 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 break;
7308 }
7309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310
7311 return mEffects.size();
7312}
7313
Eric Laurentcab11242010-07-15 12:50:15 -07007314// setDevice_l() must be called with PlaybackThread::mLock held
7315void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007316{
7317 size_t size = mEffects.size();
7318 for (size_t i = 0; i < size; i++) {
7319 mEffects[i]->setDevice(device);
7320 }
7321}
7322
Eric Laurentcab11242010-07-15 12:50:15 -07007323// setMode_l() must be called with PlaybackThread::mLock held
7324void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007325{
7326 size_t size = mEffects.size();
7327 for (size_t i = 0; i < size; i++) {
7328 mEffects[i]->setMode(mode);
7329 }
7330}
7331
Eric Laurentcab11242010-07-15 12:50:15 -07007332// setVolume_l() must be called with PlaybackThread::mLock held
7333bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334{
7335 uint32_t newLeft = *left;
7336 uint32_t newRight = *right;
7337 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007338 int ctrlIdx = -1;
7339 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007340
Eric Laurentcab11242010-07-15 12:50:15 -07007341 // first update volume controller
7342 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007343 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007344 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7345 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007346 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007347 break;
7348 }
7349 }
7350
7351 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007352 if (hasControl) {
7353 *left = mNewLeftVolume;
7354 *right = mNewRightVolume;
7355 }
7356 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007357 }
7358
7359 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007360 mLeftVolume = newLeft;
7361 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007362
7363 // second get volume update from volume controller
7364 if (ctrlIdx >= 0) {
7365 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007366 mNewLeftVolume = newLeft;
7367 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007368 }
7369 // then indicate volume to all other effects in chain.
7370 // Pass altered volume to effects before volume controller
7371 // and requested volume to effects after controller
7372 uint32_t lVol = newLeft;
7373 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007374
Mathias Agopian65ab4712010-07-14 17:59:35 -07007375 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007376 if ((int)i == ctrlIdx) continue;
7377 // this also works for ctrlIdx == -1 when there is no volume controller
7378 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 lVol = *left;
7380 rVol = *right;
7381 }
7382 mEffects[i]->setVolume(&lVol, &rVol, false);
7383 }
7384 *left = newLeft;
7385 *right = newRight;
7386
7387 return hasControl;
7388}
7389
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7391{
7392 const size_t SIZE = 256;
7393 char buffer[SIZE];
7394 String8 result;
7395
7396 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7397 result.append(buffer);
7398
7399 bool locked = tryLock(mLock);
7400 // failed to lock - AudioFlinger is probably deadlocked
7401 if (!locked) {
7402 result.append("\tCould not lock mutex:\n");
7403 }
7404
Eric Laurentcab11242010-07-15 12:50:15 -07007405 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7406 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007407 mEffects.size(),
7408 (uint32_t)mInBuffer,
7409 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007410 mActiveTrackCnt);
7411 result.append(buffer);
7412 write(fd, result.string(), result.size());
7413
7414 for (size_t i = 0; i < mEffects.size(); ++i) {
7415 sp<EffectModule> effect = mEffects[i];
7416 if (effect != 0) {
7417 effect->dump(fd, args);
7418 }
7419 }
7420
7421 if (locked) {
7422 mLock.unlock();
7423 }
7424
7425 return NO_ERROR;
7426}
7427
Eric Laurent59255e42011-07-27 19:49:51 -07007428// must be called with ThreadBase::mLock held
7429void AudioFlinger::EffectChain::setEffectSuspended_l(
7430 const effect_uuid_t *type, bool suspend)
7431{
7432 sp<SuspendedEffectDesc> desc;
7433 // use effect type UUID timelow as key as there is no real risk of identical
7434 // timeLow fields among effect type UUIDs.
7435 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7436 if (suspend) {
7437 if (index >= 0) {
7438 desc = mSuspendedEffects.valueAt(index);
7439 } else {
7440 desc = new SuspendedEffectDesc();
7441 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7442 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007443 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007444 }
7445 if (desc->mRefCount++ == 0) {
7446 sp<EffectModule> effect = getEffectIfEnabled(type);
7447 if (effect != 0) {
7448 desc->mEffect = effect;
7449 effect->setSuspended(true);
7450 effect->setEnabled(false);
7451 }
7452 }
7453 } else {
7454 if (index < 0) {
7455 return;
7456 }
7457 desc = mSuspendedEffects.valueAt(index);
7458 if (desc->mRefCount <= 0) {
7459 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7460 desc->mRefCount = 1;
7461 }
7462 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007463 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007464 if (desc->mEffect != 0) {
7465 sp<EffectModule> effect = desc->mEffect.promote();
7466 if (effect != 0) {
7467 effect->setSuspended(false);
7468 sp<EffectHandle> handle = effect->controlHandle();
7469 if (handle != 0) {
7470 effect->setEnabled(handle->enabled());
7471 }
7472 }
7473 desc->mEffect.clear();
7474 }
7475 mSuspendedEffects.removeItemsAt(index);
7476 }
7477 }
7478}
7479
7480// must be called with ThreadBase::mLock held
7481void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7482{
7483 sp<SuspendedEffectDesc> desc;
7484
7485 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7486 if (suspend) {
7487 if (index >= 0) {
7488 desc = mSuspendedEffects.valueAt(index);
7489 } else {
7490 desc = new SuspendedEffectDesc();
7491 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007492 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007493 }
7494 if (desc->mRefCount++ == 0) {
7495 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7496 for (size_t i = 0; i < effects.size(); i++) {
7497 setEffectSuspended_l(&effects[i]->desc().type, true);
7498 }
7499 }
7500 } else {
7501 if (index < 0) {
7502 return;
7503 }
7504 desc = mSuspendedEffects.valueAt(index);
7505 if (desc->mRefCount <= 0) {
7506 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7507 desc->mRefCount = 1;
7508 }
7509 if (--desc->mRefCount == 0) {
7510 Vector<const effect_uuid_t *> types;
7511 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7512 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7513 continue;
7514 }
7515 types.add(&mSuspendedEffects.valueAt(i)->mType);
7516 }
7517 for (size_t i = 0; i < types.size(); i++) {
7518 setEffectSuspended_l(types[i], false);
7519 }
Steve Block3856b092011-10-20 11:56:00 +01007520 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007521 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7522 }
7523 }
7524}
7525
Eric Laurent6bffdb82011-09-23 08:40:41 -07007526
7527// The volume effect is used for automated tests only
7528#ifndef OPENSL_ES_H_
7529static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7530 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7531const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7532#endif //OPENSL_ES_H_
7533
Eric Laurentdb7c0792011-08-10 10:37:50 -07007534bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7535{
7536 // auxiliary effects and visualizer are never suspended on output mix
7537 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7538 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007539 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7540 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007541 return false;
7542 }
7543 return true;
7544}
7545
Eric Laurent59255e42011-07-27 19:49:51 -07007546Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7547{
7548 Vector< sp<EffectModule> > effects;
7549 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007550 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007551 continue;
7552 }
7553 effects.add(mEffects[i]);
7554 }
7555 return effects;
7556}
7557
7558sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7559 const effect_uuid_t *type)
7560{
7561 sp<EffectModule> effect;
7562 effect = getEffectFromType_l(type);
7563 if (effect != 0 && !effect->isEnabled()) {
7564 effect.clear();
7565 }
7566 return effect;
7567}
7568
7569void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7570 bool enabled)
7571{
7572 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7573 if (enabled) {
7574 if (index < 0) {
7575 // if the effect is not suspend check if all effects are suspended
7576 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7577 if (index < 0) {
7578 return;
7579 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007580 if (!isEffectEligibleForSuspend(effect->desc())) {
7581 return;
7582 }
Eric Laurent59255e42011-07-27 19:49:51 -07007583 setEffectSuspended_l(&effect->desc().type, enabled);
7584 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007585 if (index < 0) {
7586 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7587 return;
7588 }
Eric Laurent59255e42011-07-27 19:49:51 -07007589 }
Steve Block3856b092011-10-20 11:56:00 +01007590 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007591 effect->desc().type.timeLow);
7592 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7593 // if effect is requested to suspended but was not yet enabled, supend it now.
7594 if (desc->mEffect == 0) {
7595 desc->mEffect = effect;
7596 effect->setEnabled(false);
7597 effect->setSuspended(true);
7598 }
7599 } else {
7600 if (index < 0) {
7601 return;
7602 }
Steve Block3856b092011-10-20 11:56:00 +01007603 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007604 effect->desc().type.timeLow);
7605 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7606 desc->mEffect.clear();
7607 effect->setSuspended(false);
7608 }
7609}
7610
Mathias Agopian65ab4712010-07-14 17:59:35 -07007611#undef LOG_TAG
7612#define LOG_TAG "AudioFlinger"
7613
7614// ----------------------------------------------------------------------------
7615
7616status_t AudioFlinger::onTransact(
7617 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7618{
7619 return BnAudioFlinger::onTransact(code, data, reply, flags);
7620}
7621
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622}; // namespace android