blob: 133dabdfc5d8412e3ec4c71f8a4d052d75a5be04 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
38
39#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
Mathias Agopian65ab4712010-07-14 17:59:35 -070061// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070062
Eric Laurentde070132010-07-13 04:45:46 -070063
Mathias Agopian65ab4712010-07-14 17:59:35 -070064namespace android {
65
66static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
67static const char* kHardwareLockedString = "Hardware lock is taken\n";
68
69//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
70static const float MAX_GAIN = 4096.0f;
71static const float MAX_GAIN_INT = 0x1000;
72
73// retry counts for buffer fill timeout
74// 50 * ~20msecs = 1 second
75static const int8_t kMaxTrackRetries = 50;
76static const int8_t kMaxTrackStartupRetries = 50;
77// allow less retry attempts on direct output thread.
78// direct outputs can be a scarce resource in audio hardware and should
79// be released as quickly as possible.
80static const int8_t kMaxTrackRetriesDirect = 2;
81
82static const int kDumpLockRetries = 50;
83static const int kDumpLockSleep = 20000;
84
85static const nsecs_t kWarningThrottle = seconds(5);
86
Eric Laurent7c7f10b2011-06-17 21:29:58 -070087// RecordThread loop sleep time upon application overrun or audio HAL read error
88static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Eric Laurent60cd0a02011-09-13 11:40:21 -070090static const nsecs_t kSetParametersTimeout = seconds(2);
91
Eric Laurent7cafbb32011-11-22 18:50:29 -080092// minimum sleep time for the mixer thread loop when tracks are active but in underrun
93static const uint32_t kMinThreadSleepTimeUs = 5000;
94// maximum divider applied to the active sleep time in the mixer thread loop
95static const uint32_t kMaxThreadSleepTimeShift = 2;
96
97
Mathias Agopian65ab4712010-07-14 17:59:35 -070098// ----------------------------------------------------------------------------
99
100static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
102 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
103 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
104 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105}
106
107static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
109 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
110 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
111 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112}
113
Gloria Wang9ee159b2011-02-24 14:51:45 -0800114// To collect the amplifier usage
115static void addBatteryData(uint32_t params) {
116 sp<IBinder> binder =
117 defaultServiceManager()->getService(String16("media.player"));
118 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
119 if (service.get() == NULL) {
120 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
121 return;
122 }
123
124 service->addBatteryData(params);
125}
126
Dima Zavin799a70e2011-04-18 16:57:27 -0700127static int load_audio_interface(const char *if_name, const hw_module_t **mod,
128 audio_hw_device_t **dev)
129{
130 int rc;
131
132 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
133 if (rc)
134 goto out;
135
136 rc = audio_hw_device_open(*mod, dev);
137 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
138 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
139 if (rc)
140 goto out;
141
142 return 0;
143
144out:
145 *mod = NULL;
146 *dev = NULL;
147 return rc;
148}
149
150static const char *audio_interfaces[] = {
151 "primary",
152 "a2dp",
153 "usb",
154};
155#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
156
Mathias Agopian65ab4712010-07-14 17:59:35 -0700157// ----------------------------------------------------------------------------
158
159AudioFlinger::AudioFlinger()
160 : BnAudioFlinger(),
Eric Laurent59bd0da2011-08-01 09:52:20 -0700161 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700162 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700163{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700164}
165
166void AudioFlinger::onFirstRef()
167{
Dima Zavin799a70e2011-04-18 16:57:27 -0700168 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700169
Eric Laurent93575202011-01-18 18:39:02 -0800170 Mutex::Autolock _l(mLock);
171
Dima Zavin799a70e2011-04-18 16:57:27 -0700172 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700173 mHardwareStatus = AUDIO_HW_IDLE;
174
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
176 const hw_module_t *mod;
177 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
180 if (rc)
181 continue;
182
183 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
184 mod->name, mod->id);
185 mAudioHwDevs.push(dev);
186
187 if (!mPrimaryHardwareDev) {
188 mPrimaryHardwareDev = dev;
189 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700190 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700191 }
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193
194 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700195
Dima Zavin799a70e2011-04-18 16:57:27 -0700196 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
197 LOGE("Primary audio interface not found");
198 return;
199 }
200
201 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
202 audio_hw_device_t *dev = mAudioHwDevs[i];
203
204 mHardwareStatus = AUDIO_HW_INIT;
205 rc = dev->init_check(dev);
206 if (rc == 0) {
207 AutoMutex lock(mHardwareLock);
208
209 mMode = AUDIO_MODE_NORMAL;
210 mHardwareStatus = AUDIO_HW_SET_MODE;
211 dev->set_mode(dev, mMode);
212 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
213 dev->set_master_volume(dev, 1.0f);
214 mHardwareStatus = AUDIO_HW_IDLE;
215 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217}
218
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700219status_t AudioFlinger::initCheck() const
220{
221 Mutex::Autolock _l(mLock);
222 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
223 return NO_INIT;
224 return NO_ERROR;
225}
226
Mathias Agopian65ab4712010-07-14 17:59:35 -0700227AudioFlinger::~AudioFlinger()
228{
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 int num_devs = mAudioHwDevs.size();
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231 while (!mRecordThreads.isEmpty()) {
232 // closeInput() will remove first entry from mRecordThreads
233 closeInput(mRecordThreads.keyAt(0));
234 }
235 while (!mPlaybackThreads.isEmpty()) {
236 // closeOutput() will remove first entry from mPlaybackThreads
237 closeOutput(mPlaybackThreads.keyAt(0));
238 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700239
240 for (int i = 0; i < num_devs; i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700244 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245}
246
Dima Zavin799a70e2011-04-18 16:57:27 -0700247audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
248{
249 /* first matching HW device is returned */
250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
251 audio_hw_device_t *dev = mAudioHwDevs[i];
252 if ((dev->get_supported_devices(dev) & devices) == devices)
253 return dev;
254 }
255 return NULL;
256}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257
258status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
259{
260 const size_t SIZE = 256;
261 char buffer[SIZE];
262 String8 result;
263
264 result.append("Clients:\n");
265 for (size_t i = 0; i < mClients.size(); ++i) {
266 wp<Client> wClient = mClients.valueAt(i);
267 if (wClient != 0) {
268 sp<Client> client = wClient.promote();
269 if (client != 0) {
270 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
271 result.append(buffer);
272 }
273 }
274 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700275
276 result.append("Global session refs:\n");
277 result.append(" session pid cnt\n");
278 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
279 AudioSessionRef *r = mAudioSessionRefs[i];
280 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
281 result.append(buffer);
282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700283 write(fd, result.string(), result.size());
284 return NO_ERROR;
285}
286
287
288status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
289{
290 const size_t SIZE = 256;
291 char buffer[SIZE];
292 String8 result;
293 int hardwareStatus = mHardwareStatus;
294
295 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
296 result.append(buffer);
297 write(fd, result.string(), result.size());
298 return NO_ERROR;
299}
300
301status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
302{
303 const size_t SIZE = 256;
304 char buffer[SIZE];
305 String8 result;
306 snprintf(buffer, SIZE, "Permission Denial: "
307 "can't dump AudioFlinger from pid=%d, uid=%d\n",
308 IPCThreadState::self()->getCallingPid(),
309 IPCThreadState::self()->getCallingUid());
310 result.append(buffer);
311 write(fd, result.string(), result.size());
312 return NO_ERROR;
313}
314
315static bool tryLock(Mutex& mutex)
316{
317 bool locked = false;
318 for (int i = 0; i < kDumpLockRetries; ++i) {
319 if (mutex.tryLock() == NO_ERROR) {
320 locked = true;
321 break;
322 }
323 usleep(kDumpLockSleep);
324 }
325 return locked;
326}
327
328status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
329{
330 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
331 dumpPermissionDenial(fd, args);
332 } else {
333 // get state of hardware lock
334 bool hardwareLocked = tryLock(mHardwareLock);
335 if (!hardwareLocked) {
336 String8 result(kHardwareLockedString);
337 write(fd, result.string(), result.size());
338 } else {
339 mHardwareLock.unlock();
340 }
341
342 bool locked = tryLock(mLock);
343
344 // failed to lock - AudioFlinger is probably deadlocked
345 if (!locked) {
346 String8 result(kDeadlockedString);
347 write(fd, result.string(), result.size());
348 }
349
350 dumpClients(fd, args);
351 dumpInternals(fd, args);
352
353 // dump playback threads
354 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
355 mPlaybackThreads.valueAt(i)->dump(fd, args);
356 }
357
358 // dump record threads
359 for (size_t i = 0; i < mRecordThreads.size(); i++) {
360 mRecordThreads.valueAt(i)->dump(fd, args);
361 }
362
Dima Zavin799a70e2011-04-18 16:57:27 -0700363 // dump all hardware devs
364 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
365 audio_hw_device_t *dev = mAudioHwDevs[i];
366 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367 }
368 if (locked) mLock.unlock();
369 }
370 return NO_ERROR;
371}
372
373
374// IAudioFlinger interface
375
376
377sp<IAudioTrack> AudioFlinger::createTrack(
378 pid_t pid,
379 int streamType,
380 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700381 uint32_t format,
382 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700383 int frameCount,
384 uint32_t flags,
385 const sp<IMemory>& sharedBuffer,
386 int output,
387 int *sessionId,
388 status_t *status)
389{
390 sp<PlaybackThread::Track> track;
391 sp<TrackHandle> trackHandle;
392 sp<Client> client;
393 wp<Client> wclient;
394 status_t lStatus;
395 int lSessionId;
396
Dima Zavinfce7a472011-04-19 22:30:36 -0700397 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700398 LOGE("invalid stream type");
399 lStatus = BAD_VALUE;
400 goto Exit;
401 }
402
403 {
404 Mutex::Autolock _l(mLock);
405 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700406 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700407 if (thread == NULL) {
408 LOGE("unknown output thread");
409 lStatus = BAD_VALUE;
410 goto Exit;
411 }
412
413 wclient = mClients.valueFor(pid);
414
415 if (wclient != NULL) {
416 client = wclient.promote();
417 } else {
418 client = new Client(this, pid);
419 mClients.add(pid, client);
420 }
421
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700423 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700424 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700425 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
426 if (mPlaybackThreads.keyAt(i) != output) {
427 // prevent same audio session on different output threads
428 uint32_t sessions = t->hasAudioSession(*sessionId);
429 if (sessions & PlaybackThread::TRACK_SESSION) {
430 lStatus = BAD_VALUE;
431 goto Exit;
432 }
433 // check if an effect with same session ID is waiting for a track to be created
434 if (sessions & PlaybackThread::EFFECT_SESSION) {
435 effectThread = t.get();
436 }
Eric Laurentde070132010-07-13 04:45:46 -0700437 }
438 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 lSessionId = *sessionId;
440 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700441 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700442 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700443 if (sessionId != NULL) {
444 *sessionId = lSessionId;
445 }
446 }
447 LOGV("createTrack() lSessionId: %d", lSessionId);
448
449 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700450 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700451
452 // move effect chain to this output thread if an effect on same session was waiting
453 // for a track to be created
454 if (lStatus == NO_ERROR && effectThread != NULL) {
455 Mutex::Autolock _dl(thread->mLock);
456 Mutex::Autolock _sl(effectThread->mLock);
457 moveEffectChain_l(lSessionId, effectThread, thread, true);
458 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 }
460 if (lStatus == NO_ERROR) {
461 trackHandle = new TrackHandle(track);
462 } else {
463 // remove local strong reference to Client before deleting the Track so that the Client
464 // destructor is called by the TrackBase destructor with mLock held
465 client.clear();
466 track.clear();
467 }
468
469Exit:
470 if(status) {
471 *status = lStatus;
472 }
473 return trackHandle;
474}
475
476uint32_t AudioFlinger::sampleRate(int output) const
477{
478 Mutex::Autolock _l(mLock);
479 PlaybackThread *thread = checkPlaybackThread_l(output);
480 if (thread == NULL) {
481 LOGW("sampleRate() unknown thread %d", output);
482 return 0;
483 }
484 return thread->sampleRate();
485}
486
487int AudioFlinger::channelCount(int output) const
488{
489 Mutex::Autolock _l(mLock);
490 PlaybackThread *thread = checkPlaybackThread_l(output);
491 if (thread == NULL) {
492 LOGW("channelCount() unknown thread %d", output);
493 return 0;
494 }
495 return thread->channelCount();
496}
497
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700498uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700499{
500 Mutex::Autolock _l(mLock);
501 PlaybackThread *thread = checkPlaybackThread_l(output);
502 if (thread == NULL) {
503 LOGW("format() unknown thread %d", output);
504 return 0;
505 }
506 return thread->format();
507}
508
509size_t AudioFlinger::frameCount(int output) const
510{
511 Mutex::Autolock _l(mLock);
512 PlaybackThread *thread = checkPlaybackThread_l(output);
513 if (thread == NULL) {
514 LOGW("frameCount() unknown thread %d", output);
515 return 0;
516 }
517 return thread->frameCount();
518}
519
520uint32_t AudioFlinger::latency(int output) const
521{
522 Mutex::Autolock _l(mLock);
523 PlaybackThread *thread = checkPlaybackThread_l(output);
524 if (thread == NULL) {
525 LOGW("latency() unknown thread %d", output);
526 return 0;
527 }
528 return thread->latency();
529}
530
531status_t AudioFlinger::setMasterVolume(float value)
532{
Eric Laurenta1884f92011-08-23 08:25:03 -0700533 status_t ret = initCheck();
534 if (ret != NO_ERROR) {
535 return ret;
536 }
537
Mathias Agopian65ab4712010-07-14 17:59:35 -0700538 // check calling permissions
539 if (!settingsAllowed()) {
540 return PERMISSION_DENIED;
541 }
542
543 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800544 { // scope for the lock
545 AutoMutex lock(mHardwareLock);
546 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700547 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800548 value = 1.0f;
549 }
550 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700551 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552
Eric Laurent93575202011-01-18 18:39:02 -0800553 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 mMasterVolume = value;
555 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
556 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
557
558 return NO_ERROR;
559}
560
561status_t AudioFlinger::setMode(int mode)
562{
Eric Laurenta1884f92011-08-23 08:25:03 -0700563 status_t ret = initCheck();
564 if (ret != NO_ERROR) {
565 return ret;
566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700567
568 // check calling permissions
569 if (!settingsAllowed()) {
570 return PERMISSION_DENIED;
571 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700572 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 LOGW("Illegal value: setMode(%d)", mode);
574 return BAD_VALUE;
575 }
576
577 { // scope for the lock
578 AutoMutex lock(mHardwareLock);
579 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700580 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700581 mHardwareStatus = AUDIO_HW_IDLE;
582 }
583
584 if (NO_ERROR == ret) {
585 Mutex::Autolock _l(mLock);
586 mMode = mode;
587 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
588 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700589 }
590
591 return ret;
592}
593
594status_t AudioFlinger::setMicMute(bool state)
595{
Eric Laurenta1884f92011-08-23 08:25:03 -0700596 status_t ret = initCheck();
597 if (ret != NO_ERROR) {
598 return ret;
599 }
600
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 // check calling permissions
602 if (!settingsAllowed()) {
603 return PERMISSION_DENIED;
604 }
605
606 AutoMutex lock(mHardwareLock);
607 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700608 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 mHardwareStatus = AUDIO_HW_IDLE;
610 return ret;
611}
612
613bool AudioFlinger::getMicMute() const
614{
Eric Laurenta1884f92011-08-23 08:25:03 -0700615 status_t ret = initCheck();
616 if (ret != NO_ERROR) {
617 return false;
618 }
619
Dima Zavinfce7a472011-04-19 22:30:36 -0700620 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700621 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700622 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 mHardwareStatus = AUDIO_HW_IDLE;
624 return state;
625}
626
627status_t AudioFlinger::setMasterMute(bool muted)
628{
629 // check calling permissions
630 if (!settingsAllowed()) {
631 return PERMISSION_DENIED;
632 }
633
Eric Laurent93575202011-01-18 18:39:02 -0800634 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 mMasterMute = muted;
636 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
637 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
638
639 return NO_ERROR;
640}
641
642float AudioFlinger::masterVolume() const
643{
644 return mMasterVolume;
645}
646
647bool AudioFlinger::masterMute() const
648{
649 return mMasterMute;
650}
651
652status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
653{
654 // check calling permissions
655 if (!settingsAllowed()) {
656 return PERMISSION_DENIED;
657 }
658
Dima Zavinfce7a472011-04-19 22:30:36 -0700659 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 return BAD_VALUE;
661 }
662
663 AutoMutex lock(mLock);
664 PlaybackThread *thread = NULL;
665 if (output) {
666 thread = checkPlaybackThread_l(output);
667 if (thread == NULL) {
668 return BAD_VALUE;
669 }
670 }
671
672 mStreamTypes[stream].volume = value;
673
674 if (thread == NULL) {
675 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
676 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
677 }
678 } else {
679 thread->setStreamVolume(stream, value);
680 }
681
682 return NO_ERROR;
683}
684
685status_t AudioFlinger::setStreamMute(int stream, bool muted)
686{
687 // check calling permissions
688 if (!settingsAllowed()) {
689 return PERMISSION_DENIED;
690 }
691
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
693 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700694 return BAD_VALUE;
695 }
696
Eric Laurent93575202011-01-18 18:39:02 -0800697 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698 mStreamTypes[stream].mute = muted;
699 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
700 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
701
702 return NO_ERROR;
703}
704
705float AudioFlinger::streamVolume(int stream, int output) const
706{
Dima Zavinfce7a472011-04-19 22:30:36 -0700707 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 return 0.0f;
709 }
710
711 AutoMutex lock(mLock);
712 float volume;
713 if (output) {
714 PlaybackThread *thread = checkPlaybackThread_l(output);
715 if (thread == NULL) {
716 return 0.0f;
717 }
718 volume = thread->streamVolume(stream);
719 } else {
720 volume = mStreamTypes[stream].volume;
721 }
722
723 return volume;
724}
725
726bool AudioFlinger::streamMute(int stream) const
727{
Dima Zavinfce7a472011-04-19 22:30:36 -0700728 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700729 return true;
730 }
731
732 return mStreamTypes[stream].mute;
733}
734
Mathias Agopian65ab4712010-07-14 17:59:35 -0700735status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
736{
737 status_t result;
738
739 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
740 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
741 // check calling permissions
742 if (!settingsAllowed()) {
743 return PERMISSION_DENIED;
744 }
745
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 // ioHandle == 0 means the parameters are global to the audio hardware interface
747 if (ioHandle == 0) {
748 AutoMutex lock(mHardwareLock);
749 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700750 status_t final_result = NO_ERROR;
751 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
752 audio_hw_device_t *dev = mAudioHwDevs[i];
753 result = dev->set_parameters(dev, keyValuePairs.string());
754 final_result = result ?: final_result;
755 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700757 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
758 AudioParameter param = AudioParameter(keyValuePairs);
759 String8 value;
760 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
761 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700762 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
763 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700764 for (size_t i = 0; i < mRecordThreads.size(); i++) {
765 sp<RecordThread> thread = mRecordThreads.valueAt(i);
766 RecordThread::RecordTrack *track = thread->track();
767 if (track != NULL) {
768 audio_devices_t device = (audio_devices_t)(
769 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700770 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700771 thread->setEffectSuspended(FX_IID_AEC,
772 suspend,
773 track->sessionId());
774 thread->setEffectSuspended(FX_IID_NS,
775 suspend,
776 track->sessionId());
777 }
778 }
Eric Laurentbee53372011-08-29 12:42:48 -0700779 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700780 }
781 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700782 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700783 }
784
785 // hold a strong ref on thread in case closeOutput() or closeInput() is called
786 // and the thread is exited once the lock is released
787 sp<ThreadBase> thread;
788 {
789 Mutex::Autolock _l(mLock);
790 thread = checkPlaybackThread_l(ioHandle);
791 if (thread == NULL) {
792 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700793 } else if (thread.get() == primaryPlaybackThread_l()) {
794 // indicate output device change to all input threads for pre processing
795 AudioParameter param = AudioParameter(keyValuePairs);
796 int value;
797 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
798 for (size_t i = 0; i < mRecordThreads.size(); i++) {
799 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
800 }
801 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700802 }
803 }
804 if (thread != NULL) {
805 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700806 return result;
807 }
808 return BAD_VALUE;
809}
810
811String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
812{
813// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
814// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
815
816 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700817 String8 out_s8;
818
Dima Zavin799a70e2011-04-18 16:57:27 -0700819 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
820 audio_hw_device_t *dev = mAudioHwDevs[i];
821 char *s = dev->get_parameters(dev, keys.string());
822 out_s8 += String8(s);
823 free(s);
824 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700825 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700826 }
827
828 Mutex::Autolock _l(mLock);
829
830 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
831 if (playbackThread != NULL) {
832 return playbackThread->getParameters(keys);
833 }
834 RecordThread *recordThread = checkRecordThread_l(ioHandle);
835 if (recordThread != NULL) {
836 return recordThread->getParameters(keys);
837 }
838 return String8("");
839}
840
841size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
842{
Eric Laurenta1884f92011-08-23 08:25:03 -0700843 status_t ret = initCheck();
844 if (ret != NO_ERROR) {
845 return 0;
846 }
847
Dima Zavin799a70e2011-04-18 16:57:27 -0700848 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700849}
850
851unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
852{
853 if (ioHandle == 0) {
854 return 0;
855 }
856
857 Mutex::Autolock _l(mLock);
858
859 RecordThread *recordThread = checkRecordThread_l(ioHandle);
860 if (recordThread != NULL) {
861 return recordThread->getInputFramesLost();
862 }
863 return 0;
864}
865
866status_t AudioFlinger::setVoiceVolume(float value)
867{
Eric Laurenta1884f92011-08-23 08:25:03 -0700868 status_t ret = initCheck();
869 if (ret != NO_ERROR) {
870 return ret;
871 }
872
Mathias Agopian65ab4712010-07-14 17:59:35 -0700873 // check calling permissions
874 if (!settingsAllowed()) {
875 return PERMISSION_DENIED;
876 }
877
878 AutoMutex lock(mHardwareLock);
879 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700880 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 mHardwareStatus = AUDIO_HW_IDLE;
882
883 return ret;
884}
885
886status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
887{
888 status_t status;
889
890 Mutex::Autolock _l(mLock);
891
892 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
893 if (playbackThread != NULL) {
894 return playbackThread->getRenderPosition(halFrames, dspFrames);
895 }
896
897 return BAD_VALUE;
898}
899
900void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
901{
902
903 Mutex::Autolock _l(mLock);
904
905 int pid = IPCThreadState::self()->getCallingPid();
906 if (mNotificationClients.indexOfKey(pid) < 0) {
907 sp<NotificationClient> notificationClient = new NotificationClient(this,
908 client,
909 pid);
910 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
911
912 mNotificationClients.add(pid, notificationClient);
913
914 sp<IBinder> binder = client->asBinder();
915 binder->linkToDeath(notificationClient);
916
917 // the config change is always sent from playback or record threads to avoid deadlock
918 // with AudioSystem::gLock
919 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
920 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
921 }
922
923 for (size_t i = 0; i < mRecordThreads.size(); i++) {
924 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
925 }
926 }
927}
928
929void AudioFlinger::removeNotificationClient(pid_t pid)
930{
931 Mutex::Autolock _l(mLock);
932
933 int index = mNotificationClients.indexOfKey(pid);
934 if (index >= 0) {
935 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
936 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 mNotificationClients.removeItem(pid);
938 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700939
940 LOGV("%d died, releasing its sessions", pid);
941 int num = mAudioSessionRefs.size();
942 bool removed = false;
943 for (int i = 0; i< num; i++) {
944 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
945 LOGV(" pid %d @ %d", ref->pid, i);
946 if (ref->pid == pid) {
947 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
948 mAudioSessionRefs.removeAt(i);
949 delete ref;
950 removed = true;
951 i--;
952 num--;
953 }
954 }
955 if (removed) {
956 purgeStaleEffects_l();
957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700958}
959
960// audioConfigChanged_l() must be called with AudioFlinger::mLock held
961void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
962{
963 size_t size = mNotificationClients.size();
964 for (size_t i = 0; i < size; i++) {
965 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
966 }
967}
968
969// removeClient_l() must be called with AudioFlinger::mLock held
970void AudioFlinger::removeClient_l(pid_t pid)
971{
972 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
973 mClients.removeItem(pid);
974}
975
976
977// ----------------------------------------------------------------------------
978
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700979AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 : Thread(false),
981 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700982 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
983 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700984{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700985 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986}
987
988AudioFlinger::ThreadBase::~ThreadBase()
989{
990 mParamCond.broadcast();
991 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700992 // do not lock the mutex in destructor
993 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700994 if (mPowerManager != 0) {
995 sp<IBinder> binder = mPowerManager->asBinder();
996 binder->unlinkToDeath(mDeathRecipient);
997 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700998}
999
1000void AudioFlinger::ThreadBase::exit()
1001{
1002 // keep a strong ref on ourself so that we wont get
1003 // destroyed in the middle of requestExitAndWait()
1004 sp <ThreadBase> strongMe = this;
1005
1006 LOGV("ThreadBase::exit");
1007 {
1008 AutoMutex lock(&mLock);
1009 mExiting = true;
1010 requestExit();
1011 mWaitWorkCV.signal();
1012 }
1013 requestExitAndWait();
1014}
1015
1016uint32_t AudioFlinger::ThreadBase::sampleRate() const
1017{
1018 return mSampleRate;
1019}
1020
1021int AudioFlinger::ThreadBase::channelCount() const
1022{
1023 return (int)mChannelCount;
1024}
1025
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001026uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001027{
1028 return mFormat;
1029}
1030
1031size_t AudioFlinger::ThreadBase::frameCount() const
1032{
1033 return mFrameCount;
1034}
1035
1036status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1037{
1038 status_t status;
1039
1040 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1041 Mutex::Autolock _l(mLock);
1042
1043 mNewParameters.add(keyValuePairs);
1044 mWaitWorkCV.signal();
1045 // wait condition with timeout in case the thread loop has exited
1046 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001047 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048 status = mParamStatus;
1049 mWaitWorkCV.signal();
1050 } else {
1051 status = TIMED_OUT;
1052 }
1053 return status;
1054}
1055
1056void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1057{
1058 Mutex::Autolock _l(mLock);
1059 sendConfigEvent_l(event, param);
1060}
1061
1062// sendConfigEvent_l() must be called with ThreadBase::mLock held
1063void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1064{
1065 ConfigEvent *configEvent = new ConfigEvent();
1066 configEvent->mEvent = event;
1067 configEvent->mParam = param;
1068 mConfigEvents.add(configEvent);
1069 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1070 mWaitWorkCV.signal();
1071}
1072
1073void AudioFlinger::ThreadBase::processConfigEvents()
1074{
1075 mLock.lock();
1076 while(!mConfigEvents.isEmpty()) {
1077 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1078 ConfigEvent *configEvent = mConfigEvents[0];
1079 mConfigEvents.removeAt(0);
1080 // release mLock before locking AudioFlinger mLock: lock order is always
1081 // AudioFlinger then ThreadBase to avoid cross deadlock
1082 mLock.unlock();
1083 mAudioFlinger->mLock.lock();
1084 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1085 mAudioFlinger->mLock.unlock();
1086 delete configEvent;
1087 mLock.lock();
1088 }
1089 mLock.unlock();
1090}
1091
1092status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1093{
1094 const size_t SIZE = 256;
1095 char buffer[SIZE];
1096 String8 result;
1097
1098 bool locked = tryLock(mLock);
1099 if (!locked) {
1100 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1101 write(fd, buffer, strlen(buffer));
1102 }
1103
1104 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1105 result.append(buffer);
1106 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1111 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001112 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1113 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001114 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1115 result.append(buffer);
1116 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1117 result.append(buffer);
1118
1119 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1120 result.append(buffer);
1121 result.append(" Index Command");
1122 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1123 snprintf(buffer, SIZE, "\n %02d ", i);
1124 result.append(buffer);
1125 result.append(mNewParameters[i]);
1126 }
1127
1128 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1129 result.append(buffer);
1130 snprintf(buffer, SIZE, " Index event param\n");
1131 result.append(buffer);
1132 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1133 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1134 result.append(buffer);
1135 }
1136 result.append("\n");
1137
1138 write(fd, result.string(), result.size());
1139
1140 if (locked) {
1141 mLock.unlock();
1142 }
1143 return NO_ERROR;
1144}
1145
Eric Laurent1d2bff02011-07-24 17:49:51 -07001146status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1147{
1148 const size_t SIZE = 256;
1149 char buffer[SIZE];
1150 String8 result;
1151
1152 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1153 write(fd, buffer, strlen(buffer));
1154
1155 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1156 sp<EffectChain> chain = mEffectChains[i];
1157 if (chain != 0) {
1158 chain->dump(fd, args);
1159 }
1160 }
1161 return NO_ERROR;
1162}
1163
Eric Laurentfeb0db62011-07-22 09:04:31 -07001164void AudioFlinger::ThreadBase::acquireWakeLock()
1165{
1166 Mutex::Autolock _l(mLock);
1167 acquireWakeLock_l();
1168}
1169
1170void AudioFlinger::ThreadBase::acquireWakeLock_l()
1171{
1172 if (mPowerManager == 0) {
1173 // use checkService() to avoid blocking if power service is not up yet
1174 sp<IBinder> binder =
1175 defaultServiceManager()->checkService(String16("power"));
1176 if (binder == 0) {
1177 LOGW("Thread %s cannot connect to the power manager service", mName);
1178 } else {
1179 mPowerManager = interface_cast<IPowerManager>(binder);
1180 binder->linkToDeath(mDeathRecipient);
1181 }
1182 }
1183 if (mPowerManager != 0) {
1184 sp<IBinder> binder = new BBinder();
1185 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1186 binder,
1187 String16(mName));
1188 if (status == NO_ERROR) {
1189 mWakeLockToken = binder;
1190 }
1191 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1192 }
1193}
1194
1195void AudioFlinger::ThreadBase::releaseWakeLock()
1196{
1197 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001198 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001199}
1200
1201void AudioFlinger::ThreadBase::releaseWakeLock_l()
1202{
1203 if (mWakeLockToken != 0) {
1204 LOGV("releaseWakeLock_l() %s", mName);
1205 if (mPowerManager != 0) {
1206 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1207 }
1208 mWakeLockToken.clear();
1209 }
1210}
1211
1212void AudioFlinger::ThreadBase::clearPowerManager()
1213{
1214 Mutex::Autolock _l(mLock);
1215 releaseWakeLock_l();
1216 mPowerManager.clear();
1217}
1218
1219void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1220{
1221 sp<ThreadBase> thread = mThread.promote();
1222 if (thread != 0) {
1223 thread->clearPowerManager();
1224 }
1225 LOGW("power manager service died !!!");
1226}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001227
Eric Laurent59255e42011-07-27 19:49:51 -07001228void AudioFlinger::ThreadBase::setEffectSuspended(
1229 const effect_uuid_t *type, bool suspend, int sessionId)
1230{
1231 Mutex::Autolock _l(mLock);
1232 setEffectSuspended_l(type, suspend, sessionId);
1233}
1234
1235void AudioFlinger::ThreadBase::setEffectSuspended_l(
1236 const effect_uuid_t *type, bool suspend, int sessionId)
1237{
1238 sp<EffectChain> chain;
1239 chain = getEffectChain_l(sessionId);
1240 if (chain != 0) {
1241 if (type != NULL) {
1242 chain->setEffectSuspended_l(type, suspend);
1243 } else {
1244 chain->setEffectSuspendedAll_l(suspend);
1245 }
1246 }
1247
1248 updateSuspendedSessions_l(type, suspend, sessionId);
1249}
1250
1251void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1252{
1253 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1254 if (index < 0) {
1255 return;
1256 }
1257
1258 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1259 mSuspendedSessions.editValueAt(index);
1260
1261 for (size_t i = 0; i < sessionEffects.size(); i++) {
1262 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1263 for (int j = 0; j < desc->mRefCount; j++) {
1264 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1265 chain->setEffectSuspendedAll_l(true);
1266 } else {
1267 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1268 desc->mType.timeLow);
1269 chain->setEffectSuspended_l(&desc->mType, true);
1270 }
1271 }
1272 }
1273}
1274
Eric Laurent59255e42011-07-27 19:49:51 -07001275void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1276 bool suspend,
1277 int sessionId)
1278{
1279 int index = mSuspendedSessions.indexOfKey(sessionId);
1280
1281 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1282
1283 if (suspend) {
1284 if (index >= 0) {
1285 sessionEffects = mSuspendedSessions.editValueAt(index);
1286 } else {
1287 mSuspendedSessions.add(sessionId, sessionEffects);
1288 }
1289 } else {
1290 if (index < 0) {
1291 return;
1292 }
1293 sessionEffects = mSuspendedSessions.editValueAt(index);
1294 }
1295
1296
1297 int key = EffectChain::kKeyForSuspendAll;
1298 if (type != NULL) {
1299 key = type->timeLow;
1300 }
1301 index = sessionEffects.indexOfKey(key);
1302
1303 sp <SuspendedSessionDesc> desc;
1304 if (suspend) {
1305 if (index >= 0) {
1306 desc = sessionEffects.valueAt(index);
1307 } else {
1308 desc = new SuspendedSessionDesc();
1309 if (type != NULL) {
1310 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1311 }
1312 sessionEffects.add(key, desc);
1313 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1314 }
1315 desc->mRefCount++;
1316 } else {
1317 if (index < 0) {
1318 return;
1319 }
1320 desc = sessionEffects.valueAt(index);
1321 if (--desc->mRefCount == 0) {
1322 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1323 sessionEffects.removeItemsAt(index);
1324 if (sessionEffects.isEmpty()) {
1325 LOGV("updateSuspendedSessions_l() restore removing session %d",
1326 sessionId);
1327 mSuspendedSessions.removeItem(sessionId);
1328 }
1329 }
1330 }
1331 if (!sessionEffects.isEmpty()) {
1332 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1333 }
1334}
1335
1336void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1337 bool enabled,
1338 int sessionId)
1339{
1340 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001341 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1342}
Eric Laurent59255e42011-07-27 19:49:51 -07001343
Eric Laurenta85a74a2011-10-19 11:44:54 -07001344void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1345 bool enabled,
1346 int sessionId)
1347{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001348 if (mType != RECORD) {
1349 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1350 // another session. This gives the priority to well behaved effect control panels
1351 // and applications not using global effects.
1352 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1353 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1354 }
1355 }
Eric Laurent59255e42011-07-27 19:49:51 -07001356
1357 sp<EffectChain> chain = getEffectChain_l(sessionId);
1358 if (chain != 0) {
1359 chain->checkSuspendOnEffectEnabled(effect, enabled);
1360 }
1361}
1362
Mathias Agopian65ab4712010-07-14 17:59:35 -07001363// ----------------------------------------------------------------------------
1364
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001365AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1366 AudioStreamOut* output,
1367 int id,
1368 uint32_t device)
1369 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001371 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001373 snprintf(mName, kNameLength, "AudioOut_%d", id);
1374
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375 readOutputParameters();
1376
1377 mMasterVolume = mAudioFlinger->masterVolume();
1378 mMasterMute = mAudioFlinger->masterMute();
1379
Dima Zavinfce7a472011-04-19 22:30:36 -07001380 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1382 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001383 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 }
1385}
1386
1387AudioFlinger::PlaybackThread::~PlaybackThread()
1388{
1389 delete [] mMixBuffer;
1390}
1391
1392status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1393{
1394 dumpInternals(fd, args);
1395 dumpTracks(fd, args);
1396 dumpEffectChains(fd, args);
1397 return NO_ERROR;
1398}
1399
1400status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1401{
1402 const size_t SIZE = 256;
1403 char buffer[SIZE];
1404 String8 result;
1405
1406 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1407 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001408 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 -07001409 for (size_t i = 0; i < mTracks.size(); ++i) {
1410 sp<Track> track = mTracks[i];
1411 if (track != 0) {
1412 track->dump(buffer, SIZE);
1413 result.append(buffer);
1414 }
1415 }
1416
1417 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1418 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001419 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 -07001420 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1421 wp<Track> wTrack = mActiveTracks[i];
1422 if (wTrack != 0) {
1423 sp<Track> track = wTrack.promote();
1424 if (track != 0) {
1425 track->dump(buffer, SIZE);
1426 result.append(buffer);
1427 }
1428 }
1429 }
1430 write(fd, result.string(), result.size());
1431 return NO_ERROR;
1432}
1433
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1435{
1436 const size_t SIZE = 256;
1437 char buffer[SIZE];
1438 String8 result;
1439
1440 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1441 result.append(buffer);
1442 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1453 result.append(buffer);
1454 write(fd, result.string(), result.size());
1455
1456 dumpBase(fd, args);
1457
1458 return NO_ERROR;
1459}
1460
1461// Thread virtuals
1462status_t AudioFlinger::PlaybackThread::readyToRun()
1463{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001464 status_t status = initCheck();
1465 if (status == NO_ERROR) {
1466 LOGI("AudioFlinger's thread %p ready to run", this);
1467 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001469 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001470 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471}
1472
1473void AudioFlinger::PlaybackThread::onFirstRef()
1474{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001475 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1479sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1480 const sp<AudioFlinger::Client>& client,
1481 int streamType,
1482 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001483 uint32_t format,
1484 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485 int frameCount,
1486 const sp<IMemory>& sharedBuffer,
1487 int sessionId,
1488 status_t *status)
1489{
1490 sp<Track> track;
1491 status_t lStatus;
1492
1493 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001494 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1495 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1496 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1497 "for output %p with format %d",
1498 sampleRate, format, channelMask, mOutput, mFormat);
1499 lStatus = BAD_VALUE;
1500 goto Exit;
1501 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 }
1503 } else {
1504 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1505 if (sampleRate > mSampleRate*2) {
1506 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1507 lStatus = BAD_VALUE;
1508 goto Exit;
1509 }
1510 }
1511
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001512 lStatus = initCheck();
1513 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001514 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001515 goto Exit;
1516 }
1517
1518 { // scope for mLock
1519 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001520
1521 // all tracks in same audio session must share the same routing strategy otherwise
1522 // conflicts will happen when tracks are moved from one output to another by audio policy
1523 // manager
1524 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001525 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001526 for (size_t i = 0; i < mTracks.size(); ++i) {
1527 sp<Track> t = mTracks[i];
1528 if (t != 0) {
1529 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001530 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001531 lStatus = BAD_VALUE;
1532 goto Exit;
1533 }
1534 }
1535 }
1536
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001538 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 if (track->getCblk() == NULL || track->name() < 0) {
1540 lStatus = NO_MEMORY;
1541 goto Exit;
1542 }
1543 mTracks.add(track);
1544
1545 sp<EffectChain> chain = getEffectChain_l(sessionId);
1546 if (chain != 0) {
1547 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1548 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001549 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001550 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001551 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001552
1553 // invalidate track immediately if the stream type was moved to another thread since
1554 // createTrack() was called by the client process.
1555 if (!mStreamTypes[streamType].valid) {
1556 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1557 this, streamType);
1558 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1559 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001560 }
1561 lStatus = NO_ERROR;
1562
1563Exit:
1564 if(status) {
1565 *status = lStatus;
1566 }
1567 return track;
1568}
1569
1570uint32_t AudioFlinger::PlaybackThread::latency() const
1571{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001572 Mutex::Autolock _l(mLock);
1573 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001574 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001575 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001576 return 0;
1577 }
1578}
1579
1580status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1581{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001582 mMasterVolume = value;
1583 return NO_ERROR;
1584}
1585
1586status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1587{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001588 mMasterMute = muted;
1589 return NO_ERROR;
1590}
1591
1592float AudioFlinger::PlaybackThread::masterVolume() const
1593{
1594 return mMasterVolume;
1595}
1596
1597bool AudioFlinger::PlaybackThread::masterMute() const
1598{
1599 return mMasterMute;
1600}
1601
1602status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1603{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001604 mStreamTypes[stream].volume = value;
1605 return NO_ERROR;
1606}
1607
1608status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1609{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001610 mStreamTypes[stream].mute = muted;
1611 return NO_ERROR;
1612}
1613
1614float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1615{
1616 return mStreamTypes[stream].volume;
1617}
1618
1619bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1620{
1621 return mStreamTypes[stream].mute;
1622}
1623
Mathias Agopian65ab4712010-07-14 17:59:35 -07001624// addTrack_l() must be called with ThreadBase::mLock held
1625status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1626{
1627 status_t status = ALREADY_EXISTS;
1628
1629 // set retry count for buffer fill
1630 track->mRetryCount = kMaxTrackStartupRetries;
1631 if (mActiveTracks.indexOf(track) < 0) {
1632 // the track is newly added, make sure it fills up all its
1633 // buffers before playing. This is to ensure the client will
1634 // effectively get the latency it requested.
1635 track->mFillingUpStatus = Track::FS_FILLING;
1636 track->mResetDone = false;
1637 mActiveTracks.add(track);
1638 if (track->mainBuffer() != mMixBuffer) {
1639 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1640 if (chain != 0) {
1641 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001642 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 }
1644 }
1645
1646 status = NO_ERROR;
1647 }
1648
1649 LOGV("mWaitWorkCV.broadcast");
1650 mWaitWorkCV.broadcast();
1651
1652 return status;
1653}
1654
1655// destroyTrack_l() must be called with ThreadBase::mLock held
1656void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1657{
1658 track->mState = TrackBase::TERMINATED;
1659 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001660 removeTrack_l(track);
1661 }
1662}
1663
1664void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1665{
1666 mTracks.remove(track);
1667 deleteTrackName_l(track->name());
1668 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1669 if (chain != 0) {
1670 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 }
1672}
1673
1674String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1675{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001676 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001677 char *s;
1678
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001679 Mutex::Autolock _l(mLock);
1680 if (initCheck() != NO_ERROR) {
1681 return out_s8;
1682 }
1683
Dima Zavin799a70e2011-04-18 16:57:27 -07001684 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001685 out_s8 = String8(s);
1686 free(s);
1687 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688}
1689
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001690// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1692 AudioSystem::OutputDescriptor desc;
1693 void *param2 = 0;
1694
1695 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1696
1697 switch (event) {
1698 case AudioSystem::OUTPUT_OPENED:
1699 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001700 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701 desc.samplingRate = mSampleRate;
1702 desc.format = mFormat;
1703 desc.frameCount = mFrameCount;
1704 desc.latency = latency();
1705 param2 = &desc;
1706 break;
1707
1708 case AudioSystem::STREAM_CONFIG_CHANGED:
1709 param2 = &param;
1710 case AudioSystem::OUTPUT_CLOSED:
1711 default:
1712 break;
1713 }
1714 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1715}
1716
1717void AudioFlinger::PlaybackThread::readOutputParameters()
1718{
Dima Zavin799a70e2011-04-18 16:57:27 -07001719 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001720 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1721 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001722 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1723 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1724 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725
1726 // FIXME - Current mixer implementation only supports stereo output: Always
1727 // Allocate a stereo buffer even if HW output is mono.
1728 if (mMixBuffer != NULL) delete[] mMixBuffer;
1729 mMixBuffer = new int16_t[mFrameCount * 2];
1730 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1731
Eric Laurentde070132010-07-13 04:45:46 -07001732 // force reconfiguration of effect chains and engines to take new buffer size and audio
1733 // parameters into account
1734 // Note that mLock is not held when readOutputParameters() is called from the constructor
1735 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1736 // matter.
1737 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1738 Vector< sp<EffectChain> > effectChains = mEffectChains;
1739 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001740 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001741 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742}
1743
1744status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1745{
1746 if (halFrames == 0 || dspFrames == 0) {
1747 return BAD_VALUE;
1748 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001749 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001750 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 return INVALID_OPERATION;
1752 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001753 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754
Dima Zavin799a70e2011-04-18 16:57:27 -07001755 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756}
1757
Eric Laurent39e94f82010-07-28 01:32:47 -07001758uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759{
1760 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001761 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001763 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 }
1765
1766 for (size_t i = 0; i < mTracks.size(); ++i) {
1767 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001768 if (sessionId == track->sessionId() &&
1769 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001770 result |= TRACK_SESSION;
1771 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 }
1773 }
1774
Eric Laurent39e94f82010-07-28 01:32:47 -07001775 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001776}
1777
Eric Laurentde070132010-07-13 04:45:46 -07001778uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1779{
Dima Zavinfce7a472011-04-19 22:30:36 -07001780 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001781 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001782 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1783 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001784 }
1785 for (size_t i = 0; i < mTracks.size(); i++) {
1786 sp<Track> track = mTracks[i];
1787 if (sessionId == track->sessionId() &&
1788 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001789 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001790 }
1791 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001792 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001793}
1794
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001796AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1797{
1798 Mutex::Autolock _l(mLock);
1799 return mOutput;
1800}
1801
1802AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1803{
1804 Mutex::Autolock _l(mLock);
1805 AudioStreamOut *output = mOutput;
1806 mOutput = NULL;
1807 return output;
1808}
1809
1810// this method must always be called either with ThreadBase mLock held or inside the thread loop
1811audio_stream_t* AudioFlinger::PlaybackThread::stream()
1812{
1813 if (mOutput == NULL) {
1814 return NULL;
1815 }
1816 return &mOutput->stream->common;
1817}
1818
Eric Laurent162b40b2011-12-05 09:47:19 -08001819uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1820{
1821 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1822 // decoding and transfer time. So sleeping for half of the latency would likely cause
1823 // underruns
1824 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1825 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1826 } else {
1827 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1828 }
1829}
1830
Mathias Agopian65ab4712010-07-14 17:59:35 -07001831// ----------------------------------------------------------------------------
1832
Dima Zavin799a70e2011-04-18 16:57:27 -07001833AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001834 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08001835 mAudioMixer(0), mPrevMixerStatus(MIXER_IDLE)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001837 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1839
1840 // FIXME - Current mixer implementation only supports stereo output
1841 if (mChannelCount == 1) {
1842 LOGE("Invalid audio hardware channel count");
1843 }
1844}
1845
1846AudioFlinger::MixerThread::~MixerThread()
1847{
1848 delete mAudioMixer;
1849}
1850
1851bool AudioFlinger::MixerThread::threadLoop()
1852{
1853 Vector< sp<Track> > tracksToRemove;
1854 uint32_t mixerStatus = MIXER_IDLE;
1855 nsecs_t standbyTime = systemTime();
1856 size_t mixBufferSize = mFrameCount * mFrameSize;
1857 // FIXME: Relaxed timing because of a certain device that can't meet latency
1858 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001859 // increase threshold again due to low power audio mode. The way this warning threshold is
1860 // calculated and its usefulness should be reconsidered anyway.
1861 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001862 nsecs_t lastWarning = 0;
1863 bool longStandbyExit = false;
1864 uint32_t activeSleepTime = activeSleepTimeUs();
1865 uint32_t idleSleepTime = idleSleepTimeUs();
1866 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001867 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001868 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001869#ifdef DEBUG_CPU_USAGE
1870 ThreadCpuUsage cpu;
1871 const CentralTendencyStatistics& stats = cpu.statistics();
1872#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873
Eric Laurentfeb0db62011-07-22 09:04:31 -07001874 acquireWakeLock();
1875
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 while (!exitPending())
1877 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001878#ifdef DEBUG_CPU_USAGE
1879 cpu.sampleAndEnable();
1880 unsigned n = stats.n();
1881 // cpu.elapsed() is expensive, so don't call it every loop
1882 if ((n & 127) == 1) {
1883 long long elapsed = cpu.elapsed();
1884 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1885 double perLoop = elapsed / (double) n;
1886 double perLoop100 = perLoop * 0.01;
1887 double mean = stats.mean();
1888 double stddev = stats.stddev();
1889 double minimum = stats.minimum();
1890 double maximum = stats.maximum();
1891 cpu.resetStatistics();
1892 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",
1893 elapsed * .000000001, n, perLoop * .000001,
1894 mean * .001,
1895 stddev * .001,
1896 minimum * .001,
1897 maximum * .001,
1898 mean / perLoop100,
1899 stddev / perLoop100,
1900 minimum / perLoop100,
1901 maximum / perLoop100);
1902 }
1903 }
1904#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 processConfigEvents();
1906
1907 mixerStatus = MIXER_IDLE;
1908 { // scope for mLock
1909
1910 Mutex::Autolock _l(mLock);
1911
1912 if (checkForNewParameters_l()) {
1913 mixBufferSize = mFrameCount * mFrameSize;
1914 // FIXME: Relaxed timing because of a certain device that can't meet latency
1915 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001916 // increase threshold again due to low power audio mode. The way this warning
1917 // threshold is calculated and its usefulness should be reconsidered anyway.
1918 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 activeSleepTime = activeSleepTimeUs();
1920 idleSleepTime = idleSleepTimeUs();
1921 }
1922
1923 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1924
1925 // put audio hardware into standby after short delay
1926 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1927 mSuspended) {
1928 if (!mStandby) {
1929 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001930 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931 mStandby = true;
1932 mBytesWritten = 0;
1933 }
1934
1935 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1936 // we're about to wait, flush the binder command buffer
1937 IPCThreadState::self()->flushCommands();
1938
1939 if (exitPending()) break;
1940
Eric Laurentfeb0db62011-07-22 09:04:31 -07001941 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001942 // wait until we have something to do...
1943 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1944 mWaitWorkCV.wait(mLock);
1945 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001946 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08001948 mPrevMixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 if (mMasterMute == false) {
1950 char value[PROPERTY_VALUE_MAX];
1951 property_get("ro.audio.silent", value, "0");
1952 if (atoi(value)) {
1953 LOGD("Silence is golden");
1954 setMasterMute(true);
1955 }
1956 }
1957
1958 standbyTime = systemTime() + kStandbyTimeInNsecs;
1959 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001960 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 continue;
1962 }
1963 }
1964
1965 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1966
1967 // prevent any changes in effect chain list and in each effect chain
1968 // during mixing and effect process as the audio buffers could be deleted
1969 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001970 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 }
1972
1973 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1974 // mix buffers...
1975 mAudioMixer->process();
1976 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001977 // increase sleep time progressively when application underrun condition clears
1978 if (sleepTimeShift > 0) {
1979 sleepTimeShift--;
1980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 standbyTime = systemTime() + kStandbyTimeInNsecs;
1982 //TODO: delay standby when effects have a tail
1983 } else {
1984 // If no tracks are ready, sleep once for the duration of an output
1985 // buffer size, then write 0s to the output
1986 if (sleepTime == 0) {
1987 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001988 sleepTime = activeSleepTime >> sleepTimeShift;
1989 if (sleepTime < kMinThreadSleepTimeUs) {
1990 sleepTime = kMinThreadSleepTimeUs;
1991 }
1992 // reduce sleep time in case of consecutive application underruns to avoid
1993 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1994 // duration we would end up writing less data than needed by the audio HAL if
1995 // the condition persists.
1996 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1997 sleepTimeShift++;
1998 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001999 } else {
2000 sleepTime = idleSleepTime;
2001 }
2002 } else if (mBytesWritten != 0 ||
2003 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2004 memset (mMixBuffer, 0, mixBufferSize);
2005 sleepTime = 0;
2006 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2007 }
2008 // TODO add standby time extension fct of effect tail
2009 }
2010
2011 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002012 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
2014 // sleepTime == 0 means we must write to audio hardware
2015 if (sleepTime == 0) {
2016 for (size_t i = 0; i < effectChains.size(); i ++) {
2017 effectChains[i]->process_l();
2018 }
2019 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002020 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002021 mLastWriteTime = systemTime();
2022 mInWrite = true;
2023 mBytesWritten += mixBufferSize;
2024
Dima Zavin799a70e2011-04-18 16:57:27 -07002025 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002026 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2027 mNumWrites++;
2028 mInWrite = false;
2029 nsecs_t now = systemTime();
2030 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002031 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 mNumDelayedWrites++;
2033 if ((now - lastWarning) > kWarningThrottle) {
2034 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2035 ns2ms(delta), mNumDelayedWrites, this);
2036 lastWarning = now;
2037 }
2038 if (mStandby) {
2039 longStandbyExit = true;
2040 }
2041 }
2042 mStandby = false;
2043 } else {
2044 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002045 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 usleep(sleepTime);
2047 }
2048
2049 // finally let go of all our tracks, without the lock held
2050 // since we can't guarantee the destructors won't acquire that
2051 // same lock.
2052 tracksToRemove.clear();
2053
2054 // Effect chains will be actually deleted here if they were removed from
2055 // mEffectChains list during mixing or effects processing
2056 effectChains.clear();
2057 }
2058
2059 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002060 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061 }
2062
Eric Laurentfeb0db62011-07-22 09:04:31 -07002063 releaseWakeLock();
2064
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 LOGV("MixerThread %p exiting", this);
2066 return false;
2067}
2068
2069// prepareTracks_l() must be called with ThreadBase::mLock held
2070uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2071{
2072
2073 uint32_t mixerStatus = MIXER_IDLE;
2074 // find out which tracks need to be processed
2075 size_t count = activeTracks.size();
2076 size_t mixedTracks = 0;
2077 size_t tracksWithEffect = 0;
2078
2079 float masterVolume = mMasterVolume;
2080 bool masterMute = mMasterMute;
2081
Eric Laurent571d49c2010-08-11 05:20:11 -07002082 if (masterMute) {
2083 masterVolume = 0;
2084 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002086 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002088 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002089 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002090 masterVolume = (float)((v + (1 << 23)) >> 24);
2091 chain.clear();
2092 }
2093
2094 for (size_t i=0 ; i<count ; i++) {
2095 sp<Track> t = activeTracks[i].promote();
2096 if (t == 0) continue;
2097
2098 Track* const track = t.get();
2099 audio_track_cblk_t* cblk = track->cblk();
2100
2101 // The first time a track is added we wait
2102 // for all its buffers to be filled before processing it
2103 mAudioMixer->setActiveTrack(track->name());
Eric Laurenta47b69c2011-11-08 18:10:16 -08002104 // make sure that we have enough frames to mix one full buffer.
2105 // enforce this condition only once to enable draining the buffer in case the client
2106 // app does not call stop() and relies on underrun to stop:
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08002107 // hence the test on (mPrevMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
Eric Laurenta47b69c2011-11-08 18:10:16 -08002108 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002109 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002110 if (!track->isStopped() && !track->isPausing() &&
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08002111 (mPrevMixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002112 if (t->sampleRate() == (int)mSampleRate) {
2113 minFrames = mFrameCount;
2114 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002115 // +1 for rounding and +1 for additional sample needed for interpolation
2116 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2117 // add frames already consumed but not yet released by the resampler
2118 // because cblk->framesReady() will include these frames
2119 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2120 // the minimum track buffer size is normally twice the number of frames necessary
2121 // to fill one buffer and the resampler should not leave more than one buffer worth
2122 // of unreleased frames after each pass, but just in case...
2123 LOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002124 }
2125 }
2126 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127 !track->isPaused() && !track->isTerminated())
2128 {
2129 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2130
2131 mixedTracks++;
2132
2133 // track->mainBuffer() != mMixBuffer means there is an effect chain
2134 // connected to the track
2135 chain.clear();
2136 if (track->mainBuffer() != mMixBuffer) {
2137 chain = getEffectChain_l(track->sessionId());
2138 // Delegate volume control to effect in track effect chain if needed
2139 if (chain != 0) {
2140 tracksWithEffect++;
2141 } else {
2142 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2143 track->name(), track->sessionId());
2144 }
2145 }
2146
2147
2148 int param = AudioMixer::VOLUME;
2149 if (track->mFillingUpStatus == Track::FS_FILLED) {
2150 // no ramp for the first volume setting
2151 track->mFillingUpStatus = Track::FS_ACTIVE;
2152 if (track->mState == TrackBase::RESUMING) {
2153 track->mState = TrackBase::ACTIVE;
2154 param = AudioMixer::RAMP_VOLUME;
2155 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002156 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002157 } else if (cblk->server != 0) {
2158 // If the track is stopped before the first frame was mixed,
2159 // do not apply ramp
2160 param = AudioMixer::RAMP_VOLUME;
2161 }
2162
2163 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002164 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002165 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002167 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 if (track->isPausing()) {
2169 track->setPaused();
2170 }
2171 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002172
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 // read original volumes with volume control
2174 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002176 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2177 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178
Eric Laurente0aed6d2010-09-10 17:44:44 -07002179 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002181 // Delegate volume control to effect in track effect chain if needed
2182 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2183 // Do not ramp volume if volume is controlled by effect
2184 param = AudioMixer::VOLUME;
2185 track->mHasVolumeController = true;
2186 } else {
2187 // force no volume ramp when volume controller was just disabled or removed
2188 // from effect chain to avoid volume spike
2189 if (track->mHasVolumeController) {
2190 param = AudioMixer::VOLUME;
2191 }
2192 track->mHasVolumeController = false;
2193 }
2194
2195 // Convert volumes from 8.24 to 4.12 format
2196 int16_t left, right, aux;
2197 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2198 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2199 left = int16_t(v_clamped);
2200 v_clamped = (vr + (1 << 11)) >> 12;
2201 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2202 right = int16_t(v_clamped);
2203
2204 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2205 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206
Mathias Agopian65ab4712010-07-14 17:59:35 -07002207 // XXX: these things DON'T need to be done each time
2208 mAudioMixer->setBufferProvider(track);
2209 mAudioMixer->enable(AudioMixer::MIXING);
2210
2211 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2212 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2213 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2214 mAudioMixer->setParameter(
2215 AudioMixer::TRACK,
2216 AudioMixer::FORMAT, (void *)track->format());
2217 mAudioMixer->setParameter(
2218 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002219 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002220 mAudioMixer->setParameter(
2221 AudioMixer::RESAMPLE,
2222 AudioMixer::SAMPLE_RATE,
2223 (void *)(cblk->sampleRate));
2224 mAudioMixer->setParameter(
2225 AudioMixer::TRACK,
2226 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2227 mAudioMixer->setParameter(
2228 AudioMixer::TRACK,
2229 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2230
2231 // reset retry count
2232 track->mRetryCount = kMaxTrackRetries;
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08002233 // If one track is ready, set the mixer ready if:
2234 // - the mixer was not ready during previous round OR
2235 // - no other track is not ready
2236 if (mPrevMixerStatus != MIXER_TRACKS_READY ||
2237 mixerStatus != MIXER_TRACKS_ENABLED) {
2238 mixerStatus = MIXER_TRACKS_READY;
2239 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 } else {
2241 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2242 if (track->isStopped()) {
2243 track->reset();
2244 }
2245 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2246 // We have consumed all the buffers of this track.
2247 // Remove it from the list of active tracks.
2248 tracksToRemove->add(track);
2249 } else {
2250 // No buffers for this track. Give it a few chances to
2251 // fill a buffer, then remove it from active list.
2252 if (--(track->mRetryCount) <= 0) {
2253 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2254 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002255 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002256 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08002257 // If one track is not ready, mark the mixer also not ready if:
2258 // - the mixer was ready during previous round OR
2259 // - no other track is ready
2260 } else if (mPrevMixerStatus == MIXER_TRACKS_READY ||
2261 mixerStatus != MIXER_TRACKS_READY) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002262 mixerStatus = MIXER_TRACKS_ENABLED;
2263 }
2264 }
2265 mAudioMixer->disable(AudioMixer::MIXING);
2266 }
2267 }
2268
2269 // remove all the tracks that need to be...
2270 count = tracksToRemove->size();
2271 if (UNLIKELY(count)) {
2272 for (size_t i=0 ; i<count ; i++) {
2273 const sp<Track>& track = tracksToRemove->itemAt(i);
2274 mActiveTracks.remove(track);
2275 if (track->mainBuffer() != mMixBuffer) {
2276 chain = getEffectChain_l(track->sessionId());
2277 if (chain != 0) {
2278 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002279 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002280 }
2281 }
2282 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002283 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002284 }
2285 }
2286 }
2287
2288 // mix buffer must be cleared if all tracks are connected to an
2289 // effect chain as in this case the mixer will not write to
2290 // mix buffer and track effects will accumulate into it
2291 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2292 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2293 }
2294
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08002295 mPrevMixerStatus = mixerStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 return mixerStatus;
2297}
2298
2299void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2300{
Eric Laurentde070132010-07-13 04:45:46 -07002301 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2302 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002304
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305 size_t size = mTracks.size();
2306 for (size_t i = 0; i < size; i++) {
2307 sp<Track> t = mTracks[i];
2308 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002309 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002310 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 }
2312 }
2313}
2314
Eric Laurent9f6530f2011-08-30 10:18:54 -07002315void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2316{
2317 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2318 this, streamType, valid);
2319 Mutex::Autolock _l(mLock);
2320
2321 mStreamTypes[streamType].valid = valid;
2322}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323
2324// getTrackName_l() must be called with ThreadBase::mLock held
2325int AudioFlinger::MixerThread::getTrackName_l()
2326{
2327 return mAudioMixer->getTrackName();
2328}
2329
2330// deleteTrackName_l() must be called with ThreadBase::mLock held
2331void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2332{
2333 LOGV("remove track (%d) and delete from mixer", name);
2334 mAudioMixer->deleteTrackName(name);
2335}
2336
2337// checkForNewParameters_l() must be called with ThreadBase::mLock held
2338bool AudioFlinger::MixerThread::checkForNewParameters_l()
2339{
2340 bool reconfig = false;
2341
2342 while (!mNewParameters.isEmpty()) {
2343 status_t status = NO_ERROR;
2344 String8 keyValuePair = mNewParameters[0];
2345 AudioParameter param = AudioParameter(keyValuePair);
2346 int value;
2347
2348 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2349 reconfig = true;
2350 }
2351 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002352 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 status = BAD_VALUE;
2354 } else {
2355 reconfig = true;
2356 }
2357 }
2358 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002359 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 status = BAD_VALUE;
2361 } else {
2362 reconfig = true;
2363 }
2364 }
2365 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2366 // do not accept frame count changes if tracks are open as the track buffer
2367 // size depends on frame count and correct behavior would not be garantied
2368 // if frame count is changed after track creation
2369 if (!mTracks.isEmpty()) {
2370 status = INVALID_OPERATION;
2371 } else {
2372 reconfig = true;
2373 }
2374 }
2375 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002376 // when changing the audio output device, call addBatteryData to notify
2377 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002378 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002379 uint32_t params = 0;
2380 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002381 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002382 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2383 }
2384
2385 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002386 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002387 // check if any other device (except speaker) is on
2388 if (value & deviceWithoutSpeaker ) {
2389 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2390 }
2391
2392 if (params != 0) {
2393 addBatteryData(params);
2394 }
2395 }
2396
Mathias Agopian65ab4712010-07-14 17:59:35 -07002397 // forward device change to effects that have requested to be
2398 // aware of attached audio device.
2399 mDevice = (uint32_t)value;
2400 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002401 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002402 }
2403 }
2404
2405 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002406 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002407 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002408 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002409 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 mStandby = true;
2411 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002412 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002413 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 }
2415 if (status == NO_ERROR && reconfig) {
2416 delete mAudioMixer;
2417 readOutputParameters();
2418 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2419 for (size_t i = 0; i < mTracks.size() ; i++) {
2420 int name = getTrackName_l();
2421 if (name < 0) break;
2422 mTracks[i]->mName = name;
2423 // limit track sample rate to 2 x new output sample rate
2424 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2425 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2426 }
2427 }
2428 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2429 }
2430 }
2431
2432 mNewParameters.removeAt(0);
2433
2434 mParamStatus = status;
2435 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002436 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2437 // already timed out waiting for the status and will never signal the condition.
2438 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 }
2440 return reconfig;
2441}
2442
2443status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2444{
2445 const size_t SIZE = 256;
2446 char buffer[SIZE];
2447 String8 result;
2448
2449 PlaybackThread::dumpInternals(fd, args);
2450
2451 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2452 result.append(buffer);
2453 write(fd, result.string(), result.size());
2454 return NO_ERROR;
2455}
2456
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2458{
Eric Laurent60e18242010-07-29 06:50:24 -07002459 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460}
2461
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002462uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2463{
2464 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2465}
2466
Mathias Agopian65ab4712010-07-14 17:59:35 -07002467// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002468AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469 : PlaybackThread(audioFlinger, output, id, device)
2470{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002471 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472}
2473
2474AudioFlinger::DirectOutputThread::~DirectOutputThread()
2475{
2476}
2477
2478
2479static inline int16_t clamp16(int32_t sample)
2480{
2481 if ((sample>>15) ^ (sample>>31))
2482 sample = 0x7FFF ^ (sample>>31);
2483 return sample;
2484}
2485
2486static inline
2487int32_t mul(int16_t in, int16_t v)
2488{
2489#if defined(__arm__) && !defined(__thumb__)
2490 int32_t out;
2491 asm( "smulbb %[out], %[in], %[v] \n"
2492 : [out]"=r"(out)
2493 : [in]"%r"(in), [v]"r"(v)
2494 : );
2495 return out;
2496#else
2497 return in * int32_t(v);
2498#endif
2499}
2500
2501void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2502{
2503 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002504 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 return;
2506 }
2507
2508 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002509 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002510 size_t count = mFrameCount * mChannelCount;
2511 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2512 int16_t *dst = mMixBuffer + count-1;
2513 while(count--) {
2514 *dst-- = (int16_t)(*src--^0x80) << 8;
2515 }
2516 }
2517
2518 size_t frameCount = mFrameCount;
2519 int16_t *out = mMixBuffer;
2520 if (ramp) {
2521 if (mChannelCount == 1) {
2522 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2523 int32_t vlInc = d / (int32_t)frameCount;
2524 int32_t vl = ((int32_t)mLeftVolShort << 16);
2525 do {
2526 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2527 out++;
2528 vl += vlInc;
2529 } while (--frameCount);
2530
2531 } else {
2532 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2533 int32_t vlInc = d / (int32_t)frameCount;
2534 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2535 int32_t vrInc = d / (int32_t)frameCount;
2536 int32_t vl = ((int32_t)mLeftVolShort << 16);
2537 int32_t vr = ((int32_t)mRightVolShort << 16);
2538 do {
2539 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2540 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2541 out += 2;
2542 vl += vlInc;
2543 vr += vrInc;
2544 } while (--frameCount);
2545 }
2546 } else {
2547 if (mChannelCount == 1) {
2548 do {
2549 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2550 out++;
2551 } while (--frameCount);
2552 } else {
2553 do {
2554 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2555 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2556 out += 2;
2557 } while (--frameCount);
2558 }
2559 }
2560
2561 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002562 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002563 size_t count = mFrameCount * mChannelCount;
2564 int16_t *src = mMixBuffer;
2565 uint8_t *dst = (uint8_t *)mMixBuffer;
2566 while(count--) {
2567 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2568 }
2569 }
2570
2571 mLeftVolShort = leftVol;
2572 mRightVolShort = rightVol;
2573}
2574
2575bool AudioFlinger::DirectOutputThread::threadLoop()
2576{
2577 uint32_t mixerStatus = MIXER_IDLE;
2578 sp<Track> trackToRemove;
2579 sp<Track> activeTrack;
2580 nsecs_t standbyTime = systemTime();
2581 int8_t *curBuf;
2582 size_t mixBufferSize = mFrameCount*mFrameSize;
2583 uint32_t activeSleepTime = activeSleepTimeUs();
2584 uint32_t idleSleepTime = idleSleepTimeUs();
2585 uint32_t sleepTime = idleSleepTime;
2586 // use shorter standby delay as on normal output to release
2587 // hardware resources as soon as possible
2588 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2589
Eric Laurentfeb0db62011-07-22 09:04:31 -07002590 acquireWakeLock();
2591
Mathias Agopian65ab4712010-07-14 17:59:35 -07002592 while (!exitPending())
2593 {
2594 bool rampVolume;
2595 uint16_t leftVol;
2596 uint16_t rightVol;
2597 Vector< sp<EffectChain> > effectChains;
2598
2599 processConfigEvents();
2600
2601 mixerStatus = MIXER_IDLE;
2602
2603 { // scope for the mLock
2604
2605 Mutex::Autolock _l(mLock);
2606
2607 if (checkForNewParameters_l()) {
2608 mixBufferSize = mFrameCount*mFrameSize;
2609 activeSleepTime = activeSleepTimeUs();
2610 idleSleepTime = idleSleepTimeUs();
2611 standbyDelay = microseconds(activeSleepTime*2);
2612 }
2613
2614 // put audio hardware into standby after short delay
2615 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2616 mSuspended) {
2617 // wait until we have something to do...
2618 if (!mStandby) {
2619 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002620 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 mStandby = true;
2622 mBytesWritten = 0;
2623 }
2624
2625 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2626 // we're about to wait, flush the binder command buffer
2627 IPCThreadState::self()->flushCommands();
2628
2629 if (exitPending()) break;
2630
Eric Laurentfeb0db62011-07-22 09:04:31 -07002631 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2633 mWaitWorkCV.wait(mLock);
2634 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002635 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002636
2637 if (mMasterMute == false) {
2638 char value[PROPERTY_VALUE_MAX];
2639 property_get("ro.audio.silent", value, "0");
2640 if (atoi(value)) {
2641 LOGD("Silence is golden");
2642 setMasterMute(true);
2643 }
2644 }
2645
2646 standbyTime = systemTime() + standbyDelay;
2647 sleepTime = idleSleepTime;
2648 continue;
2649 }
2650 }
2651
2652 effectChains = mEffectChains;
2653
2654 // find out which tracks need to be processed
2655 if (mActiveTracks.size() != 0) {
2656 sp<Track> t = mActiveTracks[0].promote();
2657 if (t == 0) continue;
2658
2659 Track* const track = t.get();
2660 audio_track_cblk_t* cblk = track->cblk();
2661
2662 // The first time a track is added we wait
2663 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002664 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002665 !track->isPaused() && !track->isTerminated())
2666 {
2667 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2668
2669 if (track->mFillingUpStatus == Track::FS_FILLED) {
2670 track->mFillingUpStatus = Track::FS_ACTIVE;
2671 mLeftVolFloat = mRightVolFloat = 0;
2672 mLeftVolShort = mRightVolShort = 0;
2673 if (track->mState == TrackBase::RESUMING) {
2674 track->mState = TrackBase::ACTIVE;
2675 rampVolume = true;
2676 }
2677 } else if (cblk->server != 0) {
2678 // If the track is stopped before the first frame was mixed,
2679 // do not apply ramp
2680 rampVolume = true;
2681 }
2682 // compute volume for this track
2683 float left, right;
2684 if (track->isMuted() || mMasterMute || track->isPausing() ||
2685 mStreamTypes[track->type()].mute) {
2686 left = right = 0;
2687 if (track->isPausing()) {
2688 track->setPaused();
2689 }
2690 } else {
2691 float typeVolume = mStreamTypes[track->type()].volume;
2692 float v = mMasterVolume * typeVolume;
2693 float v_clamped = v * cblk->volume[0];
2694 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2695 left = v_clamped/MAX_GAIN;
2696 v_clamped = v * cblk->volume[1];
2697 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2698 right = v_clamped/MAX_GAIN;
2699 }
2700
2701 if (left != mLeftVolFloat || right != mRightVolFloat) {
2702 mLeftVolFloat = left;
2703 mRightVolFloat = right;
2704
2705 // If audio HAL implements volume control,
2706 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002707 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002708 left = 1.0f;
2709 right = 1.0f;
2710 }
2711
2712 // Convert volumes from float to 8.24
2713 uint32_t vl = (uint32_t)(left * (1 << 24));
2714 uint32_t vr = (uint32_t)(right * (1 << 24));
2715
2716 // Delegate volume control to effect in track effect chain if needed
2717 // only one effect chain can be present on DirectOutputThread, so if
2718 // there is one, the track is connected to it
2719 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002720 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002721 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002722 rampVolume = false;
2723 }
2724 }
2725
2726 // Convert volumes from 8.24 to 4.12 format
2727 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2728 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2729 leftVol = (uint16_t)v_clamped;
2730 v_clamped = (vr + (1 << 11)) >> 12;
2731 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2732 rightVol = (uint16_t)v_clamped;
2733 } else {
2734 leftVol = mLeftVolShort;
2735 rightVol = mRightVolShort;
2736 rampVolume = false;
2737 }
2738
2739 // reset retry count
2740 track->mRetryCount = kMaxTrackRetriesDirect;
2741 activeTrack = t;
2742 mixerStatus = MIXER_TRACKS_READY;
2743 } else {
2744 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2745 if (track->isStopped()) {
2746 track->reset();
2747 }
2748 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2749 // We have consumed all the buffers of this track.
2750 // Remove it from the list of active tracks.
2751 trackToRemove = track;
2752 } else {
2753 // No buffers for this track. Give it a few chances to
2754 // fill a buffer, then remove it from active list.
2755 if (--(track->mRetryCount) <= 0) {
2756 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2757 trackToRemove = track;
2758 } else {
2759 mixerStatus = MIXER_TRACKS_ENABLED;
2760 }
2761 }
2762 }
2763 }
2764
2765 // remove all the tracks that need to be...
2766 if (UNLIKELY(trackToRemove != 0)) {
2767 mActiveTracks.remove(trackToRemove);
2768 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002769 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2770 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002771 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002772 }
2773 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002774 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 }
2776 }
2777
Eric Laurentde070132010-07-13 04:45:46 -07002778 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002779 }
2780
2781 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2782 AudioBufferProvider::Buffer buffer;
2783 size_t frameCount = mFrameCount;
2784 curBuf = (int8_t *)mMixBuffer;
2785 // output audio to hardware
2786 while (frameCount) {
2787 buffer.frameCount = frameCount;
2788 activeTrack->getNextBuffer(&buffer);
2789 if (UNLIKELY(buffer.raw == 0)) {
2790 memset(curBuf, 0, frameCount * mFrameSize);
2791 break;
2792 }
2793 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2794 frameCount -= buffer.frameCount;
2795 curBuf += buffer.frameCount * mFrameSize;
2796 activeTrack->releaseBuffer(&buffer);
2797 }
2798 sleepTime = 0;
2799 standbyTime = systemTime() + standbyDelay;
2800 } else {
2801 if (sleepTime == 0) {
2802 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2803 sleepTime = activeSleepTime;
2804 } else {
2805 sleepTime = idleSleepTime;
2806 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002807 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002808 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2809 sleepTime = 0;
2810 }
2811 }
2812
2813 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002814 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 }
2816 // sleepTime == 0 means we must write to audio hardware
2817 if (sleepTime == 0) {
2818 if (mixerStatus == MIXER_TRACKS_READY) {
2819 applyVolume(leftVol, rightVol, rampVolume);
2820 }
2821 for (size_t i = 0; i < effectChains.size(); i ++) {
2822 effectChains[i]->process_l();
2823 }
Eric Laurentde070132010-07-13 04:45:46 -07002824 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002825
2826 mLastWriteTime = systemTime();
2827 mInWrite = true;
2828 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002829 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002830 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2831 mNumWrites++;
2832 mInWrite = false;
2833 mStandby = false;
2834 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002835 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002836 usleep(sleepTime);
2837 }
2838
2839 // finally let go of removed track, without the lock held
2840 // since we can't guarantee the destructors won't acquire that
2841 // same lock.
2842 trackToRemove.clear();
2843 activeTrack.clear();
2844
2845 // Effect chains will be actually deleted here if they were removed from
2846 // mEffectChains list during mixing or effects processing
2847 effectChains.clear();
2848 }
2849
2850 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002851 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002852 }
2853
Eric Laurentfeb0db62011-07-22 09:04:31 -07002854 releaseWakeLock();
2855
Mathias Agopian65ab4712010-07-14 17:59:35 -07002856 LOGV("DirectOutputThread %p exiting", this);
2857 return false;
2858}
2859
2860// getTrackName_l() must be called with ThreadBase::mLock held
2861int AudioFlinger::DirectOutputThread::getTrackName_l()
2862{
2863 return 0;
2864}
2865
2866// deleteTrackName_l() must be called with ThreadBase::mLock held
2867void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2868{
2869}
2870
2871// checkForNewParameters_l() must be called with ThreadBase::mLock held
2872bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2873{
2874 bool reconfig = false;
2875
2876 while (!mNewParameters.isEmpty()) {
2877 status_t status = NO_ERROR;
2878 String8 keyValuePair = mNewParameters[0];
2879 AudioParameter param = AudioParameter(keyValuePair);
2880 int value;
2881
2882 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2883 // do not accept frame count changes if tracks are open as the track buffer
2884 // size depends on frame count and correct behavior would not be garantied
2885 // if frame count is changed after track creation
2886 if (!mTracks.isEmpty()) {
2887 status = INVALID_OPERATION;
2888 } else {
2889 reconfig = true;
2890 }
2891 }
2892 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002893 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002894 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002896 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 mStandby = true;
2898 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002899 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002900 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002901 }
2902 if (status == NO_ERROR && reconfig) {
2903 readOutputParameters();
2904 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2905 }
2906 }
2907
2908 mNewParameters.removeAt(0);
2909
2910 mParamStatus = status;
2911 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002912 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2913 // already timed out waiting for the status and will never signal the condition.
2914 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 }
2916 return reconfig;
2917}
2918
2919uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2920{
2921 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002922 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002923 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002924 } else {
2925 time = 10000;
2926 }
2927 return time;
2928}
2929
2930uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2931{
2932 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002933 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002934 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935 } else {
2936 time = 10000;
2937 }
2938 return time;
2939}
2940
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002941uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2942{
2943 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002944 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002945 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2946 } else {
2947 time = 10000;
2948 }
2949 return time;
2950}
2951
2952
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953// ----------------------------------------------------------------------------
2954
2955AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2956 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2957{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002958 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 addOutputTrack(mainThread);
2960}
2961
2962AudioFlinger::DuplicatingThread::~DuplicatingThread()
2963{
2964 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2965 mOutputTracks[i]->destroy();
2966 }
2967 mOutputTracks.clear();
2968}
2969
2970bool AudioFlinger::DuplicatingThread::threadLoop()
2971{
2972 Vector< sp<Track> > tracksToRemove;
2973 uint32_t mixerStatus = MIXER_IDLE;
2974 nsecs_t standbyTime = systemTime();
2975 size_t mixBufferSize = mFrameCount*mFrameSize;
2976 SortedVector< sp<OutputTrack> > outputTracks;
2977 uint32_t writeFrames = 0;
2978 uint32_t activeSleepTime = activeSleepTimeUs();
2979 uint32_t idleSleepTime = idleSleepTimeUs();
2980 uint32_t sleepTime = idleSleepTime;
2981 Vector< sp<EffectChain> > effectChains;
2982
Eric Laurentfeb0db62011-07-22 09:04:31 -07002983 acquireWakeLock();
2984
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985 while (!exitPending())
2986 {
2987 processConfigEvents();
2988
2989 mixerStatus = MIXER_IDLE;
2990 { // scope for the mLock
2991
2992 Mutex::Autolock _l(mLock);
2993
2994 if (checkForNewParameters_l()) {
2995 mixBufferSize = mFrameCount*mFrameSize;
2996 updateWaitTime();
2997 activeSleepTime = activeSleepTimeUs();
2998 idleSleepTime = idleSleepTimeUs();
2999 }
3000
3001 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3002
3003 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3004 outputTracks.add(mOutputTracks[i]);
3005 }
3006
3007 // put audio hardware into standby after short delay
3008 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3009 mSuspended) {
3010 if (!mStandby) {
3011 for (size_t i = 0; i < outputTracks.size(); i++) {
3012 outputTracks[i]->stop();
3013 }
3014 mStandby = true;
3015 mBytesWritten = 0;
3016 }
3017
3018 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3019 // we're about to wait, flush the binder command buffer
3020 IPCThreadState::self()->flushCommands();
3021 outputTracks.clear();
3022
3023 if (exitPending()) break;
3024
Eric Laurentfeb0db62011-07-22 09:04:31 -07003025 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
3027 mWaitWorkCV.wait(mLock);
3028 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003029 acquireWakeLock_l();
3030
Eric Laurenteaa0b5c2012-01-23 18:35:10 -08003031 mPrevMixerStatus = MIXER_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 if (mMasterMute == false) {
3033 char value[PROPERTY_VALUE_MAX];
3034 property_get("ro.audio.silent", value, "0");
3035 if (atoi(value)) {
3036 LOGD("Silence is golden");
3037 setMasterMute(true);
3038 }
3039 }
3040
3041 standbyTime = systemTime() + kStandbyTimeInNsecs;
3042 sleepTime = idleSleepTime;
3043 continue;
3044 }
3045 }
3046
3047 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3048
3049 // prevent any changes in effect chain list and in each effect chain
3050 // during mixing and effect process as the audio buffers could be deleted
3051 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003052 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 }
3054
3055 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3056 // mix buffers...
3057 if (outputsReady(outputTracks)) {
3058 mAudioMixer->process();
3059 } else {
3060 memset(mMixBuffer, 0, mixBufferSize);
3061 }
3062 sleepTime = 0;
3063 writeFrames = mFrameCount;
3064 } else {
3065 if (sleepTime == 0) {
3066 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3067 sleepTime = activeSleepTime;
3068 } else {
3069 sleepTime = idleSleepTime;
3070 }
3071 } else if (mBytesWritten != 0) {
3072 // flush remaining overflow buffers in output tracks
3073 for (size_t i = 0; i < outputTracks.size(); i++) {
3074 if (outputTracks[i]->isActive()) {
3075 sleepTime = 0;
3076 writeFrames = 0;
3077 memset(mMixBuffer, 0, mixBufferSize);
3078 break;
3079 }
3080 }
3081 }
3082 }
3083
3084 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003085 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003086 }
3087 // sleepTime == 0 means we must write to audio hardware
3088 if (sleepTime == 0) {
3089 for (size_t i = 0; i < effectChains.size(); i ++) {
3090 effectChains[i]->process_l();
3091 }
3092 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003093 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003094
3095 standbyTime = systemTime() + kStandbyTimeInNsecs;
3096 for (size_t i = 0; i < outputTracks.size(); i++) {
3097 outputTracks[i]->write(mMixBuffer, writeFrames);
3098 }
3099 mStandby = false;
3100 mBytesWritten += mixBufferSize;
3101 } else {
3102 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003103 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 usleep(sleepTime);
3105 }
3106
3107 // finally let go of all our tracks, without the lock held
3108 // since we can't guarantee the destructors won't acquire that
3109 // same lock.
3110 tracksToRemove.clear();
3111 outputTracks.clear();
3112
3113 // Effect chains will be actually deleted here if they were removed from
3114 // mEffectChains list during mixing or effects processing
3115 effectChains.clear();
3116 }
3117
Eric Laurentfeb0db62011-07-22 09:04:31 -07003118 releaseWakeLock();
3119
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 return false;
3121}
3122
3123void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3124{
3125 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3126 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3127 this,
3128 mSampleRate,
3129 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003130 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131 frameCount);
3132 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003133 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003134 mOutputTracks.add(outputTrack);
3135 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3136 updateWaitTime();
3137 }
3138}
3139
3140void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3141{
3142 Mutex::Autolock _l(mLock);
3143 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3144 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3145 mOutputTracks[i]->destroy();
3146 mOutputTracks.removeAt(i);
3147 updateWaitTime();
3148 return;
3149 }
3150 }
3151 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3152}
3153
3154void AudioFlinger::DuplicatingThread::updateWaitTime()
3155{
3156 mWaitTimeMs = UINT_MAX;
3157 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3158 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3159 if (strong != NULL) {
3160 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3161 if (waitTimeMs < mWaitTimeMs) {
3162 mWaitTimeMs = waitTimeMs;
3163 }
3164 }
3165 }
3166}
3167
3168
3169bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3170{
3171 for (size_t i = 0; i < outputTracks.size(); i++) {
3172 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3173 if (thread == 0) {
3174 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3175 return false;
3176 }
3177 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3178 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3179 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3180 return false;
3181 }
3182 }
3183 return true;
3184}
3185
3186uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3187{
3188 return (mWaitTimeMs * 1000) / 2;
3189}
3190
3191// ----------------------------------------------------------------------------
3192
3193// TrackBase constructor must be called with AudioFlinger::mLock held
3194AudioFlinger::ThreadBase::TrackBase::TrackBase(
3195 const wp<ThreadBase>& thread,
3196 const sp<Client>& client,
3197 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003198 uint32_t format,
3199 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200 int frameCount,
3201 uint32_t flags,
3202 const sp<IMemory>& sharedBuffer,
3203 int sessionId)
3204 : RefBase(),
3205 mThread(thread),
3206 mClient(client),
3207 mCblk(0),
3208 mFrameCount(0),
3209 mState(IDLE),
3210 mClientTid(-1),
3211 mFormat(format),
3212 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3213 mSessionId(sessionId)
3214{
3215 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3216
3217 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3218 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003219 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3221 if (sharedBuffer == 0) {
3222 size += bufferSize;
3223 }
3224
3225 if (client != NULL) {
3226 mCblkMemory = client->heap()->allocate(size);
3227 if (mCblkMemory != 0) {
3228 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3229 if (mCblk) { // construct the shared structure in-place.
3230 new(mCblk) audio_track_cblk_t();
3231 // clear all buffers
3232 mCblk->frameCount = frameCount;
3233 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003234 mChannelCount = channelCount;
3235 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 if (sharedBuffer == 0) {
3237 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3238 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3239 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003240 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 mCblk->flags = CBLK_UNDERRUN_ON;
3242 } else {
3243 mBuffer = sharedBuffer->pointer();
3244 }
3245 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3246 }
3247 } else {
3248 LOGE("not enough memory for AudioTrack size=%u", size);
3249 client->heap()->dump("AudioTrack");
3250 return;
3251 }
3252 } else {
3253 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3254 if (mCblk) { // construct the shared structure in-place.
3255 new(mCblk) audio_track_cblk_t();
3256 // clear all buffers
3257 mCblk->frameCount = frameCount;
3258 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003259 mChannelCount = channelCount;
3260 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3262 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3263 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003264 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003265 mCblk->flags = CBLK_UNDERRUN_ON;
3266 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3267 }
3268 }
3269}
3270
3271AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3272{
3273 if (mCblk) {
3274 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3275 if (mClient == NULL) {
3276 delete mCblk;
3277 }
3278 }
3279 mCblkMemory.clear(); // and free the shared memory
3280 if (mClient != NULL) {
3281 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3282 mClient.clear();
3283 }
3284}
3285
3286void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3287{
3288 buffer->raw = 0;
3289 mFrameCount = buffer->frameCount;
3290 step();
3291 buffer->frameCount = 0;
3292}
3293
3294bool AudioFlinger::ThreadBase::TrackBase::step() {
3295 bool result;
3296 audio_track_cblk_t* cblk = this->cblk();
3297
3298 result = cblk->stepServer(mFrameCount);
3299 if (!result) {
3300 LOGV("stepServer failed acquiring cblk mutex");
3301 mFlags |= STEPSERVER_FAILED;
3302 }
3303 return result;
3304}
3305
3306void AudioFlinger::ThreadBase::TrackBase::reset() {
3307 audio_track_cblk_t* cblk = this->cblk();
3308
3309 cblk->user = 0;
3310 cblk->server = 0;
3311 cblk->userBase = 0;
3312 cblk->serverBase = 0;
3313 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3314 LOGV("TrackBase::reset");
3315}
3316
3317sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3318{
3319 return mCblkMemory;
3320}
3321
3322int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3323 return (int)mCblk->sampleRate;
3324}
3325
3326int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003327 return (const int)mChannelCount;
3328}
3329
3330uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3331 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332}
3333
3334void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3335 audio_track_cblk_t* cblk = this->cblk();
3336 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3337 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3338
3339 // Check validity of returned pointer in case the track control block would have been corrupted.
3340 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3341 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3342 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 -07003343 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003345 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 return 0;
3347 }
3348
3349 return bufferStart;
3350}
3351
3352// ----------------------------------------------------------------------------
3353
3354// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3355AudioFlinger::PlaybackThread::Track::Track(
3356 const wp<ThreadBase>& thread,
3357 const sp<Client>& client,
3358 int streamType,
3359 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003360 uint32_t format,
3361 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362 int frameCount,
3363 const sp<IMemory>& sharedBuffer,
3364 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003365 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003366 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3367 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003368{
3369 if (mCblk != NULL) {
3370 sp<ThreadBase> baseThread = thread.promote();
3371 if (baseThread != 0) {
3372 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3373 mName = playbackThread->getTrackName_l();
3374 mMainBuffer = playbackThread->mixBuffer();
3375 }
3376 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3377 if (mName < 0) {
3378 LOGE("no more track names available");
3379 }
3380 mVolume[0] = 1.0f;
3381 mVolume[1] = 1.0f;
3382 mStreamType = streamType;
3383 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3384 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003385 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003386 }
3387}
3388
3389AudioFlinger::PlaybackThread::Track::~Track()
3390{
3391 LOGV("PlaybackThread::Track destructor");
3392 sp<ThreadBase> thread = mThread.promote();
3393 if (thread != 0) {
3394 Mutex::Autolock _l(thread->mLock);
3395 mState = TERMINATED;
3396 }
3397}
3398
3399void AudioFlinger::PlaybackThread::Track::destroy()
3400{
3401 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3402 // by removing it from mTracks vector, so there is a risk that this Tracks's
3403 // desctructor is called. As the destructor needs to lock mLock,
3404 // we must acquire a strong reference on this Track before locking mLock
3405 // here so that the destructor is called only when exiting this function.
3406 // On the other hand, as long as Track::destroy() is only called by
3407 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3408 // this Track with its member mTrack.
3409 sp<Track> keep(this);
3410 { // scope for mLock
3411 sp<ThreadBase> thread = mThread.promote();
3412 if (thread != 0) {
3413 if (!isOutputTrack()) {
3414 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003415 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003416 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003417 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003418
3419 // to track the speaker usage
3420 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003421 }
3422 AudioSystem::releaseOutput(thread->id());
3423 }
3424 Mutex::Autolock _l(thread->mLock);
3425 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3426 playbackThread->destroyTrack_l(this);
3427 }
3428 }
3429}
3430
3431void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3432{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003433 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 -07003434 mName - AudioMixer::TRACK0,
3435 (mClient == NULL) ? getpid() : mClient->pid(),
3436 mStreamType,
3437 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003438 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003439 mSessionId,
3440 mFrameCount,
3441 mState,
3442 mMute,
3443 mFillingUpStatus,
3444 mCblk->sampleRate,
3445 mCblk->volume[0],
3446 mCblk->volume[1],
3447 mCblk->server,
3448 mCblk->user,
3449 (int)mMainBuffer,
3450 (int)mAuxBuffer);
3451}
3452
3453status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3454{
3455 audio_track_cblk_t* cblk = this->cblk();
3456 uint32_t framesReady;
3457 uint32_t framesReq = buffer->frameCount;
3458
3459 // Check if last stepServer failed, try to step now
3460 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3461 if (!step()) goto getNextBuffer_exit;
3462 LOGV("stepServer recovered");
3463 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3464 }
3465
3466 framesReady = cblk->framesReady();
3467
3468 if (LIKELY(framesReady)) {
3469 uint32_t s = cblk->server;
3470 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3471
3472 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3473 if (framesReq > framesReady) {
3474 framesReq = framesReady;
3475 }
3476 if (s + framesReq > bufferEnd) {
3477 framesReq = bufferEnd - s;
3478 }
3479
3480 buffer->raw = getBuffer(s, framesReq);
3481 if (buffer->raw == 0) goto getNextBuffer_exit;
3482
3483 buffer->frameCount = framesReq;
3484 return NO_ERROR;
3485 }
3486
3487getNextBuffer_exit:
3488 buffer->raw = 0;
3489 buffer->frameCount = 0;
3490 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3491 return NOT_ENOUGH_DATA;
3492}
3493
3494bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003495 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496
3497 if (mCblk->framesReady() >= mCblk->frameCount ||
3498 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3499 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003500 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 return true;
3502 }
3503 return false;
3504}
3505
3506status_t AudioFlinger::PlaybackThread::Track::start()
3507{
3508 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003509 LOGV("start(%d), calling thread %d session %d",
3510 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 sp<ThreadBase> thread = mThread.promote();
3512 if (thread != 0) {
3513 Mutex::Autolock _l(thread->mLock);
3514 int state = mState;
3515 // here the track could be either new, or restarted
3516 // in both cases "unstop" the track
3517 if (mState == PAUSED) {
3518 mState = TrackBase::RESUMING;
3519 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3520 } else {
3521 mState = TrackBase::ACTIVE;
3522 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3523 }
3524
3525 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3526 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003527 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003528 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003529 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003531
3532 // to track the speaker usage
3533 if (status == NO_ERROR) {
3534 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 }
3537 if (status == NO_ERROR) {
3538 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3539 playbackThread->addTrack_l(this);
3540 } else {
3541 mState = state;
3542 }
3543 } else {
3544 status = BAD_VALUE;
3545 }
3546 return status;
3547}
3548
3549void AudioFlinger::PlaybackThread::Track::stop()
3550{
3551 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3552 sp<ThreadBase> thread = mThread.promote();
3553 if (thread != 0) {
3554 Mutex::Autolock _l(thread->mLock);
3555 int state = mState;
3556 if (mState > STOPPED) {
3557 mState = STOPPED;
3558 // If the track is not active (PAUSED and buffers full), flush buffers
3559 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3560 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3561 reset();
3562 }
3563 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3564 }
3565 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3566 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003567 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003568 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003569 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003570 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003571
3572 // to track the speaker usage
3573 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 }
3575 }
3576}
3577
3578void AudioFlinger::PlaybackThread::Track::pause()
3579{
3580 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3581 sp<ThreadBase> thread = mThread.promote();
3582 if (thread != 0) {
3583 Mutex::Autolock _l(thread->mLock);
3584 if (mState == ACTIVE || mState == RESUMING) {
3585 mState = PAUSING;
3586 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3587 if (!isOutputTrack()) {
3588 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003589 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003590 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003591 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003593
3594 // to track the speaker usage
3595 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 }
3597 }
3598 }
3599}
3600
3601void AudioFlinger::PlaybackThread::Track::flush()
3602{
3603 LOGV("flush(%d)", mName);
3604 sp<ThreadBase> thread = mThread.promote();
3605 if (thread != 0) {
3606 Mutex::Autolock _l(thread->mLock);
3607 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3608 return;
3609 }
3610 // No point remaining in PAUSED state after a flush => go to
3611 // STOPPED state
3612 mState = STOPPED;
3613
Eric Laurent38ccae22011-03-28 18:37:07 -07003614 // do not reset the track if it is still in the process of being stopped or paused.
3615 // this will be done by prepareTracks_l() when the track is stopped.
3616 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3617 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3618 reset();
3619 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 }
3621}
3622
3623void AudioFlinger::PlaybackThread::Track::reset()
3624{
3625 // Do not reset twice to avoid discarding data written just after a flush and before
3626 // the audioflinger thread detects the track is stopped.
3627 if (!mResetDone) {
3628 TrackBase::reset();
3629 // Force underrun condition to avoid false underrun callback until first data is
3630 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003631 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3632 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003633 mFillingUpStatus = FS_FILLING;
3634 mResetDone = true;
3635 }
3636}
3637
3638void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3639{
3640 mMute = muted;
3641}
3642
3643void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3644{
3645 mVolume[0] = left;
3646 mVolume[1] = right;
3647}
3648
3649status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3650{
3651 status_t status = DEAD_OBJECT;
3652 sp<ThreadBase> thread = mThread.promote();
3653 if (thread != 0) {
3654 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3655 status = playbackThread->attachAuxEffect(this, EffectId);
3656 }
3657 return status;
3658}
3659
3660void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3661{
3662 mAuxEffectId = EffectId;
3663 mAuxBuffer = buffer;
3664}
3665
3666// ----------------------------------------------------------------------------
3667
3668// RecordTrack constructor must be called with AudioFlinger::mLock held
3669AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3670 const wp<ThreadBase>& thread,
3671 const sp<Client>& client,
3672 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003673 uint32_t format,
3674 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003675 int frameCount,
3676 uint32_t flags,
3677 int sessionId)
3678 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003679 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003680 mOverflow(false)
3681{
3682 if (mCblk != NULL) {
3683 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003684 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003685 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003686 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003687 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003688 } else {
3689 mCblk->frameSize = sizeof(int8_t);
3690 }
3691 }
3692}
3693
3694AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3695{
3696 sp<ThreadBase> thread = mThread.promote();
3697 if (thread != 0) {
3698 AudioSystem::releaseInput(thread->id());
3699 }
3700}
3701
3702status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3703{
3704 audio_track_cblk_t* cblk = this->cblk();
3705 uint32_t framesAvail;
3706 uint32_t framesReq = buffer->frameCount;
3707
3708 // Check if last stepServer failed, try to step now
3709 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3710 if (!step()) goto getNextBuffer_exit;
3711 LOGV("stepServer recovered");
3712 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3713 }
3714
3715 framesAvail = cblk->framesAvailable_l();
3716
3717 if (LIKELY(framesAvail)) {
3718 uint32_t s = cblk->server;
3719 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3720
3721 if (framesReq > framesAvail) {
3722 framesReq = framesAvail;
3723 }
3724 if (s + framesReq > bufferEnd) {
3725 framesReq = bufferEnd - s;
3726 }
3727
3728 buffer->raw = getBuffer(s, framesReq);
3729 if (buffer->raw == 0) goto getNextBuffer_exit;
3730
3731 buffer->frameCount = framesReq;
3732 return NO_ERROR;
3733 }
3734
3735getNextBuffer_exit:
3736 buffer->raw = 0;
3737 buffer->frameCount = 0;
3738 return NOT_ENOUGH_DATA;
3739}
3740
3741status_t AudioFlinger::RecordThread::RecordTrack::start()
3742{
3743 sp<ThreadBase> thread = mThread.promote();
3744 if (thread != 0) {
3745 RecordThread *recordThread = (RecordThread *)thread.get();
3746 return recordThread->start(this);
3747 } else {
3748 return BAD_VALUE;
3749 }
3750}
3751
3752void AudioFlinger::RecordThread::RecordTrack::stop()
3753{
3754 sp<ThreadBase> thread = mThread.promote();
3755 if (thread != 0) {
3756 RecordThread *recordThread = (RecordThread *)thread.get();
3757 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003758 TrackBase::reset();
3759 // Force overerrun condition to avoid false overrun callback until first data is
3760 // read from buffer
3761 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003762 }
3763}
3764
3765void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3766{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003767 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003768 (mClient == NULL) ? getpid() : mClient->pid(),
3769 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003770 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 mSessionId,
3772 mFrameCount,
3773 mState,
3774 mCblk->sampleRate,
3775 mCblk->server,
3776 mCblk->user);
3777}
3778
3779
3780// ----------------------------------------------------------------------------
3781
3782AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3783 const wp<ThreadBase>& thread,
3784 DuplicatingThread *sourceThread,
3785 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003786 uint32_t format,
3787 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003789 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 mActive(false), mSourceThread(sourceThread)
3791{
3792
3793 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3794 if (mCblk != NULL) {
3795 mCblk->flags |= CBLK_DIRECTION_OUT;
3796 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3797 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3798 mOutBuffer.frameCount = 0;
3799 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003800 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3801 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3802 mCblk, mBuffer, mCblk->buffers,
3803 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003804 } else {
3805 LOGW("Error creating output track on thread %p", playbackThread);
3806 }
3807}
3808
3809AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3810{
3811 clearBufferQueue();
3812}
3813
3814status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3815{
3816 status_t status = Track::start();
3817 if (status != NO_ERROR) {
3818 return status;
3819 }
3820
3821 mActive = true;
3822 mRetryCount = 127;
3823 return status;
3824}
3825
3826void AudioFlinger::PlaybackThread::OutputTrack::stop()
3827{
3828 Track::stop();
3829 clearBufferQueue();
3830 mOutBuffer.frameCount = 0;
3831 mActive = false;
3832}
3833
3834bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3835{
3836 Buffer *pInBuffer;
3837 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003838 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 bool outputBufferFull = false;
3840 inBuffer.frameCount = frames;
3841 inBuffer.i16 = data;
3842
3843 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3844
3845 if (!mActive && frames != 0) {
3846 start();
3847 sp<ThreadBase> thread = mThread.promote();
3848 if (thread != 0) {
3849 MixerThread *mixerThread = (MixerThread *)thread.get();
3850 if (mCblk->frameCount > frames){
3851 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3852 uint32_t startFrames = (mCblk->frameCount - frames);
3853 pInBuffer = new Buffer;
3854 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3855 pInBuffer->frameCount = startFrames;
3856 pInBuffer->i16 = pInBuffer->mBuffer;
3857 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3858 mBufferQueue.add(pInBuffer);
3859 } else {
3860 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3861 }
3862 }
3863 }
3864 }
3865
3866 while (waitTimeLeftMs) {
3867 // First write pending buffers, then new data
3868 if (mBufferQueue.size()) {
3869 pInBuffer = mBufferQueue.itemAt(0);
3870 } else {
3871 pInBuffer = &inBuffer;
3872 }
3873
3874 if (pInBuffer->frameCount == 0) {
3875 break;
3876 }
3877
3878 if (mOutBuffer.frameCount == 0) {
3879 mOutBuffer.frameCount = pInBuffer->frameCount;
3880 nsecs_t startTime = systemTime();
3881 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3882 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3883 outputBufferFull = true;
3884 break;
3885 }
3886 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3887 if (waitTimeLeftMs >= waitTimeMs) {
3888 waitTimeLeftMs -= waitTimeMs;
3889 } else {
3890 waitTimeLeftMs = 0;
3891 }
3892 }
3893
3894 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3895 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3896 mCblk->stepUser(outFrames);
3897 pInBuffer->frameCount -= outFrames;
3898 pInBuffer->i16 += outFrames * channelCount;
3899 mOutBuffer.frameCount -= outFrames;
3900 mOutBuffer.i16 += outFrames * channelCount;
3901
3902 if (pInBuffer->frameCount == 0) {
3903 if (mBufferQueue.size()) {
3904 mBufferQueue.removeAt(0);
3905 delete [] pInBuffer->mBuffer;
3906 delete pInBuffer;
3907 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3908 } else {
3909 break;
3910 }
3911 }
3912 }
3913
3914 // If we could not write all frames, allocate a buffer and queue it for next time.
3915 if (inBuffer.frameCount) {
3916 sp<ThreadBase> thread = mThread.promote();
3917 if (thread != 0 && !thread->standby()) {
3918 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3919 pInBuffer = new Buffer;
3920 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3921 pInBuffer->frameCount = inBuffer.frameCount;
3922 pInBuffer->i16 = pInBuffer->mBuffer;
3923 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3924 mBufferQueue.add(pInBuffer);
3925 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3926 } else {
3927 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3928 }
3929 }
3930 }
3931
3932 // Calling write() with a 0 length buffer, means that no more data will be written:
3933 // If no more buffers are pending, fill output track buffer to make sure it is started
3934 // by output mixer.
3935 if (frames == 0 && mBufferQueue.size() == 0) {
3936 if (mCblk->user < mCblk->frameCount) {
3937 frames = mCblk->frameCount - mCblk->user;
3938 pInBuffer = new Buffer;
3939 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3940 pInBuffer->frameCount = frames;
3941 pInBuffer->i16 = pInBuffer->mBuffer;
3942 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3943 mBufferQueue.add(pInBuffer);
3944 } else if (mActive) {
3945 stop();
3946 }
3947 }
3948
3949 return outputBufferFull;
3950}
3951
3952status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3953{
3954 int active;
3955 status_t result;
3956 audio_track_cblk_t* cblk = mCblk;
3957 uint32_t framesReq = buffer->frameCount;
3958
3959// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3960 buffer->frameCount = 0;
3961
3962 uint32_t framesAvail = cblk->framesAvailable();
3963
3964
3965 if (framesAvail == 0) {
3966 Mutex::Autolock _l(cblk->lock);
3967 goto start_loop_here;
3968 while (framesAvail == 0) {
3969 active = mActive;
3970 if (UNLIKELY(!active)) {
3971 LOGV("Not active and NO_MORE_BUFFERS");
3972 return AudioTrack::NO_MORE_BUFFERS;
3973 }
3974 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3975 if (result != NO_ERROR) {
3976 return AudioTrack::NO_MORE_BUFFERS;
3977 }
3978 // read the server count again
3979 start_loop_here:
3980 framesAvail = cblk->framesAvailable_l();
3981 }
3982 }
3983
3984// if (framesAvail < framesReq) {
3985// return AudioTrack::NO_MORE_BUFFERS;
3986// }
3987
3988 if (framesReq > framesAvail) {
3989 framesReq = framesAvail;
3990 }
3991
3992 uint32_t u = cblk->user;
3993 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3994
3995 if (u + framesReq > bufferEnd) {
3996 framesReq = bufferEnd - u;
3997 }
3998
3999 buffer->frameCount = framesReq;
4000 buffer->raw = (void *)cblk->buffer(u);
4001 return NO_ERROR;
4002}
4003
4004
4005void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4006{
4007 size_t size = mBufferQueue.size();
4008 Buffer *pBuffer;
4009
4010 for (size_t i = 0; i < size; i++) {
4011 pBuffer = mBufferQueue.itemAt(i);
4012 delete [] pBuffer->mBuffer;
4013 delete pBuffer;
4014 }
4015 mBufferQueue.clear();
4016}
4017
4018// ----------------------------------------------------------------------------
4019
4020AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4021 : RefBase(),
4022 mAudioFlinger(audioFlinger),
4023 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4024 mPid(pid)
4025{
4026 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4027}
4028
4029// Client destructor must be called with AudioFlinger::mLock held
4030AudioFlinger::Client::~Client()
4031{
4032 mAudioFlinger->removeClient_l(mPid);
4033}
4034
4035const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4036{
4037 return mMemoryDealer;
4038}
4039
4040// ----------------------------------------------------------------------------
4041
4042AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4043 const sp<IAudioFlingerClient>& client,
4044 pid_t pid)
4045 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4046{
4047}
4048
4049AudioFlinger::NotificationClient::~NotificationClient()
4050{
4051 mClient.clear();
4052}
4053
4054void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4055{
4056 sp<NotificationClient> keep(this);
4057 {
4058 mAudioFlinger->removeNotificationClient(mPid);
4059 }
4060}
4061
4062// ----------------------------------------------------------------------------
4063
4064AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4065 : BnAudioTrack(),
4066 mTrack(track)
4067{
4068}
4069
4070AudioFlinger::TrackHandle::~TrackHandle() {
4071 // just stop the track on deletion, associated resources
4072 // will be freed from the main thread once all pending buffers have
4073 // been played. Unless it's not in the active track list, in which
4074 // case we free everything now...
4075 mTrack->destroy();
4076}
4077
4078status_t AudioFlinger::TrackHandle::start() {
4079 return mTrack->start();
4080}
4081
4082void AudioFlinger::TrackHandle::stop() {
4083 mTrack->stop();
4084}
4085
4086void AudioFlinger::TrackHandle::flush() {
4087 mTrack->flush();
4088}
4089
4090void AudioFlinger::TrackHandle::mute(bool e) {
4091 mTrack->mute(e);
4092}
4093
4094void AudioFlinger::TrackHandle::pause() {
4095 mTrack->pause();
4096}
4097
4098void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4099 mTrack->setVolume(left, right);
4100}
4101
4102sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4103 return mTrack->getCblk();
4104}
4105
4106status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4107{
4108 return mTrack->attachAuxEffect(EffectId);
4109}
4110
4111status_t AudioFlinger::TrackHandle::onTransact(
4112 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4113{
4114 return BnAudioTrack::onTransact(code, data, reply, flags);
4115}
4116
4117// ----------------------------------------------------------------------------
4118
4119sp<IAudioRecord> AudioFlinger::openRecord(
4120 pid_t pid,
4121 int input,
4122 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004123 uint32_t format,
4124 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125 int frameCount,
4126 uint32_t flags,
4127 int *sessionId,
4128 status_t *status)
4129{
4130 sp<RecordThread::RecordTrack> recordTrack;
4131 sp<RecordHandle> recordHandle;
4132 sp<Client> client;
4133 wp<Client> wclient;
4134 status_t lStatus;
4135 RecordThread *thread;
4136 size_t inFrameCount;
4137 int lSessionId;
4138
4139 // check calling permissions
4140 if (!recordingAllowed()) {
4141 lStatus = PERMISSION_DENIED;
4142 goto Exit;
4143 }
4144
4145 // add client to list
4146 { // scope for mLock
4147 Mutex::Autolock _l(mLock);
4148 thread = checkRecordThread_l(input);
4149 if (thread == NULL) {
4150 lStatus = BAD_VALUE;
4151 goto Exit;
4152 }
4153
4154 wclient = mClients.valueFor(pid);
4155 if (wclient != NULL) {
4156 client = wclient.promote();
4157 } else {
4158 client = new Client(this, pid);
4159 mClients.add(pid, client);
4160 }
4161
4162 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004163 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 lSessionId = *sessionId;
4165 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004166 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167 if (sessionId != NULL) {
4168 *sessionId = lSessionId;
4169 }
4170 }
4171 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004172 recordTrack = thread->createRecordTrack_l(client,
4173 sampleRate,
4174 format,
4175 channelMask,
4176 frameCount,
4177 flags,
4178 lSessionId,
4179 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004181 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004182 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4183 // destructor is called by the TrackBase destructor with mLock held
4184 client.clear();
4185 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004186 goto Exit;
4187 }
4188
4189 // return to handle to client
4190 recordHandle = new RecordHandle(recordTrack);
4191 lStatus = NO_ERROR;
4192
4193Exit:
4194 if (status) {
4195 *status = lStatus;
4196 }
4197 return recordHandle;
4198}
4199
4200// ----------------------------------------------------------------------------
4201
4202AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4203 : BnAudioRecord(),
4204 mRecordTrack(recordTrack)
4205{
4206}
4207
4208AudioFlinger::RecordHandle::~RecordHandle() {
4209 stop();
4210}
4211
4212status_t AudioFlinger::RecordHandle::start() {
4213 LOGV("RecordHandle::start()");
4214 return mRecordTrack->start();
4215}
4216
4217void AudioFlinger::RecordHandle::stop() {
4218 LOGV("RecordHandle::stop()");
4219 mRecordTrack->stop();
4220}
4221
4222sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4223 return mRecordTrack->getCblk();
4224}
4225
4226status_t AudioFlinger::RecordHandle::onTransact(
4227 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4228{
4229 return BnAudioRecord::onTransact(code, data, reply, flags);
4230}
4231
4232// ----------------------------------------------------------------------------
4233
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004234AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4235 AudioStreamIn *input,
4236 uint32_t sampleRate,
4237 uint32_t channels,
4238 int id,
4239 uint32_t device) :
4240 ThreadBase(audioFlinger, id, device),
4241 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004242{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004243 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004244
4245 snprintf(mName, kNameLength, "AudioIn_%d", id);
4246
Dima Zavinfce7a472011-04-19 22:30:36 -07004247 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248 mReqSampleRate = sampleRate;
4249 readInputParameters();
4250}
4251
4252
4253AudioFlinger::RecordThread::~RecordThread()
4254{
4255 delete[] mRsmpInBuffer;
4256 if (mResampler != 0) {
4257 delete mResampler;
4258 delete[] mRsmpOutBuffer;
4259 }
4260}
4261
4262void AudioFlinger::RecordThread::onFirstRef()
4263{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004264 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265}
4266
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004267status_t AudioFlinger::RecordThread::readyToRun()
4268{
4269 status_t status = initCheck();
4270 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4271 return status;
4272}
4273
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274bool AudioFlinger::RecordThread::threadLoop()
4275{
4276 AudioBufferProvider::Buffer buffer;
4277 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004278 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279
Eric Laurent44d98482010-09-30 16:12:31 -07004280 nsecs_t lastWarning = 0;
4281
Eric Laurentfeb0db62011-07-22 09:04:31 -07004282 acquireWakeLock();
4283
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284 // start recording
4285 while (!exitPending()) {
4286
4287 processConfigEvents();
4288
4289 { // scope for mLock
4290 Mutex::Autolock _l(mLock);
4291 checkForNewParameters_l();
4292 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4293 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004294 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004295 mStandby = true;
4296 }
4297
4298 if (exitPending()) break;
4299
Eric Laurentfeb0db62011-07-22 09:04:31 -07004300 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004301 LOGV("RecordThread: loop stopping");
4302 // go to sleep
4303 mWaitWorkCV.wait(mLock);
4304 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004305 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004306 continue;
4307 }
4308 if (mActiveTrack != 0) {
4309 if (mActiveTrack->mState == TrackBase::PAUSING) {
4310 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004311 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004312 mStandby = true;
4313 }
4314 mActiveTrack.clear();
4315 mStartStopCond.broadcast();
4316 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4317 if (mReqChannelCount != mActiveTrack->channelCount()) {
4318 mActiveTrack.clear();
4319 mStartStopCond.broadcast();
4320 } else if (mBytesRead != 0) {
4321 // record start succeeds only if first read from audio input
4322 // succeeds
4323 if (mBytesRead > 0) {
4324 mActiveTrack->mState = TrackBase::ACTIVE;
4325 } else {
4326 mActiveTrack.clear();
4327 }
4328 mStartStopCond.broadcast();
4329 }
4330 mStandby = false;
4331 }
4332 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004333 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 }
4335
4336 if (mActiveTrack != 0) {
4337 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4338 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004339 unlockEffectChains(effectChains);
4340 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004341 continue;
4342 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004343 for (size_t i = 0; i < effectChains.size(); i ++) {
4344 effectChains[i]->process_l();
4345 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004346
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 buffer.frameCount = mFrameCount;
4348 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4349 size_t framesOut = buffer.frameCount;
4350 if (mResampler == 0) {
4351 // no resampling
4352 while (framesOut) {
4353 size_t framesIn = mFrameCount - mRsmpInIndex;
4354 if (framesIn) {
4355 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4356 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4357 if (framesIn > framesOut)
4358 framesIn = framesOut;
4359 mRsmpInIndex += framesIn;
4360 framesOut -= framesIn;
4361 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004362 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004363 memcpy(dst, src, framesIn * mFrameSize);
4364 } else {
4365 int16_t *src16 = (int16_t *)src;
4366 int16_t *dst16 = (int16_t *)dst;
4367 if (mChannelCount == 1) {
4368 while (framesIn--) {
4369 *dst16++ = *src16;
4370 *dst16++ = *src16++;
4371 }
4372 } else {
4373 while (framesIn--) {
4374 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4375 src16 += 2;
4376 }
4377 }
4378 }
4379 }
4380 if (framesOut && mFrameCount == mRsmpInIndex) {
4381 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004382 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004383 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 framesOut = 0;
4385 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004386 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004387 mRsmpInIndex = 0;
4388 }
4389 if (mBytesRead < 0) {
4390 LOGE("Error reading audio input");
4391 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4392 // Force input into standby so that it tries to
4393 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004394 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004395 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004396 }
4397 mRsmpInIndex = mFrameCount;
4398 framesOut = 0;
4399 buffer.frameCount = 0;
4400 }
4401 }
4402 }
4403 } else {
4404 // resampling
4405
4406 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4407 // alter output frame count as if we were expecting stereo samples
4408 if (mChannelCount == 1 && mReqChannelCount == 1) {
4409 framesOut >>= 1;
4410 }
4411 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4412 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4413 // are 32 bit aligned which should be always true.
4414 if (mChannelCount == 2 && mReqChannelCount == 1) {
4415 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4416 // the resampler always outputs stereo samples: do post stereo to mono conversion
4417 int16_t *src = (int16_t *)mRsmpOutBuffer;
4418 int16_t *dst = buffer.i16;
4419 while (framesOut--) {
4420 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4421 src += 2;
4422 }
4423 } else {
4424 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4425 }
4426
4427 }
4428 mActiveTrack->releaseBuffer(&buffer);
4429 mActiveTrack->overflow();
4430 }
4431 // client isn't retrieving buffers fast enough
4432 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004433 if (!mActiveTrack->setOverflow()) {
4434 nsecs_t now = systemTime();
4435 if ((now - lastWarning) > kWarningThrottle) {
4436 LOGW("RecordThread: buffer overflow");
4437 lastWarning = now;
4438 }
4439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004440 // Release the processor for a while before asking for a new buffer.
4441 // This will give the application more chance to read from the buffer and
4442 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004443 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004444 }
4445 }
Eric Laurentec437d82011-07-26 20:54:46 -07004446 // enable changes in effect chain
4447 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004448 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449 }
4450
4451 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004452 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004453 }
4454 mActiveTrack.clear();
4455
4456 mStartStopCond.broadcast();
4457
Eric Laurentfeb0db62011-07-22 09:04:31 -07004458 releaseWakeLock();
4459
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 LOGV("RecordThread %p exiting", this);
4461 return false;
4462}
4463
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004464
4465sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4466 const sp<AudioFlinger::Client>& client,
4467 uint32_t sampleRate,
4468 int format,
4469 int channelMask,
4470 int frameCount,
4471 uint32_t flags,
4472 int sessionId,
4473 status_t *status)
4474{
4475 sp<RecordTrack> track;
4476 status_t lStatus;
4477
4478 lStatus = initCheck();
4479 if (lStatus != NO_ERROR) {
4480 LOGE("Audio driver not initialized.");
4481 goto Exit;
4482 }
4483
4484 { // scope for mLock
4485 Mutex::Autolock _l(mLock);
4486
4487 track = new RecordTrack(this, client, sampleRate,
4488 format, channelMask, frameCount, flags, sessionId);
4489
4490 if (track->getCblk() == NULL) {
4491 lStatus = NO_MEMORY;
4492 goto Exit;
4493 }
4494
4495 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004496 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4497 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004498 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004499 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4500 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004501 }
4502 lStatus = NO_ERROR;
4503
4504Exit:
4505 if (status) {
4506 *status = lStatus;
4507 }
4508 return track;
4509}
4510
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4512{
4513 LOGV("RecordThread::start");
4514 sp <ThreadBase> strongMe = this;
4515 status_t status = NO_ERROR;
4516 {
4517 AutoMutex lock(&mLock);
4518 if (mActiveTrack != 0) {
4519 if (recordTrack != mActiveTrack.get()) {
4520 status = -EBUSY;
4521 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4522 mActiveTrack->mState = TrackBase::ACTIVE;
4523 }
4524 return status;
4525 }
4526
4527 recordTrack->mState = TrackBase::IDLE;
4528 mActiveTrack = recordTrack;
4529 mLock.unlock();
4530 status_t status = AudioSystem::startInput(mId);
4531 mLock.lock();
4532 if (status != NO_ERROR) {
4533 mActiveTrack.clear();
4534 return status;
4535 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004536 mRsmpInIndex = mFrameCount;
4537 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004538 if (mResampler != NULL) {
4539 mResampler->reset();
4540 }
4541 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 // signal thread to start
4543 LOGV("Signal record thread");
4544 mWaitWorkCV.signal();
4545 // do not wait for mStartStopCond if exiting
4546 if (mExiting) {
4547 mActiveTrack.clear();
4548 status = INVALID_OPERATION;
4549 goto startError;
4550 }
4551 mStartStopCond.wait(mLock);
4552 if (mActiveTrack == 0) {
4553 LOGV("Record failed to start");
4554 status = BAD_VALUE;
4555 goto startError;
4556 }
4557 LOGV("Record started OK");
4558 return status;
4559 }
4560startError:
4561 AudioSystem::stopInput(mId);
4562 return status;
4563}
4564
4565void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4566 LOGV("RecordThread::stop");
4567 sp <ThreadBase> strongMe = this;
4568 {
4569 AutoMutex lock(&mLock);
4570 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4571 mActiveTrack->mState = TrackBase::PAUSING;
4572 // do not wait for mStartStopCond if exiting
4573 if (mExiting) {
4574 return;
4575 }
4576 mStartStopCond.wait(mLock);
4577 // if we have been restarted, recordTrack == mActiveTrack.get() here
4578 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4579 mLock.unlock();
4580 AudioSystem::stopInput(mId);
4581 mLock.lock();
4582 LOGV("Record stopped OK");
4583 }
4584 }
4585 }
4586}
4587
4588status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4589{
4590 const size_t SIZE = 256;
4591 char buffer[SIZE];
4592 String8 result;
4593 pid_t pid = 0;
4594
4595 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4596 result.append(buffer);
4597
4598 if (mActiveTrack != 0) {
4599 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004600 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 mActiveTrack->dump(buffer, SIZE);
4602 result.append(buffer);
4603
4604 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4605 result.append(buffer);
4606 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4607 result.append(buffer);
4608 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4609 result.append(buffer);
4610 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4611 result.append(buffer);
4612 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4613 result.append(buffer);
4614
4615
4616 } else {
4617 result.append("No record client\n");
4618 }
4619 write(fd, result.string(), result.size());
4620
4621 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004622 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004623
4624 return NO_ERROR;
4625}
4626
4627status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4628{
4629 size_t framesReq = buffer->frameCount;
4630 size_t framesReady = mFrameCount - mRsmpInIndex;
4631 int channelCount;
4632
4633 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004634 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 if (mBytesRead < 0) {
4636 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4637 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4638 // Force input into standby so that it tries to
4639 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004640 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004641 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 }
4643 buffer->raw = 0;
4644 buffer->frameCount = 0;
4645 return NOT_ENOUGH_DATA;
4646 }
4647 mRsmpInIndex = 0;
4648 framesReady = mFrameCount;
4649 }
4650
4651 if (framesReq > framesReady) {
4652 framesReq = framesReady;
4653 }
4654
4655 if (mChannelCount == 1 && mReqChannelCount == 2) {
4656 channelCount = 1;
4657 } else {
4658 channelCount = 2;
4659 }
4660 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4661 buffer->frameCount = framesReq;
4662 return NO_ERROR;
4663}
4664
4665void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4666{
4667 mRsmpInIndex += buffer->frameCount;
4668 buffer->frameCount = 0;
4669}
4670
4671bool AudioFlinger::RecordThread::checkForNewParameters_l()
4672{
4673 bool reconfig = false;
4674
4675 while (!mNewParameters.isEmpty()) {
4676 status_t status = NO_ERROR;
4677 String8 keyValuePair = mNewParameters[0];
4678 AudioParameter param = AudioParameter(keyValuePair);
4679 int value;
4680 int reqFormat = mFormat;
4681 int reqSamplingRate = mReqSampleRate;
4682 int reqChannelCount = mReqChannelCount;
4683
4684 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4685 reqSamplingRate = value;
4686 reconfig = true;
4687 }
4688 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4689 reqFormat = value;
4690 reconfig = true;
4691 }
4692 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004693 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004694 reconfig = true;
4695 }
4696 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4697 // do not accept frame count changes if tracks are open as the track buffer
4698 // size depends on frame count and correct behavior would not be garantied
4699 // if frame count is changed after track creation
4700 if (mActiveTrack != 0) {
4701 status = INVALID_OPERATION;
4702 } else {
4703 reconfig = true;
4704 }
4705 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004706 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4707 // forward device change to effects that have requested to be
4708 // aware of attached audio device.
4709 for (size_t i = 0; i < mEffectChains.size(); i++) {
4710 mEffectChains[i]->setDevice_l(value);
4711 }
4712 // store input device and output device but do not forward output device to audio HAL.
4713 // Note that status is ignored by the caller for output device
4714 // (see AudioFlinger::setParameters()
4715 if (value & AUDIO_DEVICE_OUT_ALL) {
4716 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4717 status = BAD_VALUE;
4718 } else {
4719 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004720 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4721 if (mTrack != NULL) {
4722 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004723 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004724 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4725 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4726 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004727 }
4728 mDevice |= (uint32_t)value;
4729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004731 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004733 mInput->stream->common.standby(&mInput->stream->common);
4734 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004735 }
4736 if (reconfig) {
4737 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004738 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004739 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004740 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4741 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004742 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743 status = NO_ERROR;
4744 }
4745 if (status == NO_ERROR) {
4746 readInputParameters();
4747 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4748 }
4749 }
4750 }
4751
4752 mNewParameters.removeAt(0);
4753
4754 mParamStatus = status;
4755 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004756 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4757 // already timed out waiting for the status and will never signal the condition.
4758 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004759 }
4760 return reconfig;
4761}
4762
4763String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4764{
Dima Zavinfce7a472011-04-19 22:30:36 -07004765 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004766 String8 out_s8 = String8();
4767
4768 Mutex::Autolock _l(mLock);
4769 if (initCheck() != NO_ERROR) {
4770 return out_s8;
4771 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004772
Dima Zavin799a70e2011-04-18 16:57:27 -07004773 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004774 out_s8 = String8(s);
4775 free(s);
4776 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004777}
4778
4779void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4780 AudioSystem::OutputDescriptor desc;
4781 void *param2 = 0;
4782
4783 switch (event) {
4784 case AudioSystem::INPUT_OPENED:
4785 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004786 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787 desc.samplingRate = mSampleRate;
4788 desc.format = mFormat;
4789 desc.frameCount = mFrameCount;
4790 desc.latency = 0;
4791 param2 = &desc;
4792 break;
4793
4794 case AudioSystem::INPUT_CLOSED:
4795 default:
4796 break;
4797 }
4798 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4799}
4800
4801void AudioFlinger::RecordThread::readInputParameters()
4802{
4803 if (mRsmpInBuffer) delete mRsmpInBuffer;
4804 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4805 if (mResampler) delete mResampler;
4806 mResampler = 0;
4807
Dima Zavin799a70e2011-04-18 16:57:27 -07004808 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004809 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4810 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004811 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4812 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4813 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 mFrameCount = mInputBytes / mFrameSize;
4815 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4816
4817 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4818 {
4819 int channelCount;
4820 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4821 // stereo to mono post process as the resampler always outputs stereo.
4822 if (mChannelCount == 1 && mReqChannelCount == 2) {
4823 channelCount = 1;
4824 } else {
4825 channelCount = 2;
4826 }
4827 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4828 mResampler->setSampleRate(mSampleRate);
4829 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4830 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4831
4832 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4833 if (mChannelCount == 1 && mReqChannelCount == 1) {
4834 mFrameCount >>= 1;
4835 }
4836
4837 }
4838 mRsmpInIndex = mFrameCount;
4839}
4840
4841unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4842{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004843 Mutex::Autolock _l(mLock);
4844 if (initCheck() != NO_ERROR) {
4845 return 0;
4846 }
4847
Dima Zavin799a70e2011-04-18 16:57:27 -07004848 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849}
4850
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004851uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4852{
4853 Mutex::Autolock _l(mLock);
4854 uint32_t result = 0;
4855 if (getEffectChain_l(sessionId) != 0) {
4856 result = EFFECT_SESSION;
4857 }
4858
4859 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4860 result |= TRACK_SESSION;
4861 }
4862
4863 return result;
4864}
4865
Eric Laurent59bd0da2011-08-01 09:52:20 -07004866AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4867{
4868 Mutex::Autolock _l(mLock);
4869 return mTrack;
4870}
4871
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004872AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4873{
4874 Mutex::Autolock _l(mLock);
4875 return mInput;
4876}
4877
4878AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4879{
4880 Mutex::Autolock _l(mLock);
4881 AudioStreamIn *input = mInput;
4882 mInput = NULL;
4883 return input;
4884}
4885
4886// this method must always be called either with ThreadBase mLock held or inside the thread loop
4887audio_stream_t* AudioFlinger::RecordThread::stream()
4888{
4889 if (mInput == NULL) {
4890 return NULL;
4891 }
4892 return &mInput->stream->common;
4893}
4894
4895
Mathias Agopian65ab4712010-07-14 17:59:35 -07004896// ----------------------------------------------------------------------------
4897
4898int AudioFlinger::openOutput(uint32_t *pDevices,
4899 uint32_t *pSamplingRate,
4900 uint32_t *pFormat,
4901 uint32_t *pChannels,
4902 uint32_t *pLatencyMs,
4903 uint32_t flags)
4904{
4905 status_t status;
4906 PlaybackThread *thread = NULL;
4907 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4908 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4909 uint32_t format = pFormat ? *pFormat : 0;
4910 uint32_t channels = pChannels ? *pChannels : 0;
4911 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004912 audio_stream_out_t *outStream;
4913 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004914
4915 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4916 pDevices ? *pDevices : 0,
4917 samplingRate,
4918 format,
4919 channels,
4920 flags);
4921
4922 if (pDevices == NULL || *pDevices == 0) {
4923 return 0;
4924 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004925
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 Mutex::Autolock _l(mLock);
4927
Dima Zavin799a70e2011-04-18 16:57:27 -07004928 outHwDev = findSuitableHwDev_l(*pDevices);
4929 if (outHwDev == NULL)
4930 return 0;
4931
4932 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4933 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004934 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004935 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 samplingRate,
4937 format,
4938 channels,
4939 status);
4940
4941 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004942 if (outStream != NULL) {
4943 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004944 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004945
Dima Zavinfce7a472011-04-19 22:30:36 -07004946 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4947 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4948 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004949 thread = new DirectOutputThread(this, output, id, *pDevices);
4950 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4951 } else {
4952 thread = new MixerThread(this, output, id, *pDevices);
4953 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004954 }
4955 mPlaybackThreads.add(id, thread);
4956
4957 if (pSamplingRate) *pSamplingRate = samplingRate;
4958 if (pFormat) *pFormat = format;
4959 if (pChannels) *pChannels = channels;
4960 if (pLatencyMs) *pLatencyMs = thread->latency();
4961
4962 // notify client processes of the new output creation
4963 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4964 return id;
4965 }
4966
4967 return 0;
4968}
4969
4970int AudioFlinger::openDuplicateOutput(int output1, int output2)
4971{
4972 Mutex::Autolock _l(mLock);
4973 MixerThread *thread1 = checkMixerThread_l(output1);
4974 MixerThread *thread2 = checkMixerThread_l(output2);
4975
4976 if (thread1 == NULL || thread2 == NULL) {
4977 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4978 return 0;
4979 }
4980
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004981 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004982 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4983 thread->addOutputTrack(thread2);
4984 mPlaybackThreads.add(id, thread);
4985 // notify client processes of the new output creation
4986 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4987 return id;
4988}
4989
4990status_t AudioFlinger::closeOutput(int output)
4991{
4992 // keep strong reference on the playback thread so that
4993 // it is not destroyed while exit() is executed
4994 sp <PlaybackThread> thread;
4995 {
4996 Mutex::Autolock _l(mLock);
4997 thread = checkPlaybackThread_l(output);
4998 if (thread == NULL) {
4999 return BAD_VALUE;
5000 }
5001
5002 LOGV("closeOutput() %d", output);
5003
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005004 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005005 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005006 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5008 dupThread->removeOutputTrack((MixerThread *)thread.get());
5009 }
5010 }
5011 }
5012 void *param2 = 0;
5013 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5014 mPlaybackThreads.removeItem(output);
5015 }
5016 thread->exit();
5017
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005018 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005019 AudioStreamOut *out = thread->clearOutput();
5020 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005021 out->hwDev->close_output_stream(out->hwDev, out->stream);
5022 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 }
5024 return NO_ERROR;
5025}
5026
5027status_t AudioFlinger::suspendOutput(int output)
5028{
5029 Mutex::Autolock _l(mLock);
5030 PlaybackThread *thread = checkPlaybackThread_l(output);
5031
5032 if (thread == NULL) {
5033 return BAD_VALUE;
5034 }
5035
5036 LOGV("suspendOutput() %d", output);
5037 thread->suspend();
5038
5039 return NO_ERROR;
5040}
5041
5042status_t AudioFlinger::restoreOutput(int output)
5043{
5044 Mutex::Autolock _l(mLock);
5045 PlaybackThread *thread = checkPlaybackThread_l(output);
5046
5047 if (thread == NULL) {
5048 return BAD_VALUE;
5049 }
5050
5051 LOGV("restoreOutput() %d", output);
5052
5053 thread->restore();
5054
5055 return NO_ERROR;
5056}
5057
5058int AudioFlinger::openInput(uint32_t *pDevices,
5059 uint32_t *pSamplingRate,
5060 uint32_t *pFormat,
5061 uint32_t *pChannels,
5062 uint32_t acoustics)
5063{
5064 status_t status;
5065 RecordThread *thread = NULL;
5066 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5067 uint32_t format = pFormat ? *pFormat : 0;
5068 uint32_t channels = pChannels ? *pChannels : 0;
5069 uint32_t reqSamplingRate = samplingRate;
5070 uint32_t reqFormat = format;
5071 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 audio_stream_in_t *inStream;
5073 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005074
5075 if (pDevices == NULL || *pDevices == 0) {
5076 return 0;
5077 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005078
Mathias Agopian65ab4712010-07-14 17:59:35 -07005079 Mutex::Autolock _l(mLock);
5080
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 inHwDev = findSuitableHwDev_l(*pDevices);
5082 if (inHwDev == NULL)
5083 return 0;
5084
5085 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5086 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005087 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005088 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005089 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005090 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 samplingRate,
5092 format,
5093 channels,
5094 acoustics,
5095 status);
5096
5097 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5098 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5099 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005100 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005101 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005102 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005103 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005104 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005105 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5106 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005107 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005108 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 }
5110
Dima Zavin799a70e2011-04-18 16:57:27 -07005111 if (inStream != NULL) {
5112 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5113
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005114 int id = nextUniqueId();
5115 // Start record thread
5116 // RecorThread require both input and output device indication to forward to audio
5117 // pre processing modules
5118 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5119 thread = new RecordThread(this,
5120 input,
5121 reqSamplingRate,
5122 reqChannels,
5123 id,
5124 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005125 mRecordThreads.add(id, thread);
5126 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5127 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5128 if (pFormat) *pFormat = format;
5129 if (pChannels) *pChannels = reqChannels;
5130
Dima Zavin799a70e2011-04-18 16:57:27 -07005131 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005132
5133 // notify client processes of the new input creation
5134 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5135 return id;
5136 }
5137
5138 return 0;
5139}
5140
5141status_t AudioFlinger::closeInput(int input)
5142{
5143 // keep strong reference on the record thread so that
5144 // it is not destroyed while exit() is executed
5145 sp <RecordThread> thread;
5146 {
5147 Mutex::Autolock _l(mLock);
5148 thread = checkRecordThread_l(input);
5149 if (thread == NULL) {
5150 return BAD_VALUE;
5151 }
5152
5153 LOGV("closeInput() %d", input);
5154 void *param2 = 0;
5155 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5156 mRecordThreads.removeItem(input);
5157 }
5158 thread->exit();
5159
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005160 AudioStreamIn *in = thread->clearInput();
5161 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005162 in->hwDev->close_input_stream(in->hwDev, in->stream);
5163 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164
5165 return NO_ERROR;
5166}
5167
5168status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5169{
5170 Mutex::Autolock _l(mLock);
5171 MixerThread *dstThread = checkMixerThread_l(output);
5172 if (dstThread == NULL) {
5173 LOGW("setStreamOutput() bad output id %d", output);
5174 return BAD_VALUE;
5175 }
5176
5177 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5178 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5179
Eric Laurent9f6530f2011-08-30 10:18:54 -07005180 dstThread->setStreamValid(stream, true);
5181
Mathias Agopian65ab4712010-07-14 17:59:35 -07005182 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5183 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5184 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005185 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005186 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005187 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189 }
Eric Laurentde070132010-07-13 04:45:46 -07005190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005191
5192 return NO_ERROR;
5193}
5194
5195
5196int AudioFlinger::newAudioSessionId()
5197{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005198 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005199}
5200
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005201void AudioFlinger::acquireAudioSessionId(int audioSession)
5202{
5203 Mutex::Autolock _l(mLock);
5204 int caller = IPCThreadState::self()->getCallingPid();
5205 LOGV("acquiring %d from %d", audioSession, caller);
5206 int num = mAudioSessionRefs.size();
5207 for (int i = 0; i< num; i++) {
5208 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5209 if (ref->sessionid == audioSession && ref->pid == caller) {
5210 ref->cnt++;
5211 LOGV(" incremented refcount to %d", ref->cnt);
5212 return;
5213 }
5214 }
5215 AudioSessionRef *ref = new AudioSessionRef();
5216 ref->sessionid = audioSession;
5217 ref->pid = caller;
5218 ref->cnt = 1;
5219 mAudioSessionRefs.push(ref);
5220 LOGV(" added new entry for %d", ref->sessionid);
5221}
5222
5223void AudioFlinger::releaseAudioSessionId(int audioSession)
5224{
5225 Mutex::Autolock _l(mLock);
5226 int caller = IPCThreadState::self()->getCallingPid();
5227 LOGV("releasing %d from %d", audioSession, caller);
5228 int num = mAudioSessionRefs.size();
5229 for (int i = 0; i< num; i++) {
5230 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5231 if (ref->sessionid == audioSession && ref->pid == caller) {
5232 ref->cnt--;
5233 LOGV(" decremented refcount to %d", ref->cnt);
5234 if (ref->cnt == 0) {
5235 mAudioSessionRefs.removeAt(i);
5236 delete ref;
5237 purgeStaleEffects_l();
5238 }
5239 return;
5240 }
5241 }
5242 LOGW("session id %d not found for pid %d", audioSession, caller);
5243}
5244
5245void AudioFlinger::purgeStaleEffects_l() {
5246
5247 LOGV("purging stale effects");
5248
5249 Vector< sp<EffectChain> > chains;
5250
5251 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5252 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5253 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5254 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005255 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5256 chains.push(ec);
5257 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005258 }
5259 }
5260 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5261 sp<RecordThread> t = mRecordThreads.valueAt(i);
5262 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5263 sp<EffectChain> ec = t->mEffectChains[j];
5264 chains.push(ec);
5265 }
5266 }
5267
5268 for (size_t i = 0; i < chains.size(); i++) {
5269 sp<EffectChain> ec = chains[i];
5270 int sessionid = ec->sessionId();
5271 sp<ThreadBase> t = ec->mThread.promote();
5272 if (t == 0) {
5273 continue;
5274 }
5275 size_t numsessionrefs = mAudioSessionRefs.size();
5276 bool found = false;
5277 for (size_t k = 0; k < numsessionrefs; k++) {
5278 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5279 if (ref->sessionid == sessionid) {
5280 LOGV(" session %d still exists for %d with %d refs",
5281 sessionid, ref->pid, ref->cnt);
5282 found = true;
5283 break;
5284 }
5285 }
5286 if (!found) {
5287 // remove all effects from the chain
5288 while (ec->mEffects.size()) {
5289 sp<EffectModule> effect = ec->mEffects[0];
5290 effect->unPin();
5291 Mutex::Autolock _l (t->mLock);
5292 t->removeEffect_l(effect);
5293 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5294 sp<EffectHandle> handle = effect->mHandles[j].promote();
5295 if (handle != 0) {
5296 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005297 if (handle->mHasControl && handle->mEnabled) {
5298 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5299 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005300 }
5301 }
5302 AudioSystem::unregisterEffect(effect->id());
5303 }
5304 }
5305 }
5306 return;
5307}
5308
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5310AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5311{
5312 PlaybackThread *thread = NULL;
5313 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5314 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5315 }
5316 return thread;
5317}
5318
5319// checkMixerThread_l() must be called with AudioFlinger::mLock held
5320AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5321{
5322 PlaybackThread *thread = checkPlaybackThread_l(output);
5323 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005324 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325 thread = NULL;
5326 }
5327 }
5328 return (MixerThread *)thread;
5329}
5330
5331// checkRecordThread_l() must be called with AudioFlinger::mLock held
5332AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5333{
5334 RecordThread *thread = NULL;
5335 if (mRecordThreads.indexOfKey(input) >= 0) {
5336 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5337 }
5338 return thread;
5339}
5340
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005341uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005343 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344}
5345
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005346AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5347{
5348 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5349 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005350 AudioStreamOut *output = thread->getOutput();
5351 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005352 return thread;
5353 }
5354 }
5355 return NULL;
5356}
5357
5358uint32_t AudioFlinger::primaryOutputDevice_l()
5359{
5360 PlaybackThread *thread = primaryPlaybackThread_l();
5361
5362 if (thread == NULL) {
5363 return 0;
5364 }
5365
5366 return thread->device();
5367}
5368
5369
Mathias Agopian65ab4712010-07-14 17:59:35 -07005370// ----------------------------------------------------------------------------
5371// Effect management
5372// ----------------------------------------------------------------------------
5373
5374
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5376{
5377 Mutex::Autolock _l(mLock);
5378 return EffectQueryNumberEffects(numEffects);
5379}
5380
5381status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5382{
5383 Mutex::Autolock _l(mLock);
5384 return EffectQueryEffect(index, descriptor);
5385}
5386
5387status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5388{
5389 Mutex::Autolock _l(mLock);
5390 return EffectGetDescriptor(pUuid, descriptor);
5391}
5392
5393
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5395 effect_descriptor_t *pDesc,
5396 const sp<IEffectClient>& effectClient,
5397 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005398 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 int sessionId,
5400 status_t *status,
5401 int *id,
5402 int *enabled)
5403{
5404 status_t lStatus = NO_ERROR;
5405 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406 effect_descriptor_t desc;
5407 sp<Client> client;
5408 wp<Client> wclient;
5409
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005410 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5411 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005412
5413 if (pDesc == NULL) {
5414 lStatus = BAD_VALUE;
5415 goto Exit;
5416 }
5417
Eric Laurent84e9a102010-09-23 16:10:16 -07005418 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005419 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005420 lStatus = PERMISSION_DENIED;
5421 goto Exit;
5422 }
5423
Dima Zavinfce7a472011-04-19 22:30:36 -07005424 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005425 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005426 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005427 lStatus = PERMISSION_DENIED;
5428 goto Exit;
5429 }
5430
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005431 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005432 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005433 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005434 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005435 lStatus = BAD_VALUE;
5436 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005437 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005438 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005439 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005440 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005441 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005442 }
5443 }
5444
Mathias Agopian65ab4712010-07-14 17:59:35 -07005445 {
5446 Mutex::Autolock _l(mLock);
5447
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448
5449 if (!EffectIsNullUuid(&pDesc->uuid)) {
5450 // if uuid is specified, request effect descriptor
5451 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5452 if (lStatus < 0) {
5453 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5454 goto Exit;
5455 }
5456 } else {
5457 // if uuid is not specified, look for an available implementation
5458 // of the required type in effect factory
5459 if (EffectIsNullUuid(&pDesc->type)) {
5460 LOGW("createEffect() no effect type");
5461 lStatus = BAD_VALUE;
5462 goto Exit;
5463 }
5464 uint32_t numEffects = 0;
5465 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005466 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467 bool found = false;
5468
5469 lStatus = EffectQueryNumberEffects(&numEffects);
5470 if (lStatus < 0) {
5471 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5472 goto Exit;
5473 }
5474 for (uint32_t i = 0; i < numEffects; i++) {
5475 lStatus = EffectQueryEffect(i, &desc);
5476 if (lStatus < 0) {
5477 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5478 continue;
5479 }
5480 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5481 // If matching type found save effect descriptor. If the session is
5482 // 0 and the effect is not auxiliary, continue enumeration in case
5483 // an auxiliary version of this effect type is available
5484 found = true;
5485 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005486 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5488 break;
5489 }
5490 }
5491 }
5492 if (!found) {
5493 lStatus = BAD_VALUE;
5494 LOGW("createEffect() effect not found");
5495 goto Exit;
5496 }
5497 // For same effect type, chose auxiliary version over insert version if
5498 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005499 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5501 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5502 }
5503 }
5504
5505 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005506 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5508 lStatus = INVALID_OPERATION;
5509 goto Exit;
5510 }
5511
Eric Laurent59255e42011-07-27 19:49:51 -07005512 // check recording permission for visualizer
5513 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5514 !recordingAllowed()) {
5515 lStatus = PERMISSION_DENIED;
5516 goto Exit;
5517 }
5518
Mathias Agopian65ab4712010-07-14 17:59:35 -07005519 // return effect descriptor
5520 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5521
5522 // If output is not specified try to find a matching audio session ID in one of the
5523 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005524 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5525 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005526 // Note: io is never 0 when creating an effect on an input
5527 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005528 // look for the thread where the specified audio session is present
5529 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5530 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005531 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005532 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005533 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005535 if (io == 0) {
5536 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5537 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5538 io = mRecordThreads.keyAt(i);
5539 break;
5540 }
5541 }
5542 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005543 // If no output thread contains the requested session ID, default to
5544 // first output. The effect chain will be moved to the correct output
5545 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005546 if (io == 0 && mPlaybackThreads.size()) {
5547 io = mPlaybackThreads.keyAt(0);
5548 }
5549 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5550 }
5551 ThreadBase *thread = checkRecordThread_l(io);
5552 if (thread == NULL) {
5553 thread = checkPlaybackThread_l(io);
5554 if (thread == NULL) {
5555 LOGE("createEffect() unknown output thread");
5556 lStatus = BAD_VALUE;
5557 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005558 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005560
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 wclient = mClients.valueFor(pid);
5562
5563 if (wclient != NULL) {
5564 client = wclient.promote();
5565 } else {
5566 client = new Client(this, pid);
5567 mClients.add(pid, client);
5568 }
5569
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005570 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005571 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5572 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 if (handle != 0 && id != NULL) {
5574 *id = handle->id();
5575 }
5576 }
5577
5578Exit:
5579 if(status) {
5580 *status = lStatus;
5581 }
5582 return handle;
5583}
5584
Eric Laurent59255e42011-07-27 19:49:51 -07005585status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005586{
5587 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005588 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005589 Mutex::Autolock _l(mLock);
5590 if (srcOutput == dstOutput) {
5591 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5592 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 }
Eric Laurentde070132010-07-13 04:45:46 -07005594 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5595 if (srcThread == NULL) {
5596 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5597 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 }
Eric Laurentde070132010-07-13 04:45:46 -07005599 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5600 if (dstThread == NULL) {
5601 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5602 return BAD_VALUE;
5603 }
5604
5605 Mutex::Autolock _dl(dstThread->mLock);
5606 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005607 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005608
Mathias Agopian65ab4712010-07-14 17:59:35 -07005609 return NO_ERROR;
5610}
5611
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005612// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005613status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005614 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005615 AudioFlinger::PlaybackThread *dstThread,
5616 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005617{
5618 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005619 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005620
Eric Laurent59255e42011-07-27 19:49:51 -07005621 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005622 if (chain == 0) {
5623 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005624 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005625 return INVALID_OPERATION;
5626 }
5627
Eric Laurent39e94f82010-07-28 01:32:47 -07005628 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005629 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005630 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005631 // removed.
5632 srcThread->removeEffectChain_l(chain);
5633
5634 // transfer all effects one by one so that new effect chain is created on new thread with
5635 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005636 int dstOutput = dstThread->id();
5637 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005638 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005639 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5640 while (effect != 0) {
5641 srcThread->removeEffect_l(effect);
5642 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005643 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5644 if (effect->state() == EffectModule::ACTIVE ||
5645 effect->state() == EffectModule::STOPPING) {
5646 effect->start();
5647 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005648 // if the move request is not received from audio policy manager, the effect must be
5649 // re-registered with the new strategy and output
5650 if (dstChain == 0) {
5651 dstChain = effect->chain().promote();
5652 if (dstChain == 0) {
5653 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5654 srcThread->addEffect_l(effect);
5655 return NO_INIT;
5656 }
5657 strategy = dstChain->strategy();
5658 }
5659 if (reRegister) {
5660 AudioSystem::unregisterEffect(effect->id());
5661 AudioSystem::registerEffect(&effect->desc(),
5662 dstOutput,
5663 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005664 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005665 effect->id());
5666 }
Eric Laurentde070132010-07-13 04:45:46 -07005667 effect = chain->getEffectFromId_l(0);
5668 }
5669
5670 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671}
5672
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005673
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005675sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 const sp<AudioFlinger::Client>& client,
5677 const sp<IEffectClient>& effectClient,
5678 int32_t priority,
5679 int sessionId,
5680 effect_descriptor_t *desc,
5681 int *enabled,
5682 status_t *status
5683 )
5684{
5685 sp<EffectModule> effect;
5686 sp<EffectHandle> handle;
5687 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005689 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 bool effectCreated = false;
5691 bool effectRegistered = false;
5692
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005693 lStatus = initCheck();
5694 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005696 goto Exit;
5697 }
5698
5699 // Do not allow effects with session ID 0 on direct output or duplicating threads
5700 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005701 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005702 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5703 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005704 lStatus = BAD_VALUE;
5705 goto Exit;
5706 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005707 // Only Pre processor effects are allowed on input threads and only on input threads
5708 if ((mType == RECORD &&
5709 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5710 (mType != RECORD &&
5711 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5712 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5713 desc->name, desc->flags, mType);
5714 lStatus = BAD_VALUE;
5715 goto Exit;
5716 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717
5718 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5719
5720 { // scope for mLock
5721 Mutex::Autolock _l(mLock);
5722
5723 // check for existing effect chain with the requested audio session
5724 chain = getEffectChain_l(sessionId);
5725 if (chain == 0) {
5726 // create a new chain for this session
5727 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5728 chain = new EffectChain(this, sessionId);
5729 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005730 chain->setStrategy(getStrategyForSession_l(sessionId));
5731 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005733 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 }
5735
5736 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5737
5738 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005739 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005741 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005742 if (lStatus != NO_ERROR) {
5743 goto Exit;
5744 }
5745 effectRegistered = true;
5746 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005747 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748 lStatus = effect->status();
5749 if (lStatus != NO_ERROR) {
5750 goto Exit;
5751 }
Eric Laurentcab11242010-07-15 12:50:15 -07005752 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753 if (lStatus != NO_ERROR) {
5754 goto Exit;
5755 }
5756 effectCreated = true;
5757
5758 effect->setDevice(mDevice);
5759 effect->setMode(mAudioFlinger->getMode());
5760 }
5761 // create effect handle and connect it to effect module
5762 handle = new EffectHandle(effect, client, effectClient, priority);
5763 lStatus = effect->addHandle(handle);
5764 if (enabled) {
5765 *enabled = (int)effect->isEnabled();
5766 }
5767 }
5768
5769Exit:
5770 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005771 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005772 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005773 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774 }
5775 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005776 AudioSystem::unregisterEffect(effect->id());
5777 }
5778 if (chainCreated) {
5779 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005780 }
5781 handle.clear();
5782 }
5783
5784 if(status) {
5785 *status = lStatus;
5786 }
5787 return handle;
5788}
5789
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005790sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5791{
5792 sp<EffectModule> effect;
5793
5794 sp<EffectChain> chain = getEffectChain_l(sessionId);
5795 if (chain != 0) {
5796 effect = chain->getEffectFromId_l(effectId);
5797 }
5798 return effect;
5799}
5800
Eric Laurentde070132010-07-13 04:45:46 -07005801// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5802// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005803status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005804{
5805 // check for existing effect chain with the requested audio session
5806 int sessionId = effect->sessionId();
5807 sp<EffectChain> chain = getEffectChain_l(sessionId);
5808 bool chainCreated = false;
5809
5810 if (chain == 0) {
5811 // create a new chain for this session
5812 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5813 chain = new EffectChain(this, sessionId);
5814 addEffectChain_l(chain);
5815 chain->setStrategy(getStrategyForSession_l(sessionId));
5816 chainCreated = true;
5817 }
5818 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5819
5820 if (chain->getEffectFromId_l(effect->id()) != 0) {
5821 LOGW("addEffect_l() %p effect %s already present in chain %p",
5822 this, effect->desc().name, chain.get());
5823 return BAD_VALUE;
5824 }
5825
5826 status_t status = chain->addEffect_l(effect);
5827 if (status != NO_ERROR) {
5828 if (chainCreated) {
5829 removeEffectChain_l(chain);
5830 }
5831 return status;
5832 }
5833
5834 effect->setDevice(mDevice);
5835 effect->setMode(mAudioFlinger->getMode());
5836 return NO_ERROR;
5837}
5838
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005839void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005840
5841 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005842 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005843 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5844 detachAuxEffect_l(effect->id());
5845 }
5846
5847 sp<EffectChain> chain = effect->chain().promote();
5848 if (chain != 0) {
5849 // remove effect chain if removing last effect
5850 if (chain->removeEffect_l(effect) == 0) {
5851 removeEffectChain_l(chain);
5852 }
5853 } else {
5854 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5855 }
5856}
5857
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005858void AudioFlinger::ThreadBase::lockEffectChains_l(
5859 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5860{
5861 effectChains = mEffectChains;
5862 for (size_t i = 0; i < mEffectChains.size(); i++) {
5863 mEffectChains[i]->lock();
5864 }
5865}
5866
5867void AudioFlinger::ThreadBase::unlockEffectChains(
5868 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5869{
5870 for (size_t i = 0; i < effectChains.size(); i++) {
5871 effectChains[i]->unlock();
5872 }
5873}
5874
5875sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5876{
5877 Mutex::Autolock _l(mLock);
5878 return getEffectChain_l(sessionId);
5879}
5880
5881sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5882{
5883 sp<EffectChain> chain;
5884
5885 size_t size = mEffectChains.size();
5886 for (size_t i = 0; i < size; i++) {
5887 if (mEffectChains[i]->sessionId() == sessionId) {
5888 chain = mEffectChains[i];
5889 break;
5890 }
5891 }
5892 return chain;
5893}
5894
5895void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5896{
5897 Mutex::Autolock _l(mLock);
5898 size_t size = mEffectChains.size();
5899 for (size_t i = 0; i < size; i++) {
5900 mEffectChains[i]->setMode_l(mode);
5901 }
5902}
5903
5904void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005905 const wp<EffectHandle>& handle,
5906 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005907
Mathias Agopian65ab4712010-07-14 17:59:35 -07005908 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005909 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 // delete the effect module if removing last handle on it
5911 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005912 if (!effect->isPinned() || unpiniflast) {
5913 removeEffect_l(effect);
5914 AudioSystem::unregisterEffect(effect->id());
5915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005916 }
5917}
5918
5919status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5920{
5921 int session = chain->sessionId();
5922 int16_t *buffer = mMixBuffer;
5923 bool ownsBuffer = false;
5924
5925 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5926 if (session > 0) {
5927 // Only one effect chain can be present in direct output thread and it uses
5928 // the mix buffer as input
5929 if (mType != DIRECT) {
5930 size_t numSamples = mFrameCount * mChannelCount;
5931 buffer = new int16_t[numSamples];
5932 memset(buffer, 0, numSamples * sizeof(int16_t));
5933 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5934 ownsBuffer = true;
5935 }
5936
5937 // Attach all tracks with same session ID to this chain.
5938 for (size_t i = 0; i < mTracks.size(); ++i) {
5939 sp<Track> track = mTracks[i];
5940 if (session == track->sessionId()) {
5941 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5942 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005943 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944 }
5945 }
5946
5947 // indicate all active tracks in the chain
5948 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5949 sp<Track> track = mActiveTracks[i].promote();
5950 if (track == 0) continue;
5951 if (session == track->sessionId()) {
5952 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005953 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 }
5955 }
5956 }
5957
5958 chain->setInBuffer(buffer, ownsBuffer);
5959 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005960 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005961 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005962 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5963 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005964 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005965 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5966 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005967 // Effect chain for other sessions are inserted at beginning of effect
5968 // chains list to be processed before output mix effects. Relative order between other
5969 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970 size_t size = mEffectChains.size();
5971 size_t i = 0;
5972 for (i = 0; i < size; i++) {
5973 if (mEffectChains[i]->sessionId() < session) break;
5974 }
5975 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005976 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005977
5978 return NO_ERROR;
5979}
5980
5981size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5982{
5983 int session = chain->sessionId();
5984
5985 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5986
5987 for (size_t i = 0; i < mEffectChains.size(); i++) {
5988 if (chain == mEffectChains[i]) {
5989 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005990 // detach all active tracks from the chain
5991 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5992 sp<Track> track = mActiveTracks[i].promote();
5993 if (track == 0) continue;
5994 if (session == track->sessionId()) {
5995 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5996 chain.get(), session);
5997 chain->decActiveTrackCnt();
5998 }
5999 }
6000
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 // detach all tracks with same session ID from this chain
6002 for (size_t i = 0; i < mTracks.size(); ++i) {
6003 sp<Track> track = mTracks[i];
6004 if (session == track->sessionId()) {
6005 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006006 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006007 }
6008 }
Eric Laurentde070132010-07-13 04:45:46 -07006009 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 }
6011 }
6012 return mEffectChains.size();
6013}
6014
Eric Laurentde070132010-07-13 04:45:46 -07006015status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6016 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017{
6018 Mutex::Autolock _l(mLock);
6019 return attachAuxEffect_l(track, EffectId);
6020}
6021
Eric Laurentde070132010-07-13 04:45:46 -07006022status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6023 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024{
6025 status_t status = NO_ERROR;
6026
6027 if (EffectId == 0) {
6028 track->setAuxBuffer(0, NULL);
6029 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006030 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6031 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006032 if (effect != 0) {
6033 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6034 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6035 } else {
6036 status = INVALID_OPERATION;
6037 }
6038 } else {
6039 status = BAD_VALUE;
6040 }
6041 }
6042 return status;
6043}
6044
6045void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6046{
6047 for (size_t i = 0; i < mTracks.size(); ++i) {
6048 sp<Track> track = mTracks[i];
6049 if (track->auxEffectId() == effectId) {
6050 attachAuxEffect_l(track, 0);
6051 }
6052 }
6053}
6054
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006055status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6056{
6057 // only one chain per input thread
6058 if (mEffectChains.size() != 0) {
6059 return INVALID_OPERATION;
6060 }
6061 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6062
6063 chain->setInBuffer(NULL);
6064 chain->setOutBuffer(NULL);
6065
Eric Laurent59255e42011-07-27 19:49:51 -07006066 checkSuspendOnAddEffectChain_l(chain);
6067
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006068 mEffectChains.add(chain);
6069
6070 return NO_ERROR;
6071}
6072
6073size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6074{
6075 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6076 LOGW_IF(mEffectChains.size() != 1,
6077 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6078 chain.get(), mEffectChains.size(), this);
6079 if (mEffectChains.size() == 1) {
6080 mEffectChains.removeAt(0);
6081 }
6082 return 0;
6083}
6084
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085// ----------------------------------------------------------------------------
6086// EffectModule implementation
6087// ----------------------------------------------------------------------------
6088
6089#undef LOG_TAG
6090#define LOG_TAG "AudioFlinger::EffectModule"
6091
6092AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6093 const wp<AudioFlinger::EffectChain>& chain,
6094 effect_descriptor_t *desc,
6095 int id,
6096 int sessionId)
6097 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006098 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006099{
6100 LOGV("Constructor %p", this);
6101 int lStatus;
6102 sp<ThreadBase> thread = mThread.promote();
6103 if (thread == 0) {
6104 return;
6105 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106
6107 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6108
6109 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006110 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111
6112 if (mStatus != NO_ERROR) {
6113 return;
6114 }
6115 lStatus = init();
6116 if (lStatus < 0) {
6117 mStatus = lStatus;
6118 goto Error;
6119 }
6120
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006121 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6122 mPinned = true;
6123 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006124 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6125 return;
6126Error:
6127 EffectRelease(mEffectInterface);
6128 mEffectInterface = NULL;
6129 LOGV("Constructor Error %d", mStatus);
6130}
6131
6132AudioFlinger::EffectModule::~EffectModule()
6133{
6134 LOGV("Destructor %p", this);
6135 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006136 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6137 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6138 sp<ThreadBase> thread = mThread.promote();
6139 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006140 audio_stream_t *stream = thread->stream();
6141 if (stream != NULL) {
6142 stream->remove_audio_effect(stream, mEffectInterface);
6143 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006144 }
6145 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006146 // release effect engine
6147 EffectRelease(mEffectInterface);
6148 }
6149}
6150
6151status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6152{
6153 status_t status;
6154
6155 Mutex::Autolock _l(mLock);
6156 // First handle in mHandles has highest priority and controls the effect module
6157 int priority = handle->priority();
6158 size_t size = mHandles.size();
6159 sp<EffectHandle> h;
6160 size_t i;
6161 for (i = 0; i < size; i++) {
6162 h = mHandles[i].promote();
6163 if (h == 0) continue;
6164 if (h->priority() <= priority) break;
6165 }
6166 // if inserted in first place, move effect control from previous owner to this handle
6167 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006168 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006169 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006170 enabled = h->enabled();
6171 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 }
Eric Laurent59255e42011-07-27 19:49:51 -07006173 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174 status = NO_ERROR;
6175 } else {
6176 status = ALREADY_EXISTS;
6177 }
Eric Laurent59255e42011-07-27 19:49:51 -07006178 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006179 mHandles.insertAt(handle, i);
6180 return status;
6181}
6182
6183size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6184{
6185 Mutex::Autolock _l(mLock);
6186 size_t size = mHandles.size();
6187 size_t i;
6188 for (i = 0; i < size; i++) {
6189 if (mHandles[i] == handle) break;
6190 }
6191 if (i == size) {
6192 return size;
6193 }
Eric Laurent59255e42011-07-27 19:49:51 -07006194 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6195
6196 bool enabled = false;
6197 EffectHandle *hdl = handle.unsafe_get();
6198 if (hdl) {
6199 LOGV("removeHandle() unsafe_get OK");
6200 enabled = hdl->enabled();
6201 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202 mHandles.removeAt(i);
6203 size = mHandles.size();
6204 // if removed from first place, move effect control from this handle to next in line
6205 if (i == 0 && size != 0) {
6206 sp<EffectHandle> h = mHandles[0].promote();
6207 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006208 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006209 }
6210 }
6211
Eric Laurentec437d82011-07-26 20:54:46 -07006212 // Prevent calls to process() and other functions on effect interface from now on.
6213 // The effect engine will be released by the destructor when the last strong reference on
6214 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006215 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006216 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006217 }
6218
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 return size;
6220}
6221
Eric Laurent59255e42011-07-27 19:49:51 -07006222sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6223{
6224 Mutex::Autolock _l(mLock);
6225 sp<EffectHandle> handle;
6226 if (mHandles.size() != 0) {
6227 handle = mHandles[0].promote();
6228 }
6229 return handle;
6230}
6231
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006232void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233{
Eric Laurent59255e42011-07-27 19:49:51 -07006234 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 // keep a strong reference on this EffectModule to avoid calling the
6236 // destructor before we exit
6237 sp<EffectModule> keep(this);
6238 {
6239 sp<ThreadBase> thread = mThread.promote();
6240 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006241 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006242 }
6243 }
6244}
6245
6246void AudioFlinger::EffectModule::updateState() {
6247 Mutex::Autolock _l(mLock);
6248
6249 switch (mState) {
6250 case RESTART:
6251 reset_l();
6252 // FALL THROUGH
6253
6254 case STARTING:
6255 // clear auxiliary effect input buffer for next accumulation
6256 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6257 memset(mConfig.inputCfg.buffer.raw,
6258 0,
6259 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6260 }
6261 start_l();
6262 mState = ACTIVE;
6263 break;
6264 case STOPPING:
6265 stop_l();
6266 mDisableWaitCnt = mMaxDisableWaitCnt;
6267 mState = STOPPED;
6268 break;
6269 case STOPPED:
6270 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6271 // turn off sequence.
6272 if (--mDisableWaitCnt == 0) {
6273 reset_l();
6274 mState = IDLE;
6275 }
6276 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006277 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 break;
6279 }
6280}
6281
6282void AudioFlinger::EffectModule::process()
6283{
6284 Mutex::Autolock _l(mLock);
6285
Eric Laurentec437d82011-07-26 20:54:46 -07006286 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006287 mConfig.inputCfg.buffer.raw == NULL ||
6288 mConfig.outputCfg.buffer.raw == NULL) {
6289 return;
6290 }
6291
Eric Laurent8f45bd72010-08-31 13:50:07 -07006292 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006293 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6294 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6295 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6296 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006297 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298 }
6299
6300 // do the actual processing in the effect engine
6301 int ret = (*mEffectInterface)->process(mEffectInterface,
6302 &mConfig.inputCfg.buffer,
6303 &mConfig.outputCfg.buffer);
6304
6305 // force transition to IDLE state when engine is ready
6306 if (mState == STOPPED && ret == -ENODATA) {
6307 mDisableWaitCnt = 1;
6308 }
6309
6310 // clear auxiliary effect input buffer for next accumulation
6311 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006312 memset(mConfig.inputCfg.buffer.raw, 0,
6313 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006314 }
6315 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006316 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6317 // If an insert effect is idle and input buffer is different from output buffer,
6318 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006319 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006320 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006321 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6322 int16_t *in = mConfig.inputCfg.buffer.s16;
6323 int16_t *out = mConfig.outputCfg.buffer.s16;
6324 for (size_t i = 0; i < frameCnt; i++) {
6325 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006327 }
6328 }
6329}
6330
6331void AudioFlinger::EffectModule::reset_l()
6332{
6333 if (mEffectInterface == NULL) {
6334 return;
6335 }
6336 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6337}
6338
6339status_t AudioFlinger::EffectModule::configure()
6340{
6341 uint32_t channels;
6342 if (mEffectInterface == NULL) {
6343 return NO_INIT;
6344 }
6345
6346 sp<ThreadBase> thread = mThread.promote();
6347 if (thread == 0) {
6348 return DEAD_OBJECT;
6349 }
6350
6351 // TODO: handle configuration of effects replacing track process
6352 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006353 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006354 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006355 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006356 }
6357
6358 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006359 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 } else {
6361 mConfig.inputCfg.channels = channels;
6362 }
6363 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006364 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6365 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006366 mConfig.inputCfg.samplingRate = thread->sampleRate();
6367 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6368 mConfig.inputCfg.bufferProvider.cookie = NULL;
6369 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6370 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6371 mConfig.outputCfg.bufferProvider.cookie = NULL;
6372 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6373 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6374 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6375 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006376 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006377 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 // - in other sessions:
6379 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6380 // other effect: overwrites output buffer: input buffer == output buffer
6381 // Auxiliary effect:
6382 // accumulates in output buffer: input buffer != output buffer
6383 // Therefore: accumulate <=> input buffer != output buffer
6384 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6385 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6386 } else {
6387 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6388 }
6389 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6390 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6391 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6392 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6393
Eric Laurentde070132010-07-13 04:45:46 -07006394 LOGV("configure() %p thread %p buffer %p framecount %d",
6395 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6396
Mathias Agopian65ab4712010-07-14 17:59:35 -07006397 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006398 uint32_t size = sizeof(int);
6399 status_t status = (*mEffectInterface)->command(mEffectInterface,
6400 EFFECT_CMD_CONFIGURE,
6401 sizeof(effect_config_t),
6402 &mConfig,
6403 &size,
6404 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006405 if (status == 0) {
6406 status = cmdStatus;
6407 }
6408
6409 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6410 (1000 * mConfig.outputCfg.buffer.frameCount);
6411
6412 return status;
6413}
6414
6415status_t AudioFlinger::EffectModule::init()
6416{
6417 Mutex::Autolock _l(mLock);
6418 if (mEffectInterface == NULL) {
6419 return NO_INIT;
6420 }
6421 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006422 uint32_t size = sizeof(status_t);
6423 status_t status = (*mEffectInterface)->command(mEffectInterface,
6424 EFFECT_CMD_INIT,
6425 0,
6426 NULL,
6427 &size,
6428 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006429 if (status == 0) {
6430 status = cmdStatus;
6431 }
6432 return status;
6433}
6434
Eric Laurentec35a142011-10-05 17:42:25 -07006435status_t AudioFlinger::EffectModule::start()
6436{
6437 Mutex::Autolock _l(mLock);
6438 return start_l();
6439}
6440
Mathias Agopian65ab4712010-07-14 17:59:35 -07006441status_t AudioFlinger::EffectModule::start_l()
6442{
6443 if (mEffectInterface == NULL) {
6444 return NO_INIT;
6445 }
6446 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006447 uint32_t size = sizeof(status_t);
6448 status_t status = (*mEffectInterface)->command(mEffectInterface,
6449 EFFECT_CMD_ENABLE,
6450 0,
6451 NULL,
6452 &size,
6453 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 if (status == 0) {
6455 status = cmdStatus;
6456 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006457 if (status == 0 &&
6458 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6459 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6460 sp<ThreadBase> thread = mThread.promote();
6461 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006462 audio_stream_t *stream = thread->stream();
6463 if (stream != NULL) {
6464 stream->add_audio_effect(stream, mEffectInterface);
6465 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006466 }
6467 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 return status;
6469}
6470
Eric Laurentec437d82011-07-26 20:54:46 -07006471status_t AudioFlinger::EffectModule::stop()
6472{
6473 Mutex::Autolock _l(mLock);
6474 return stop_l();
6475}
6476
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477status_t AudioFlinger::EffectModule::stop_l()
6478{
6479 if (mEffectInterface == NULL) {
6480 return NO_INIT;
6481 }
6482 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006483 uint32_t size = sizeof(status_t);
6484 status_t status = (*mEffectInterface)->command(mEffectInterface,
6485 EFFECT_CMD_DISABLE,
6486 0,
6487 NULL,
6488 &size,
6489 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 if (status == 0) {
6491 status = cmdStatus;
6492 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006493 if (status == 0 &&
6494 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6495 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6496 sp<ThreadBase> thread = mThread.promote();
6497 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006498 audio_stream_t *stream = thread->stream();
6499 if (stream != NULL) {
6500 stream->remove_audio_effect(stream, mEffectInterface);
6501 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006502 }
6503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504 return status;
6505}
6506
Eric Laurent25f43952010-07-28 05:40:18 -07006507status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6508 uint32_t cmdSize,
6509 void *pCmdData,
6510 uint32_t *replySize,
6511 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512{
6513 Mutex::Autolock _l(mLock);
6514// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6515
Eric Laurentec437d82011-07-26 20:54:46 -07006516 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517 return NO_INIT;
6518 }
Eric Laurent25f43952010-07-28 05:40:18 -07006519 status_t status = (*mEffectInterface)->command(mEffectInterface,
6520 cmdCode,
6521 cmdSize,
6522 pCmdData,
6523 replySize,
6524 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006525 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006526 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006527 for (size_t i = 1; i < mHandles.size(); i++) {
6528 sp<EffectHandle> h = mHandles[i].promote();
6529 if (h != 0) {
6530 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6531 }
6532 }
6533 }
6534 return status;
6535}
6536
6537status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6538{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006539
Mathias Agopian65ab4712010-07-14 17:59:35 -07006540 Mutex::Autolock _l(mLock);
6541 LOGV("setEnabled %p enabled %d", this, enabled);
6542
6543 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006544 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6545 if (enabled && status != NO_ERROR) {
6546 return status;
6547 }
6548
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 switch (mState) {
6550 // going from disabled to enabled
6551 case IDLE:
6552 mState = STARTING;
6553 break;
6554 case STOPPED:
6555 mState = RESTART;
6556 break;
6557 case STOPPING:
6558 mState = ACTIVE;
6559 break;
6560
6561 // going from enabled to disabled
6562 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006563 mState = STOPPED;
6564 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006565 case STARTING:
6566 mState = IDLE;
6567 break;
6568 case ACTIVE:
6569 mState = STOPPING;
6570 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006571 case DESTROYED:
6572 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 }
6574 for (size_t i = 1; i < mHandles.size(); i++) {
6575 sp<EffectHandle> h = mHandles[i].promote();
6576 if (h != 0) {
6577 h->setEnabled(enabled);
6578 }
6579 }
6580 }
6581 return NO_ERROR;
6582}
6583
6584bool AudioFlinger::EffectModule::isEnabled()
6585{
6586 switch (mState) {
6587 case RESTART:
6588 case STARTING:
6589 case ACTIVE:
6590 return true;
6591 case IDLE:
6592 case STOPPING:
6593 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006594 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006595 default:
6596 return false;
6597 }
6598}
6599
Eric Laurent8f45bd72010-08-31 13:50:07 -07006600bool AudioFlinger::EffectModule::isProcessEnabled()
6601{
6602 switch (mState) {
6603 case RESTART:
6604 case ACTIVE:
6605 case STOPPING:
6606 case STOPPED:
6607 return true;
6608 case IDLE:
6609 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006610 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006611 default:
6612 return false;
6613 }
6614}
6615
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6617{
6618 Mutex::Autolock _l(mLock);
6619 status_t status = NO_ERROR;
6620
6621 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6622 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006623 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006624 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6625 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006626 status_t cmdStatus;
6627 uint32_t volume[2];
6628 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006629 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006630 volume[0] = *left;
6631 volume[1] = *right;
6632 if (controller) {
6633 pVolume = volume;
6634 }
Eric Laurent25f43952010-07-28 05:40:18 -07006635 status = (*mEffectInterface)->command(mEffectInterface,
6636 EFFECT_CMD_SET_VOLUME,
6637 size,
6638 volume,
6639 &size,
6640 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6642 *left = volume[0];
6643 *right = volume[1];
6644 }
6645 }
6646 return status;
6647}
6648
6649status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6650{
6651 Mutex::Autolock _l(mLock);
6652 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006653 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6654 // audio pre processing modules on RecordThread can receive both output and
6655 // input device indication in the same call
6656 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6657 if (dev) {
6658 status_t cmdStatus;
6659 uint32_t size = sizeof(status_t);
6660
6661 status = (*mEffectInterface)->command(mEffectInterface,
6662 EFFECT_CMD_SET_DEVICE,
6663 sizeof(uint32_t),
6664 &dev,
6665 &size,
6666 &cmdStatus);
6667 if (status == NO_ERROR) {
6668 status = cmdStatus;
6669 }
6670 }
6671 dev = device & AUDIO_DEVICE_IN_ALL;
6672 if (dev) {
6673 status_t cmdStatus;
6674 uint32_t size = sizeof(status_t);
6675
6676 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6677 EFFECT_CMD_SET_INPUT_DEVICE,
6678 sizeof(uint32_t),
6679 &dev,
6680 &size,
6681 &cmdStatus);
6682 if (status2 == NO_ERROR) {
6683 status2 = cmdStatus;
6684 }
6685 if (status == NO_ERROR) {
6686 status = status2;
6687 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006688 }
6689 }
6690 return status;
6691}
6692
6693status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6694{
6695 Mutex::Autolock _l(mLock);
6696 status_t status = NO_ERROR;
6697 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006698 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006699 uint32_t size = sizeof(status_t);
6700 status = (*mEffectInterface)->command(mEffectInterface,
6701 EFFECT_CMD_SET_AUDIO_MODE,
6702 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006703 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006704 &size,
6705 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 if (status == NO_ERROR) {
6707 status = cmdStatus;
6708 }
6709 }
6710 return status;
6711}
6712
Eric Laurent59255e42011-07-27 19:49:51 -07006713void AudioFlinger::EffectModule::setSuspended(bool suspended)
6714{
6715 Mutex::Autolock _l(mLock);
6716 mSuspended = suspended;
6717}
6718bool AudioFlinger::EffectModule::suspended()
6719{
6720 Mutex::Autolock _l(mLock);
6721 return mSuspended;
6722}
6723
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6725{
6726 const size_t SIZE = 256;
6727 char buffer[SIZE];
6728 String8 result;
6729
6730 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6731 result.append(buffer);
6732
6733 bool locked = tryLock(mLock);
6734 // failed to lock - AudioFlinger is probably deadlocked
6735 if (!locked) {
6736 result.append("\t\tCould not lock Fx mutex:\n");
6737 }
6738
6739 result.append("\t\tSession Status State Engine:\n");
6740 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6741 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6742 result.append(buffer);
6743
6744 result.append("\t\tDescriptor:\n");
6745 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6746 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6747 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6748 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6749 result.append(buffer);
6750 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6751 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6752 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6753 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6754 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006755 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006756 mDescriptor.apiVersion,
6757 mDescriptor.flags);
6758 result.append(buffer);
6759 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6760 mDescriptor.name);
6761 result.append(buffer);
6762 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6763 mDescriptor.implementor);
6764 result.append(buffer);
6765
6766 result.append("\t\t- Input configuration:\n");
6767 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6768 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6769 (uint32_t)mConfig.inputCfg.buffer.raw,
6770 mConfig.inputCfg.buffer.frameCount,
6771 mConfig.inputCfg.samplingRate,
6772 mConfig.inputCfg.channels,
6773 mConfig.inputCfg.format);
6774 result.append(buffer);
6775
6776 result.append("\t\t- Output configuration:\n");
6777 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6778 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6779 (uint32_t)mConfig.outputCfg.buffer.raw,
6780 mConfig.outputCfg.buffer.frameCount,
6781 mConfig.outputCfg.samplingRate,
6782 mConfig.outputCfg.channels,
6783 mConfig.outputCfg.format);
6784 result.append(buffer);
6785
6786 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6787 result.append(buffer);
6788 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6789 for (size_t i = 0; i < mHandles.size(); ++i) {
6790 sp<EffectHandle> handle = mHandles[i].promote();
6791 if (handle != 0) {
6792 handle->dump(buffer, SIZE);
6793 result.append(buffer);
6794 }
6795 }
6796
6797 result.append("\n");
6798
6799 write(fd, result.string(), result.length());
6800
6801 if (locked) {
6802 mLock.unlock();
6803 }
6804
6805 return NO_ERROR;
6806}
6807
6808// ----------------------------------------------------------------------------
6809// EffectHandle implementation
6810// ----------------------------------------------------------------------------
6811
6812#undef LOG_TAG
6813#define LOG_TAG "AudioFlinger::EffectHandle"
6814
6815AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6816 const sp<AudioFlinger::Client>& client,
6817 const sp<IEffectClient>& effectClient,
6818 int32_t priority)
6819 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006820 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006821 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006822{
6823 LOGV("constructor %p", this);
6824
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006825 if (client == 0) {
6826 return;
6827 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006828 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6829 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6830 if (mCblkMemory != 0) {
6831 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6832
6833 if (mCblk) {
6834 new(mCblk) effect_param_cblk_t();
6835 mBuffer = (uint8_t *)mCblk + bufOffset;
6836 }
6837 } else {
6838 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6839 return;
6840 }
6841}
6842
6843AudioFlinger::EffectHandle::~EffectHandle()
6844{
6845 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006846 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07006847 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848}
6849
6850status_t AudioFlinger::EffectHandle::enable()
6851{
Eric Laurent59255e42011-07-27 19:49:51 -07006852 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006853 if (!mHasControl) return INVALID_OPERATION;
6854 if (mEffect == 0) return DEAD_OBJECT;
6855
Eric Laurentdb7c0792011-08-10 10:37:50 -07006856 if (mEnabled) {
6857 return NO_ERROR;
6858 }
6859
Eric Laurent59255e42011-07-27 19:49:51 -07006860 mEnabled = true;
6861
6862 sp<ThreadBase> thread = mEffect->thread().promote();
6863 if (thread != 0) {
6864 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6865 }
6866
6867 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6868 if (mEffect->suspended()) {
6869 return NO_ERROR;
6870 }
6871
Eric Laurentdb7c0792011-08-10 10:37:50 -07006872 status_t status = mEffect->setEnabled(true);
6873 if (status != NO_ERROR) {
6874 if (thread != 0) {
6875 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6876 }
6877 mEnabled = false;
6878 }
6879 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880}
6881
6882status_t AudioFlinger::EffectHandle::disable()
6883{
Eric Laurent59255e42011-07-27 19:49:51 -07006884 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006885 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006886 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887
Eric Laurentdb7c0792011-08-10 10:37:50 -07006888 if (!mEnabled) {
6889 return NO_ERROR;
6890 }
Eric Laurent59255e42011-07-27 19:49:51 -07006891 mEnabled = false;
6892
6893 if (mEffect->suspended()) {
6894 return NO_ERROR;
6895 }
6896
6897 status_t status = mEffect->setEnabled(false);
6898
6899 sp<ThreadBase> thread = mEffect->thread().promote();
6900 if (thread != 0) {
6901 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6902 }
6903
6904 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006905}
6906
6907void AudioFlinger::EffectHandle::disconnect()
6908{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006909 disconnect(true);
6910}
6911
6912void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6913{
6914 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 if (mEffect == 0) {
6916 return;
6917 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006918 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006919
Eric Laurenta85a74a2011-10-19 11:44:54 -07006920 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006921 sp<ThreadBase> thread = mEffect->thread().promote();
6922 if (thread != 0) {
6923 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6924 }
Eric Laurent59255e42011-07-27 19:49:51 -07006925 }
6926
Mathias Agopian65ab4712010-07-14 17:59:35 -07006927 // release sp on module => module destructor can be called now
6928 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006929 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006930 if (mCblk) {
6931 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6932 }
6933 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006934 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6935 mClient.clear();
6936 }
6937}
6938
Eric Laurent25f43952010-07-28 05:40:18 -07006939status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6940 uint32_t cmdSize,
6941 void *pCmdData,
6942 uint32_t *replySize,
6943 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944{
Eric Laurent25f43952010-07-28 05:40:18 -07006945// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6946// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006947
6948 // only get parameter command is permitted for applications not controlling the effect
6949 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6950 return INVALID_OPERATION;
6951 }
6952 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006953 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954
6955 // handle commands that are not forwarded transparently to effect engine
6956 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6957 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6958 // no risk to block the whole media server process or mixer threads is we are stuck here
6959 Mutex::Autolock _l(mCblk->lock);
6960 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6961 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6962 mCblk->serverIndex = 0;
6963 mCblk->clientIndex = 0;
6964 return BAD_VALUE;
6965 }
6966 status_t status = NO_ERROR;
6967 while (mCblk->serverIndex < mCblk->clientIndex) {
6968 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006969 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006970 int *p = (int *)(mBuffer + mCblk->serverIndex);
6971 int size = *p++;
6972 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6973 LOGW("command(): invalid parameter block size");
6974 break;
6975 }
6976 effect_param_t *param = (effect_param_t *)p;
6977 if (param->psize == 0 || param->vsize == 0) {
6978 LOGW("command(): null parameter or value size");
6979 mCblk->serverIndex += size;
6980 continue;
6981 }
Eric Laurent25f43952010-07-28 05:40:18 -07006982 uint32_t psize = sizeof(effect_param_t) +
6983 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6984 param->vsize;
6985 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6986 psize,
6987 p,
6988 &rsize,
6989 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006990 // stop at first error encountered
6991 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006993 *(int *)pReplyData = reply;
6994 break;
6995 } else if (reply != NO_ERROR) {
6996 *(int *)pReplyData = reply;
6997 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006998 }
6999 mCblk->serverIndex += size;
7000 }
7001 mCblk->serverIndex = 0;
7002 mCblk->clientIndex = 0;
7003 return status;
7004 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007005 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006 return enable();
7007 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007008 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 return disable();
7010 }
7011
7012 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7013}
7014
7015sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7016 return mCblkMemory;
7017}
7018
Eric Laurent59255e42011-07-27 19:49:51 -07007019void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020{
7021 LOGV("setControl %p control %d", this, hasControl);
7022
7023 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007024 mEnabled = enabled;
7025
Mathias Agopian65ab4712010-07-14 17:59:35 -07007026 if (signal && mEffectClient != 0) {
7027 mEffectClient->controlStatusChanged(hasControl);
7028 }
7029}
7030
Eric Laurent25f43952010-07-28 05:40:18 -07007031void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7032 uint32_t cmdSize,
7033 void *pCmdData,
7034 uint32_t replySize,
7035 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007036{
7037 if (mEffectClient != 0) {
7038 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7039 }
7040}
7041
7042
7043
7044void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7045{
7046 if (mEffectClient != 0) {
7047 mEffectClient->enableStatusChanged(enabled);
7048 }
7049}
7050
7051status_t AudioFlinger::EffectHandle::onTransact(
7052 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7053{
7054 return BnEffect::onTransact(code, data, reply, flags);
7055}
7056
7057
7058void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7059{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007060 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007061
7062 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7063 (mClient == NULL) ? getpid() : mClient->pid(),
7064 mPriority,
7065 mHasControl,
7066 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007067 mCblk ? mCblk->clientIndex : 0,
7068 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007069 );
7070
7071 if (locked) {
7072 mCblk->lock.unlock();
7073 }
7074}
7075
7076#undef LOG_TAG
7077#define LOG_TAG "AudioFlinger::EffectChain"
7078
7079AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7080 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007081 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007082 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7083 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084{
Dima Zavinfce7a472011-04-19 22:30:36 -07007085 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007086 sp<ThreadBase> thread = mThread.promote();
7087 if (thread == 0) {
7088 return;
7089 }
7090 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7091 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007092}
7093
7094AudioFlinger::EffectChain::~EffectChain()
7095{
7096 if (mOwnInBuffer) {
7097 delete mInBuffer;
7098 }
7099
7100}
7101
Eric Laurent59255e42011-07-27 19:49:51 -07007102// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007103sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007104{
7105 sp<EffectModule> effect;
7106 size_t size = mEffects.size();
7107
7108 for (size_t i = 0; i < size; i++) {
7109 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7110 effect = mEffects[i];
7111 break;
7112 }
7113 }
7114 return effect;
7115}
7116
Eric Laurent59255e42011-07-27 19:49:51 -07007117// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007118sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007119{
7120 sp<EffectModule> effect;
7121 size_t size = mEffects.size();
7122
7123 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007124 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7125 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007126 effect = mEffects[i];
7127 break;
7128 }
7129 }
7130 return effect;
7131}
7132
Eric Laurent59255e42011-07-27 19:49:51 -07007133// getEffectFromType_l() must be called with ThreadBase::mLock held
7134sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7135 const effect_uuid_t *type)
7136{
7137 sp<EffectModule> effect;
7138 size_t size = mEffects.size();
7139
7140 for (size_t i = 0; i < size; i++) {
7141 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7142 effect = mEffects[i];
7143 break;
7144 }
7145 }
7146 return effect;
7147}
7148
Mathias Agopian65ab4712010-07-14 17:59:35 -07007149// Must be called with EffectChain::mLock locked
7150void AudioFlinger::EffectChain::process_l()
7151{
Eric Laurentdac69112010-09-28 14:09:57 -07007152 sp<ThreadBase> thread = mThread.promote();
7153 if (thread == 0) {
7154 LOGW("process_l(): cannot promote mixer thread");
7155 return;
7156 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007157 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7158 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007159 // always process effects unless no more tracks are on the session and the effect tail
7160 // has been rendered
7161 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007162 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007163 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007164
Eric Laurent544fe9b2011-11-11 15:42:52 -08007165 if (!tracksOnSession && mTailBufferCount == 0) {
7166 doProcess = false;
7167 }
7168
7169 if (activeTrackCnt() == 0) {
7170 // if no track is active and the effect tail has not been rendered,
7171 // the input buffer must be cleared here as the mixer process will not do it
7172 if (tracksOnSession || mTailBufferCount > 0) {
7173 size_t numSamples = thread->frameCount() * thread->channelCount();
7174 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7175 if (mTailBufferCount > 0) {
7176 mTailBufferCount--;
7177 }
7178 }
7179 }
Eric Laurentdac69112010-09-28 14:09:57 -07007180 }
7181
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007183 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007184 for (size_t i = 0; i < size; i++) {
7185 mEffects[i]->process();
7186 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187 }
7188 for (size_t i = 0; i < size; i++) {
7189 mEffects[i]->updateState();
7190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007191}
7192
Eric Laurentcab11242010-07-15 12:50:15 -07007193// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007194status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007195{
7196 effect_descriptor_t desc = effect->desc();
7197 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7198
7199 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007200 effect->setChain(this);
7201 sp<ThreadBase> thread = mThread.promote();
7202 if (thread == 0) {
7203 return NO_INIT;
7204 }
7205 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206
7207 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7208 // Auxiliary effects are inserted at the beginning of mEffects vector as
7209 // they are processed first and accumulated in chain input buffer
7210 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007211
Mathias Agopian65ab4712010-07-14 17:59:35 -07007212 // the input buffer for auxiliary effect contains mono samples in
7213 // 32 bit format. This is to avoid saturation in AudoMixer
7214 // accumulation stage. Saturation is done in EffectModule::process() before
7215 // calling the process in effect engine
7216 size_t numSamples = thread->frameCount();
7217 int32_t *buffer = new int32_t[numSamples];
7218 memset(buffer, 0, numSamples * sizeof(int32_t));
7219 effect->setInBuffer((int16_t *)buffer);
7220 // auxiliary effects output samples to chain input buffer for further processing
7221 // by insert effects
7222 effect->setOutBuffer(mInBuffer);
7223 } else {
7224 // Insert effects are inserted at the end of mEffects vector as they are processed
7225 // after track and auxiliary effects.
7226 // Insert effect order as a function of indicated preference:
7227 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7228 // another effect is present
7229 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7230 // last effect claiming first position
7231 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7232 // first effect claiming last position
7233 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7234 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7235 // already present
7236
7237 int size = (int)mEffects.size();
7238 int idx_insert = size;
7239 int idx_insert_first = -1;
7240 int idx_insert_last = -1;
7241
7242 for (int i = 0; i < size; i++) {
7243 effect_descriptor_t d = mEffects[i]->desc();
7244 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7245 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7246 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7247 // check invalid effect chaining combinations
7248 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7249 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007250 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007251 return INVALID_OPERATION;
7252 }
7253 // remember position of first insert effect and by default
7254 // select this as insert position for new effect
7255 if (idx_insert == size) {
7256 idx_insert = i;
7257 }
7258 // remember position of last insert effect claiming
7259 // first position
7260 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7261 idx_insert_first = i;
7262 }
7263 // remember position of first insert effect claiming
7264 // last position
7265 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7266 idx_insert_last == -1) {
7267 idx_insert_last = i;
7268 }
7269 }
7270 }
7271
7272 // modify idx_insert from first position if needed
7273 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7274 if (idx_insert_last != -1) {
7275 idx_insert = idx_insert_last;
7276 } else {
7277 idx_insert = size;
7278 }
7279 } else {
7280 if (idx_insert_first != -1) {
7281 idx_insert = idx_insert_first + 1;
7282 }
7283 }
7284
7285 // always read samples from chain input buffer
7286 effect->setInBuffer(mInBuffer);
7287
7288 // if last effect in the chain, output samples to chain
7289 // output buffer, otherwise to chain input buffer
7290 if (idx_insert == size) {
7291 if (idx_insert != 0) {
7292 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7293 mEffects[idx_insert-1]->configure();
7294 }
7295 effect->setOutBuffer(mOutBuffer);
7296 } else {
7297 effect->setOutBuffer(mInBuffer);
7298 }
7299 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007300
Eric Laurentcab11242010-07-15 12:50:15 -07007301 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302 }
7303 effect->configure();
7304 return NO_ERROR;
7305}
7306
Eric Laurentcab11242010-07-15 12:50:15 -07007307// removeEffect_l() must be called with PlaybackThread::mLock held
7308size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007309{
7310 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311 int size = (int)mEffects.size();
7312 int i;
7313 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7314
7315 for (i = 0; i < size; i++) {
7316 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007317 // calling stop here will remove pre-processing effect from the audio HAL.
7318 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7319 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007320 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7321 mEffects[i]->state() == EffectModule::STOPPING) {
7322 mEffects[i]->stop();
7323 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7325 delete[] effect->inBuffer();
7326 } else {
7327 if (i == size - 1 && i != 0) {
7328 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7329 mEffects[i - 1]->configure();
7330 }
7331 }
7332 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007333 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334 break;
7335 }
7336 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007337
7338 return mEffects.size();
7339}
7340
Eric Laurentcab11242010-07-15 12:50:15 -07007341// setDevice_l() must be called with PlaybackThread::mLock held
7342void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007343{
7344 size_t size = mEffects.size();
7345 for (size_t i = 0; i < size; i++) {
7346 mEffects[i]->setDevice(device);
7347 }
7348}
7349
Eric Laurentcab11242010-07-15 12:50:15 -07007350// setMode_l() must be called with PlaybackThread::mLock held
7351void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007352{
7353 size_t size = mEffects.size();
7354 for (size_t i = 0; i < size; i++) {
7355 mEffects[i]->setMode(mode);
7356 }
7357}
7358
Eric Laurentcab11242010-07-15 12:50:15 -07007359// setVolume_l() must be called with PlaybackThread::mLock held
7360bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007361{
7362 uint32_t newLeft = *left;
7363 uint32_t newRight = *right;
7364 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007365 int ctrlIdx = -1;
7366 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367
Eric Laurentcab11242010-07-15 12:50:15 -07007368 // first update volume controller
7369 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007370 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007371 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7372 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007373 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007374 break;
7375 }
7376 }
7377
7378 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007379 if (hasControl) {
7380 *left = mNewLeftVolume;
7381 *right = mNewRightVolume;
7382 }
7383 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007384 }
7385
7386 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007387 mLeftVolume = newLeft;
7388 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007389
7390 // second get volume update from volume controller
7391 if (ctrlIdx >= 0) {
7392 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007393 mNewLeftVolume = newLeft;
7394 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007395 }
7396 // then indicate volume to all other effects in chain.
7397 // Pass altered volume to effects before volume controller
7398 // and requested volume to effects after controller
7399 uint32_t lVol = newLeft;
7400 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007401
Mathias Agopian65ab4712010-07-14 17:59:35 -07007402 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007403 if ((int)i == ctrlIdx) continue;
7404 // this also works for ctrlIdx == -1 when there is no volume controller
7405 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007406 lVol = *left;
7407 rVol = *right;
7408 }
7409 mEffects[i]->setVolume(&lVol, &rVol, false);
7410 }
7411 *left = newLeft;
7412 *right = newRight;
7413
7414 return hasControl;
7415}
7416
Mathias Agopian65ab4712010-07-14 17:59:35 -07007417status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7418{
7419 const size_t SIZE = 256;
7420 char buffer[SIZE];
7421 String8 result;
7422
7423 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7424 result.append(buffer);
7425
7426 bool locked = tryLock(mLock);
7427 // failed to lock - AudioFlinger is probably deadlocked
7428 if (!locked) {
7429 result.append("\tCould not lock mutex:\n");
7430 }
7431
Eric Laurentcab11242010-07-15 12:50:15 -07007432 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7433 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007434 mEffects.size(),
7435 (uint32_t)mInBuffer,
7436 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007437 mActiveTrackCnt);
7438 result.append(buffer);
7439 write(fd, result.string(), result.size());
7440
7441 for (size_t i = 0; i < mEffects.size(); ++i) {
7442 sp<EffectModule> effect = mEffects[i];
7443 if (effect != 0) {
7444 effect->dump(fd, args);
7445 }
7446 }
7447
7448 if (locked) {
7449 mLock.unlock();
7450 }
7451
7452 return NO_ERROR;
7453}
7454
Eric Laurent59255e42011-07-27 19:49:51 -07007455// must be called with ThreadBase::mLock held
7456void AudioFlinger::EffectChain::setEffectSuspended_l(
7457 const effect_uuid_t *type, bool suspend)
7458{
7459 sp<SuspendedEffectDesc> desc;
7460 // use effect type UUID timelow as key as there is no real risk of identical
7461 // timeLow fields among effect type UUIDs.
7462 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7463 if (suspend) {
7464 if (index >= 0) {
7465 desc = mSuspendedEffects.valueAt(index);
7466 } else {
7467 desc = new SuspendedEffectDesc();
7468 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7469 mSuspendedEffects.add(type->timeLow, desc);
7470 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7471 }
7472 if (desc->mRefCount++ == 0) {
7473 sp<EffectModule> effect = getEffectIfEnabled(type);
7474 if (effect != 0) {
7475 desc->mEffect = effect;
7476 effect->setSuspended(true);
7477 effect->setEnabled(false);
7478 }
7479 }
7480 } else {
7481 if (index < 0) {
7482 return;
7483 }
7484 desc = mSuspendedEffects.valueAt(index);
7485 if (desc->mRefCount <= 0) {
7486 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7487 desc->mRefCount = 1;
7488 }
7489 if (--desc->mRefCount == 0) {
7490 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7491 if (desc->mEffect != 0) {
7492 sp<EffectModule> effect = desc->mEffect.promote();
7493 if (effect != 0) {
7494 effect->setSuspended(false);
7495 sp<EffectHandle> handle = effect->controlHandle();
7496 if (handle != 0) {
7497 effect->setEnabled(handle->enabled());
7498 }
7499 }
7500 desc->mEffect.clear();
7501 }
7502 mSuspendedEffects.removeItemsAt(index);
7503 }
7504 }
7505}
7506
7507// must be called with ThreadBase::mLock held
7508void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7509{
7510 sp<SuspendedEffectDesc> desc;
7511
7512 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7513 if (suspend) {
7514 if (index >= 0) {
7515 desc = mSuspendedEffects.valueAt(index);
7516 } else {
7517 desc = new SuspendedEffectDesc();
7518 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7519 LOGV("setEffectSuspendedAll_l() add entry for 0");
7520 }
7521 if (desc->mRefCount++ == 0) {
7522 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7523 for (size_t i = 0; i < effects.size(); i++) {
7524 setEffectSuspended_l(&effects[i]->desc().type, true);
7525 }
7526 }
7527 } else {
7528 if (index < 0) {
7529 return;
7530 }
7531 desc = mSuspendedEffects.valueAt(index);
7532 if (desc->mRefCount <= 0) {
7533 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7534 desc->mRefCount = 1;
7535 }
7536 if (--desc->mRefCount == 0) {
7537 Vector<const effect_uuid_t *> types;
7538 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7539 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7540 continue;
7541 }
7542 types.add(&mSuspendedEffects.valueAt(i)->mType);
7543 }
7544 for (size_t i = 0; i < types.size(); i++) {
7545 setEffectSuspended_l(types[i], false);
7546 }
7547 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7548 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7549 }
7550 }
7551}
7552
Eric Laurent6bffdb82011-09-23 08:40:41 -07007553
7554// The volume effect is used for automated tests only
7555#ifndef OPENSL_ES_H_
7556static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7557 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7558const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7559#endif //OPENSL_ES_H_
7560
Eric Laurentdb7c0792011-08-10 10:37:50 -07007561bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7562{
7563 // auxiliary effects and visualizer are never suspended on output mix
7564 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7565 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007566 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7567 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007568 return false;
7569 }
7570 return true;
7571}
7572
Eric Laurent59255e42011-07-27 19:49:51 -07007573Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7574{
7575 Vector< sp<EffectModule> > effects;
7576 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007577 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007578 continue;
7579 }
7580 effects.add(mEffects[i]);
7581 }
7582 return effects;
7583}
7584
7585sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7586 const effect_uuid_t *type)
7587{
7588 sp<EffectModule> effect;
7589 effect = getEffectFromType_l(type);
7590 if (effect != 0 && !effect->isEnabled()) {
7591 effect.clear();
7592 }
7593 return effect;
7594}
7595
7596void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7597 bool enabled)
7598{
7599 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7600 if (enabled) {
7601 if (index < 0) {
7602 // if the effect is not suspend check if all effects are suspended
7603 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7604 if (index < 0) {
7605 return;
7606 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007607 if (!isEffectEligibleForSuspend(effect->desc())) {
7608 return;
7609 }
Eric Laurent59255e42011-07-27 19:49:51 -07007610 setEffectSuspended_l(&effect->desc().type, enabled);
7611 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007612 if (index < 0) {
7613 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7614 return;
7615 }
Eric Laurent59255e42011-07-27 19:49:51 -07007616 }
7617 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7618 effect->desc().type.timeLow);
7619 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7620 // if effect is requested to suspended but was not yet enabled, supend it now.
7621 if (desc->mEffect == 0) {
7622 desc->mEffect = effect;
7623 effect->setEnabled(false);
7624 effect->setSuspended(true);
7625 }
7626 } else {
7627 if (index < 0) {
7628 return;
7629 }
7630 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7631 effect->desc().type.timeLow);
7632 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7633 desc->mEffect.clear();
7634 effect->setSuspended(false);
7635 }
7636}
7637
Mathias Agopian65ab4712010-07-14 17:59:35 -07007638#undef LOG_TAG
7639#define LOG_TAG "AudioFlinger"
7640
7641// ----------------------------------------------------------------------------
7642
7643status_t AudioFlinger::onTransact(
7644 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7645{
7646 return BnAudioFlinger::onTransact(code, data, reply, flags);
7647}
7648
Mathias Agopian65ab4712010-07-14 17:59:35 -07007649}; // namespace android