blob: d7b31b13fe710dbd77b0dcb3e309aedf5a5f76f8 [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) {
Glenn Kastend8796012011-10-28 10:31:42 -0700398 LOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399 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
Steve Block3856b092011-10-20 11:56:00 +0100422 ALOGV("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) {
Glenn Kastend8796012011-10-28 10:31:42 -0700430 LOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700431 lStatus = BAD_VALUE;
432 goto Exit;
433 }
434 // check if an effect with same session ID is waiting for a track to be created
435 if (sessions & PlaybackThread::EFFECT_SESSION) {
436 effectThread = t.get();
437 }
Eric Laurentde070132010-07-13 04:45:46 -0700438 }
439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 lSessionId = *sessionId;
441 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700442 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700443 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 if (sessionId != NULL) {
445 *sessionId = lSessionId;
446 }
447 }
Steve Block3856b092011-10-20 11:56:00 +0100448 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449
450 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700451 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700452
453 // move effect chain to this output thread if an effect on same session was waiting
454 // for a track to be created
455 if (lStatus == NO_ERROR && effectThread != NULL) {
456 Mutex::Autolock _dl(thread->mLock);
457 Mutex::Autolock _sl(effectThread->mLock);
458 moveEffectChain_l(lSessionId, effectThread, thread, true);
459 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700460 }
461 if (lStatus == NO_ERROR) {
462 trackHandle = new TrackHandle(track);
463 } else {
464 // remove local strong reference to Client before deleting the Track so that the Client
465 // destructor is called by the TrackBase destructor with mLock held
466 client.clear();
467 track.clear();
468 }
469
470Exit:
471 if(status) {
472 *status = lStatus;
473 }
474 return trackHandle;
475}
476
477uint32_t AudioFlinger::sampleRate(int output) const
478{
479 Mutex::Autolock _l(mLock);
480 PlaybackThread *thread = checkPlaybackThread_l(output);
481 if (thread == NULL) {
482 LOGW("sampleRate() unknown thread %d", output);
483 return 0;
484 }
485 return thread->sampleRate();
486}
487
488int AudioFlinger::channelCount(int output) const
489{
490 Mutex::Autolock _l(mLock);
491 PlaybackThread *thread = checkPlaybackThread_l(output);
492 if (thread == NULL) {
493 LOGW("channelCount() unknown thread %d", output);
494 return 0;
495 }
496 return thread->channelCount();
497}
498
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700499uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700500{
501 Mutex::Autolock _l(mLock);
502 PlaybackThread *thread = checkPlaybackThread_l(output);
503 if (thread == NULL) {
504 LOGW("format() unknown thread %d", output);
505 return 0;
506 }
507 return thread->format();
508}
509
510size_t AudioFlinger::frameCount(int output) const
511{
512 Mutex::Autolock _l(mLock);
513 PlaybackThread *thread = checkPlaybackThread_l(output);
514 if (thread == NULL) {
515 LOGW("frameCount() unknown thread %d", output);
516 return 0;
517 }
518 return thread->frameCount();
519}
520
521uint32_t AudioFlinger::latency(int output) const
522{
523 Mutex::Autolock _l(mLock);
524 PlaybackThread *thread = checkPlaybackThread_l(output);
525 if (thread == NULL) {
526 LOGW("latency() unknown thread %d", output);
527 return 0;
528 }
529 return thread->latency();
530}
531
532status_t AudioFlinger::setMasterVolume(float value)
533{
Eric Laurenta1884f92011-08-23 08:25:03 -0700534 status_t ret = initCheck();
535 if (ret != NO_ERROR) {
536 return ret;
537 }
538
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539 // check calling permissions
540 if (!settingsAllowed()) {
541 return PERMISSION_DENIED;
542 }
543
544 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800545 { // scope for the lock
546 AutoMutex lock(mHardwareLock);
547 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700548 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800549 value = 1.0f;
550 }
551 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700552 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553
Eric Laurent93575202011-01-18 18:39:02 -0800554 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 mMasterVolume = value;
556 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
557 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
558
559 return NO_ERROR;
560}
561
562status_t AudioFlinger::setMode(int mode)
563{
Eric Laurenta1884f92011-08-23 08:25:03 -0700564 status_t ret = initCheck();
565 if (ret != NO_ERROR) {
566 return ret;
567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700568
569 // check calling permissions
570 if (!settingsAllowed()) {
571 return PERMISSION_DENIED;
572 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700573 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700574 LOGW("Illegal value: setMode(%d)", mode);
575 return BAD_VALUE;
576 }
577
578 { // scope for the lock
579 AutoMutex lock(mHardwareLock);
580 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700581 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 mHardwareStatus = AUDIO_HW_IDLE;
583 }
584
585 if (NO_ERROR == ret) {
586 Mutex::Autolock _l(mLock);
587 mMode = mode;
588 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
589 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700590 }
591
592 return ret;
593}
594
595status_t AudioFlinger::setMicMute(bool state)
596{
Eric Laurenta1884f92011-08-23 08:25:03 -0700597 status_t ret = initCheck();
598 if (ret != NO_ERROR) {
599 return ret;
600 }
601
Mathias Agopian65ab4712010-07-14 17:59:35 -0700602 // check calling permissions
603 if (!settingsAllowed()) {
604 return PERMISSION_DENIED;
605 }
606
607 AutoMutex lock(mHardwareLock);
608 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700609 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700610 mHardwareStatus = AUDIO_HW_IDLE;
611 return ret;
612}
613
614bool AudioFlinger::getMicMute() const
615{
Eric Laurenta1884f92011-08-23 08:25:03 -0700616 status_t ret = initCheck();
617 if (ret != NO_ERROR) {
618 return false;
619 }
620
Dima Zavinfce7a472011-04-19 22:30:36 -0700621 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700623 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 mHardwareStatus = AUDIO_HW_IDLE;
625 return state;
626}
627
628status_t AudioFlinger::setMasterMute(bool muted)
629{
630 // check calling permissions
631 if (!settingsAllowed()) {
632 return PERMISSION_DENIED;
633 }
634
Eric Laurent93575202011-01-18 18:39:02 -0800635 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700636 mMasterMute = muted;
637 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
638 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
639
640 return NO_ERROR;
641}
642
643float AudioFlinger::masterVolume() const
644{
645 return mMasterVolume;
646}
647
648bool AudioFlinger::masterMute() const
649{
650 return mMasterMute;
651}
652
653status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
654{
655 // check calling permissions
656 if (!settingsAllowed()) {
657 return PERMISSION_DENIED;
658 }
659
Dima Zavinfce7a472011-04-19 22:30:36 -0700660 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Glenn Kastend8796012011-10-28 10:31:42 -0700661 LOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 return BAD_VALUE;
663 }
664
665 AutoMutex lock(mLock);
666 PlaybackThread *thread = NULL;
667 if (output) {
668 thread = checkPlaybackThread_l(output);
669 if (thread == NULL) {
670 return BAD_VALUE;
671 }
672 }
673
674 mStreamTypes[stream].volume = value;
675
676 if (thread == NULL) {
677 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
678 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
679 }
680 } else {
681 thread->setStreamVolume(stream, value);
682 }
683
684 return NO_ERROR;
685}
686
687status_t AudioFlinger::setStreamMute(int stream, bool muted)
688{
689 // check calling permissions
690 if (!settingsAllowed()) {
691 return PERMISSION_DENIED;
692 }
693
Dima Zavinfce7a472011-04-19 22:30:36 -0700694 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
695 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Glenn Kastend8796012011-10-28 10:31:42 -0700696 LOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697 return BAD_VALUE;
698 }
699
Eric Laurent93575202011-01-18 18:39:02 -0800700 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 mStreamTypes[stream].mute = muted;
702 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
703 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
704
705 return NO_ERROR;
706}
707
708float AudioFlinger::streamVolume(int stream, int output) const
709{
Dima Zavinfce7a472011-04-19 22:30:36 -0700710 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711 return 0.0f;
712 }
713
714 AutoMutex lock(mLock);
715 float volume;
716 if (output) {
717 PlaybackThread *thread = checkPlaybackThread_l(output);
718 if (thread == NULL) {
719 return 0.0f;
720 }
721 volume = thread->streamVolume(stream);
722 } else {
723 volume = mStreamTypes[stream].volume;
724 }
725
726 return volume;
727}
728
729bool AudioFlinger::streamMute(int stream) const
730{
Dima Zavinfce7a472011-04-19 22:30:36 -0700731 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 return true;
733 }
734
735 return mStreamTypes[stream].mute;
736}
737
Mathias Agopian65ab4712010-07-14 17:59:35 -0700738status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
739{
740 status_t result;
741
Steve Block3856b092011-10-20 11:56:00 +0100742 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
744 // check calling permissions
745 if (!settingsAllowed()) {
746 return PERMISSION_DENIED;
747 }
748
Mathias Agopian65ab4712010-07-14 17:59:35 -0700749 // ioHandle == 0 means the parameters are global to the audio hardware interface
750 if (ioHandle == 0) {
751 AutoMutex lock(mHardwareLock);
752 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700753 status_t final_result = NO_ERROR;
754 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
755 audio_hw_device_t *dev = mAudioHwDevs[i];
756 result = dev->set_parameters(dev, keyValuePairs.string());
757 final_result = result ?: final_result;
758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700759 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700760 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
761 AudioParameter param = AudioParameter(keyValuePairs);
762 String8 value;
763 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
764 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700765 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
766 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700767 for (size_t i = 0; i < mRecordThreads.size(); i++) {
768 sp<RecordThread> thread = mRecordThreads.valueAt(i);
769 RecordThread::RecordTrack *track = thread->track();
770 if (track != NULL) {
771 audio_devices_t device = (audio_devices_t)(
772 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700773 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700774 thread->setEffectSuspended(FX_IID_AEC,
775 suspend,
776 track->sessionId());
777 thread->setEffectSuspended(FX_IID_NS,
778 suspend,
779 track->sessionId());
780 }
781 }
Eric Laurentbee53372011-08-29 12:42:48 -0700782 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700783 }
784 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700785 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700786 }
787
788 // hold a strong ref on thread in case closeOutput() or closeInput() is called
789 // and the thread is exited once the lock is released
790 sp<ThreadBase> thread;
791 {
792 Mutex::Autolock _l(mLock);
793 thread = checkPlaybackThread_l(ioHandle);
794 if (thread == NULL) {
795 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700796 } else if (thread.get() == primaryPlaybackThread_l()) {
797 // indicate output device change to all input threads for pre processing
798 AudioParameter param = AudioParameter(keyValuePairs);
799 int value;
800 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
801 for (size_t i = 0; i < mRecordThreads.size(); i++) {
802 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
803 }
804 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700805 }
806 }
807 if (thread != NULL) {
808 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 return result;
810 }
811 return BAD_VALUE;
812}
813
814String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
815{
Steve Block3856b092011-10-20 11:56:00 +0100816// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700817// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
818
819 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700820 String8 out_s8;
821
Dima Zavin799a70e2011-04-18 16:57:27 -0700822 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
823 audio_hw_device_t *dev = mAudioHwDevs[i];
824 char *s = dev->get_parameters(dev, keys.string());
825 out_s8 += String8(s);
826 free(s);
827 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700828 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700829 }
830
831 Mutex::Autolock _l(mLock);
832
833 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
834 if (playbackThread != NULL) {
835 return playbackThread->getParameters(keys);
836 }
837 RecordThread *recordThread = checkRecordThread_l(ioHandle);
838 if (recordThread != NULL) {
839 return recordThread->getParameters(keys);
840 }
841 return String8("");
842}
843
844size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
845{
Eric Laurenta1884f92011-08-23 08:25:03 -0700846 status_t ret = initCheck();
847 if (ret != NO_ERROR) {
848 return 0;
849 }
850
Dima Zavin799a70e2011-04-18 16:57:27 -0700851 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700852}
853
854unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
855{
856 if (ioHandle == 0) {
857 return 0;
858 }
859
860 Mutex::Autolock _l(mLock);
861
862 RecordThread *recordThread = checkRecordThread_l(ioHandle);
863 if (recordThread != NULL) {
864 return recordThread->getInputFramesLost();
865 }
866 return 0;
867}
868
869status_t AudioFlinger::setVoiceVolume(float value)
870{
Eric Laurenta1884f92011-08-23 08:25:03 -0700871 status_t ret = initCheck();
872 if (ret != NO_ERROR) {
873 return ret;
874 }
875
Mathias Agopian65ab4712010-07-14 17:59:35 -0700876 // check calling permissions
877 if (!settingsAllowed()) {
878 return PERMISSION_DENIED;
879 }
880
881 AutoMutex lock(mHardwareLock);
882 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700883 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700884 mHardwareStatus = AUDIO_HW_IDLE;
885
886 return ret;
887}
888
889status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
890{
891 status_t status;
892
893 Mutex::Autolock _l(mLock);
894
895 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
896 if (playbackThread != NULL) {
897 return playbackThread->getRenderPosition(halFrames, dspFrames);
898 }
899
900 return BAD_VALUE;
901}
902
903void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
904{
905
906 Mutex::Autolock _l(mLock);
907
908 int pid = IPCThreadState::self()->getCallingPid();
909 if (mNotificationClients.indexOfKey(pid) < 0) {
910 sp<NotificationClient> notificationClient = new NotificationClient(this,
911 client,
912 pid);
Steve Block3856b092011-10-20 11:56:00 +0100913 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700914
915 mNotificationClients.add(pid, notificationClient);
916
917 sp<IBinder> binder = client->asBinder();
918 binder->linkToDeath(notificationClient);
919
920 // the config change is always sent from playback or record threads to avoid deadlock
921 // with AudioSystem::gLock
922 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
923 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
924 }
925
926 for (size_t i = 0; i < mRecordThreads.size(); i++) {
927 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
928 }
929 }
930}
931
932void AudioFlinger::removeNotificationClient(pid_t pid)
933{
934 Mutex::Autolock _l(mLock);
935
936 int index = mNotificationClients.indexOfKey(pid);
937 if (index >= 0) {
938 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100939 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700940 mNotificationClients.removeItem(pid);
941 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700942
Steve Block3856b092011-10-20 11:56:00 +0100943 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700944 int num = mAudioSessionRefs.size();
945 bool removed = false;
946 for (int i = 0; i< num; i++) {
947 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700949 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100950 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700951 mAudioSessionRefs.removeAt(i);
952 delete ref;
953 removed = true;
954 i--;
955 num--;
956 }
957 }
958 if (removed) {
959 purgeStaleEffects_l();
960 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700961}
962
963// audioConfigChanged_l() must be called with AudioFlinger::mLock held
964void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
965{
966 size_t size = mNotificationClients.size();
967 for (size_t i = 0; i < size; i++) {
968 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
969 }
970}
971
972// removeClient_l() must be called with AudioFlinger::mLock held
973void AudioFlinger::removeClient_l(pid_t pid)
974{
Steve Block3856b092011-10-20 11:56:00 +0100975 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700976 mClients.removeItem(pid);
977}
978
979
980// ----------------------------------------------------------------------------
981
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700982AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700983 : Thread(false),
984 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700985 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
986 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700988 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700989}
990
991AudioFlinger::ThreadBase::~ThreadBase()
992{
993 mParamCond.broadcast();
994 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700995 // do not lock the mutex in destructor
996 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700997 if (mPowerManager != 0) {
998 sp<IBinder> binder = mPowerManager->asBinder();
999 binder->unlinkToDeath(mDeathRecipient);
1000 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001}
1002
1003void AudioFlinger::ThreadBase::exit()
1004{
1005 // keep a strong ref on ourself so that we wont get
1006 // destroyed in the middle of requestExitAndWait()
1007 sp <ThreadBase> strongMe = this;
1008
Steve Block3856b092011-10-20 11:56:00 +01001009 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 {
1011 AutoMutex lock(&mLock);
1012 mExiting = true;
1013 requestExit();
1014 mWaitWorkCV.signal();
1015 }
1016 requestExitAndWait();
1017}
1018
1019uint32_t AudioFlinger::ThreadBase::sampleRate() const
1020{
1021 return mSampleRate;
1022}
1023
1024int AudioFlinger::ThreadBase::channelCount() const
1025{
1026 return (int)mChannelCount;
1027}
1028
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001029uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001030{
1031 return mFormat;
1032}
1033
1034size_t AudioFlinger::ThreadBase::frameCount() const
1035{
1036 return mFrameCount;
1037}
1038
1039status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1040{
1041 status_t status;
1042
Steve Block3856b092011-10-20 11:56:00 +01001043 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 Mutex::Autolock _l(mLock);
1045
1046 mNewParameters.add(keyValuePairs);
1047 mWaitWorkCV.signal();
1048 // wait condition with timeout in case the thread loop has exited
1049 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001050 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 status = mParamStatus;
1052 mWaitWorkCV.signal();
1053 } else {
1054 status = TIMED_OUT;
1055 }
1056 return status;
1057}
1058
1059void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1060{
1061 Mutex::Autolock _l(mLock);
1062 sendConfigEvent_l(event, param);
1063}
1064
1065// sendConfigEvent_l() must be called with ThreadBase::mLock held
1066void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1067{
1068 ConfigEvent *configEvent = new ConfigEvent();
1069 configEvent->mEvent = event;
1070 configEvent->mParam = param;
1071 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001072 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001073 mWaitWorkCV.signal();
1074}
1075
1076void AudioFlinger::ThreadBase::processConfigEvents()
1077{
1078 mLock.lock();
1079 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001080 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 ConfigEvent *configEvent = mConfigEvents[0];
1082 mConfigEvents.removeAt(0);
1083 // release mLock before locking AudioFlinger mLock: lock order is always
1084 // AudioFlinger then ThreadBase to avoid cross deadlock
1085 mLock.unlock();
1086 mAudioFlinger->mLock.lock();
1087 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1088 mAudioFlinger->mLock.unlock();
1089 delete configEvent;
1090 mLock.lock();
1091 }
1092 mLock.unlock();
1093}
1094
1095status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1096{
1097 const size_t SIZE = 256;
1098 char buffer[SIZE];
1099 String8 result;
1100
1101 bool locked = tryLock(mLock);
1102 if (!locked) {
1103 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1104 write(fd, buffer, strlen(buffer));
1105 }
1106
1107 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1108 result.append(buffer);
1109 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1114 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001115 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1116 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001117 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1118 result.append(buffer);
1119 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1120 result.append(buffer);
1121
1122 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1123 result.append(buffer);
1124 result.append(" Index Command");
1125 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1126 snprintf(buffer, SIZE, "\n %02d ", i);
1127 result.append(buffer);
1128 result.append(mNewParameters[i]);
1129 }
1130
1131 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1132 result.append(buffer);
1133 snprintf(buffer, SIZE, " Index event param\n");
1134 result.append(buffer);
1135 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1136 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1137 result.append(buffer);
1138 }
1139 result.append("\n");
1140
1141 write(fd, result.string(), result.size());
1142
1143 if (locked) {
1144 mLock.unlock();
1145 }
1146 return NO_ERROR;
1147}
1148
Eric Laurent1d2bff02011-07-24 17:49:51 -07001149status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1150{
1151 const size_t SIZE = 256;
1152 char buffer[SIZE];
1153 String8 result;
1154
1155 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1156 write(fd, buffer, strlen(buffer));
1157
1158 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1159 sp<EffectChain> chain = mEffectChains[i];
1160 if (chain != 0) {
1161 chain->dump(fd, args);
1162 }
1163 }
1164 return NO_ERROR;
1165}
1166
Eric Laurentfeb0db62011-07-22 09:04:31 -07001167void AudioFlinger::ThreadBase::acquireWakeLock()
1168{
1169 Mutex::Autolock _l(mLock);
1170 acquireWakeLock_l();
1171}
1172
1173void AudioFlinger::ThreadBase::acquireWakeLock_l()
1174{
1175 if (mPowerManager == 0) {
1176 // use checkService() to avoid blocking if power service is not up yet
1177 sp<IBinder> binder =
1178 defaultServiceManager()->checkService(String16("power"));
1179 if (binder == 0) {
1180 LOGW("Thread %s cannot connect to the power manager service", mName);
1181 } else {
1182 mPowerManager = interface_cast<IPowerManager>(binder);
1183 binder->linkToDeath(mDeathRecipient);
1184 }
1185 }
1186 if (mPowerManager != 0) {
1187 sp<IBinder> binder = new BBinder();
1188 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1189 binder,
1190 String16(mName));
1191 if (status == NO_ERROR) {
1192 mWakeLockToken = binder;
1193 }
Steve Block3856b092011-10-20 11:56:00 +01001194 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001195 }
1196}
1197
1198void AudioFlinger::ThreadBase::releaseWakeLock()
1199{
1200 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001201 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001202}
1203
1204void AudioFlinger::ThreadBase::releaseWakeLock_l()
1205{
1206 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001207 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001208 if (mPowerManager != 0) {
1209 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1210 }
1211 mWakeLockToken.clear();
1212 }
1213}
1214
1215void AudioFlinger::ThreadBase::clearPowerManager()
1216{
1217 Mutex::Autolock _l(mLock);
1218 releaseWakeLock_l();
1219 mPowerManager.clear();
1220}
1221
1222void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1223{
1224 sp<ThreadBase> thread = mThread.promote();
1225 if (thread != 0) {
1226 thread->clearPowerManager();
1227 }
1228 LOGW("power manager service died !!!");
1229}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001230
Eric Laurent59255e42011-07-27 19:49:51 -07001231void AudioFlinger::ThreadBase::setEffectSuspended(
1232 const effect_uuid_t *type, bool suspend, int sessionId)
1233{
1234 Mutex::Autolock _l(mLock);
1235 setEffectSuspended_l(type, suspend, sessionId);
1236}
1237
1238void AudioFlinger::ThreadBase::setEffectSuspended_l(
1239 const effect_uuid_t *type, bool suspend, int sessionId)
1240{
1241 sp<EffectChain> chain;
1242 chain = getEffectChain_l(sessionId);
1243 if (chain != 0) {
1244 if (type != NULL) {
1245 chain->setEffectSuspended_l(type, suspend);
1246 } else {
1247 chain->setEffectSuspendedAll_l(suspend);
1248 }
1249 }
1250
1251 updateSuspendedSessions_l(type, suspend, sessionId);
1252}
1253
1254void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1255{
1256 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1257 if (index < 0) {
1258 return;
1259 }
1260
1261 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1262 mSuspendedSessions.editValueAt(index);
1263
1264 for (size_t i = 0; i < sessionEffects.size(); i++) {
1265 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1266 for (int j = 0; j < desc->mRefCount; j++) {
1267 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1268 chain->setEffectSuspendedAll_l(true);
1269 } else {
Steve Block3856b092011-10-20 11:56:00 +01001270 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001271 desc->mType.timeLow);
1272 chain->setEffectSuspended_l(&desc->mType, true);
1273 }
1274 }
1275 }
1276}
1277
Eric Laurent59255e42011-07-27 19:49:51 -07001278void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1279 bool suspend,
1280 int sessionId)
1281{
1282 int index = mSuspendedSessions.indexOfKey(sessionId);
1283
1284 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1285
1286 if (suspend) {
1287 if (index >= 0) {
1288 sessionEffects = mSuspendedSessions.editValueAt(index);
1289 } else {
1290 mSuspendedSessions.add(sessionId, sessionEffects);
1291 }
1292 } else {
1293 if (index < 0) {
1294 return;
1295 }
1296 sessionEffects = mSuspendedSessions.editValueAt(index);
1297 }
1298
1299
1300 int key = EffectChain::kKeyForSuspendAll;
1301 if (type != NULL) {
1302 key = type->timeLow;
1303 }
1304 index = sessionEffects.indexOfKey(key);
1305
1306 sp <SuspendedSessionDesc> desc;
1307 if (suspend) {
1308 if (index >= 0) {
1309 desc = sessionEffects.valueAt(index);
1310 } else {
1311 desc = new SuspendedSessionDesc();
1312 if (type != NULL) {
1313 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1314 }
1315 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001316 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001317 }
1318 desc->mRefCount++;
1319 } else {
1320 if (index < 0) {
1321 return;
1322 }
1323 desc = sessionEffects.valueAt(index);
1324 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001325 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001326 sessionEffects.removeItemsAt(index);
1327 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001328 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001329 sessionId);
1330 mSuspendedSessions.removeItem(sessionId);
1331 }
1332 }
1333 }
1334 if (!sessionEffects.isEmpty()) {
1335 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1336 }
1337}
1338
1339void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1340 bool enabled,
1341 int sessionId)
1342{
1343 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001344 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1345}
Eric Laurent59255e42011-07-27 19:49:51 -07001346
Eric Laurenta85a74a2011-10-19 11:44:54 -07001347void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1348 bool enabled,
1349 int sessionId)
1350{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001351 if (mType != RECORD) {
1352 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1353 // another session. This gives the priority to well behaved effect control panels
1354 // and applications not using global effects.
1355 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1356 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1357 }
1358 }
Eric Laurent59255e42011-07-27 19:49:51 -07001359
1360 sp<EffectChain> chain = getEffectChain_l(sessionId);
1361 if (chain != 0) {
1362 chain->checkSuspendOnEffectEnabled(effect, enabled);
1363 }
1364}
1365
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366// ----------------------------------------------------------------------------
1367
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001368AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1369 AudioStreamOut* output,
1370 int id,
1371 uint32_t device)
1372 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001373 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001374 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001375{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001376 snprintf(mName, kNameLength, "AudioOut_%d", id);
1377
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378 readOutputParameters();
1379
1380 mMasterVolume = mAudioFlinger->masterVolume();
1381 mMasterMute = mAudioFlinger->masterMute();
1382
Dima Zavinfce7a472011-04-19 22:30:36 -07001383 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1385 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001386 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 }
1388}
1389
1390AudioFlinger::PlaybackThread::~PlaybackThread()
1391{
1392 delete [] mMixBuffer;
1393}
1394
1395status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1396{
1397 dumpInternals(fd, args);
1398 dumpTracks(fd, args);
1399 dumpEffectChains(fd, args);
1400 return NO_ERROR;
1401}
1402
1403status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1404{
1405 const size_t SIZE = 256;
1406 char buffer[SIZE];
1407 String8 result;
1408
1409 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1410 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001411 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 -07001412 for (size_t i = 0; i < mTracks.size(); ++i) {
1413 sp<Track> track = mTracks[i];
1414 if (track != 0) {
1415 track->dump(buffer, SIZE);
1416 result.append(buffer);
1417 }
1418 }
1419
1420 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1421 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001422 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 -07001423 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1424 wp<Track> wTrack = mActiveTracks[i];
1425 if (wTrack != 0) {
1426 sp<Track> track = wTrack.promote();
1427 if (track != 0) {
1428 track->dump(buffer, SIZE);
1429 result.append(buffer);
1430 }
1431 }
1432 }
1433 write(fd, result.string(), result.size());
1434 return NO_ERROR;
1435}
1436
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1438{
1439 const size_t SIZE = 256;
1440 char buffer[SIZE];
1441 String8 result;
1442
1443 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1444 result.append(buffer);
1445 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1456 result.append(buffer);
1457 write(fd, result.string(), result.size());
1458
1459 dumpBase(fd, args);
1460
1461 return NO_ERROR;
1462}
1463
1464// Thread virtuals
1465status_t AudioFlinger::PlaybackThread::readyToRun()
1466{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001467 status_t status = initCheck();
1468 if (status == NO_ERROR) {
1469 LOGI("AudioFlinger's thread %p ready to run", this);
1470 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001472 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001473 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474}
1475
1476void AudioFlinger::PlaybackThread::onFirstRef()
1477{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001478 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001479}
1480
1481// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1482sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1483 const sp<AudioFlinger::Client>& client,
1484 int streamType,
1485 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001486 uint32_t format,
1487 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 int frameCount,
1489 const sp<IMemory>& sharedBuffer,
1490 int sessionId,
1491 status_t *status)
1492{
1493 sp<Track> track;
1494 status_t lStatus;
1495
1496 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001497 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1498 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1499 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1500 "for output %p with format %d",
1501 sampleRate, format, channelMask, mOutput, mFormat);
1502 lStatus = BAD_VALUE;
1503 goto Exit;
1504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 }
1506 } else {
1507 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1508 if (sampleRate > mSampleRate*2) {
1509 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1510 lStatus = BAD_VALUE;
1511 goto Exit;
1512 }
1513 }
1514
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001515 lStatus = initCheck();
1516 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 goto Exit;
1519 }
1520
1521 { // scope for mLock
1522 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001523
1524 // all tracks in same audio session must share the same routing strategy otherwise
1525 // conflicts will happen when tracks are moved from one output to another by audio policy
1526 // manager
1527 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001528 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001529 for (size_t i = 0; i < mTracks.size(); ++i) {
1530 sp<Track> t = mTracks[i];
1531 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001532 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1533 if (sessionId == t->sessionId() && strategy != actual) {
1534 LOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1535 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001536 lStatus = BAD_VALUE;
1537 goto Exit;
1538 }
1539 }
1540 }
1541
Mathias Agopian65ab4712010-07-14 17:59:35 -07001542 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001543 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 if (track->getCblk() == NULL || track->name() < 0) {
1545 lStatus = NO_MEMORY;
1546 goto Exit;
1547 }
1548 mTracks.add(track);
1549
1550 sp<EffectChain> chain = getEffectChain_l(sessionId);
1551 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001552 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001554 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001555 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001557
1558 // invalidate track immediately if the stream type was moved to another thread since
1559 // createTrack() was called by the client process.
1560 if (!mStreamTypes[streamType].valid) {
1561 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1562 this, streamType);
1563 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1564 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 }
1566 lStatus = NO_ERROR;
1567
1568Exit:
1569 if(status) {
1570 *status = lStatus;
1571 }
1572 return track;
1573}
1574
1575uint32_t AudioFlinger::PlaybackThread::latency() const
1576{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001577 Mutex::Autolock _l(mLock);
1578 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001579 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001580 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 return 0;
1582 }
1583}
1584
1585status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1586{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001587 mMasterVolume = value;
1588 return NO_ERROR;
1589}
1590
1591status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1592{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001593 mMasterMute = muted;
1594 return NO_ERROR;
1595}
1596
1597float AudioFlinger::PlaybackThread::masterVolume() const
1598{
1599 return mMasterVolume;
1600}
1601
1602bool AudioFlinger::PlaybackThread::masterMute() const
1603{
1604 return mMasterMute;
1605}
1606
1607status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1608{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 mStreamTypes[stream].volume = value;
1610 return NO_ERROR;
1611}
1612
1613status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1614{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001615 mStreamTypes[stream].mute = muted;
1616 return NO_ERROR;
1617}
1618
1619float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1620{
1621 return mStreamTypes[stream].volume;
1622}
1623
1624bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1625{
1626 return mStreamTypes[stream].mute;
1627}
1628
Mathias Agopian65ab4712010-07-14 17:59:35 -07001629// addTrack_l() must be called with ThreadBase::mLock held
1630status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1631{
1632 status_t status = ALREADY_EXISTS;
1633
1634 // set retry count for buffer fill
1635 track->mRetryCount = kMaxTrackStartupRetries;
1636 if (mActiveTracks.indexOf(track) < 0) {
1637 // the track is newly added, make sure it fills up all its
1638 // buffers before playing. This is to ensure the client will
1639 // effectively get the latency it requested.
1640 track->mFillingUpStatus = Track::FS_FILLING;
1641 track->mResetDone = false;
1642 mActiveTracks.add(track);
1643 if (track->mainBuffer() != mMixBuffer) {
1644 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1645 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001646 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001647 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001648 }
1649 }
1650
1651 status = NO_ERROR;
1652 }
1653
Steve Block3856b092011-10-20 11:56:00 +01001654 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 mWaitWorkCV.broadcast();
1656
1657 return status;
1658}
1659
1660// destroyTrack_l() must be called with ThreadBase::mLock held
1661void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1662{
1663 track->mState = TrackBase::TERMINATED;
1664 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001665 removeTrack_l(track);
1666 }
1667}
1668
1669void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1670{
1671 mTracks.remove(track);
1672 deleteTrackName_l(track->name());
1673 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1674 if (chain != 0) {
1675 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001676 }
1677}
1678
1679String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1680{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001682 char *s;
1683
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001684 Mutex::Autolock _l(mLock);
1685 if (initCheck() != NO_ERROR) {
1686 return out_s8;
1687 }
1688
Dima Zavin799a70e2011-04-18 16:57:27 -07001689 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001690 out_s8 = String8(s);
1691 free(s);
1692 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693}
1694
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001695// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1697 AudioSystem::OutputDescriptor desc;
1698 void *param2 = 0;
1699
Steve Block3856b092011-10-20 11:56:00 +01001700 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001701
1702 switch (event) {
1703 case AudioSystem::OUTPUT_OPENED:
1704 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001705 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001706 desc.samplingRate = mSampleRate;
1707 desc.format = mFormat;
1708 desc.frameCount = mFrameCount;
1709 desc.latency = latency();
1710 param2 = &desc;
1711 break;
1712
1713 case AudioSystem::STREAM_CONFIG_CHANGED:
1714 param2 = &param;
1715 case AudioSystem::OUTPUT_CLOSED:
1716 default:
1717 break;
1718 }
1719 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1720}
1721
1722void AudioFlinger::PlaybackThread::readOutputParameters()
1723{
Dima Zavin799a70e2011-04-18 16:57:27 -07001724 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001725 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1726 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001727 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1728 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1729 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001730
1731 // FIXME - Current mixer implementation only supports stereo output: Always
1732 // Allocate a stereo buffer even if HW output is mono.
1733 if (mMixBuffer != NULL) delete[] mMixBuffer;
1734 mMixBuffer = new int16_t[mFrameCount * 2];
1735 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1736
Eric Laurentde070132010-07-13 04:45:46 -07001737 // force reconfiguration of effect chains and engines to take new buffer size and audio
1738 // parameters into account
1739 // Note that mLock is not held when readOutputParameters() is called from the constructor
1740 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1741 // matter.
1742 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1743 Vector< sp<EffectChain> > effectChains = mEffectChains;
1744 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001745 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001746 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747}
1748
1749status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1750{
1751 if (halFrames == 0 || dspFrames == 0) {
1752 return BAD_VALUE;
1753 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001754 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001755 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 return INVALID_OPERATION;
1757 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001758 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759
Dima Zavin799a70e2011-04-18 16:57:27 -07001760 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761}
1762
Eric Laurent39e94f82010-07-28 01:32:47 -07001763uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764{
1765 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001766 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001768 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 }
1770
1771 for (size_t i = 0; i < mTracks.size(); ++i) {
1772 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001773 if (sessionId == track->sessionId() &&
1774 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001775 result |= TRACK_SESSION;
1776 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001777 }
1778 }
1779
Eric Laurent39e94f82010-07-28 01:32:47 -07001780 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001781}
1782
Eric Laurentde070132010-07-13 04:45:46 -07001783uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1784{
Dima Zavinfce7a472011-04-19 22:30:36 -07001785 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001786 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001787 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1788 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001789 }
1790 for (size_t i = 0; i < mTracks.size(); i++) {
1791 sp<Track> track = mTracks[i];
1792 if (sessionId == track->sessionId() &&
1793 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001794 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001795 }
1796 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001797 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001798}
1799
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001801AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1802{
1803 Mutex::Autolock _l(mLock);
1804 return mOutput;
1805}
1806
1807AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1808{
1809 Mutex::Autolock _l(mLock);
1810 AudioStreamOut *output = mOutput;
1811 mOutput = NULL;
1812 return output;
1813}
1814
1815// this method must always be called either with ThreadBase mLock held or inside the thread loop
1816audio_stream_t* AudioFlinger::PlaybackThread::stream()
1817{
1818 if (mOutput == NULL) {
1819 return NULL;
1820 }
1821 return &mOutput->stream->common;
1822}
1823
Eric Laurent162b40b2011-12-05 09:47:19 -08001824uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1825{
1826 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1827 // decoding and transfer time. So sleeping for half of the latency would likely cause
1828 // underruns
1829 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1830 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1831 } else {
1832 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1833 }
1834}
1835
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836// ----------------------------------------------------------------------------
1837
Dima Zavin799a70e2011-04-18 16:57:27 -07001838AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 : PlaybackThread(audioFlinger, output, id, device),
1840 mAudioMixer(0)
1841{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001842 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1844
1845 // FIXME - Current mixer implementation only supports stereo output
1846 if (mChannelCount == 1) {
1847 LOGE("Invalid audio hardware channel count");
1848 }
1849}
1850
1851AudioFlinger::MixerThread::~MixerThread()
1852{
1853 delete mAudioMixer;
1854}
1855
1856bool AudioFlinger::MixerThread::threadLoop()
1857{
1858 Vector< sp<Track> > tracksToRemove;
1859 uint32_t mixerStatus = MIXER_IDLE;
1860 nsecs_t standbyTime = systemTime();
1861 size_t mixBufferSize = mFrameCount * mFrameSize;
1862 // FIXME: Relaxed timing because of a certain device that can't meet latency
1863 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001864 // increase threshold again due to low power audio mode. The way this warning threshold is
1865 // calculated and its usefulness should be reconsidered anyway.
1866 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 nsecs_t lastWarning = 0;
1868 bool longStandbyExit = false;
1869 uint32_t activeSleepTime = activeSleepTimeUs();
1870 uint32_t idleSleepTime = idleSleepTimeUs();
1871 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001872 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001873 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001874#ifdef DEBUG_CPU_USAGE
1875 ThreadCpuUsage cpu;
1876 const CentralTendencyStatistics& stats = cpu.statistics();
1877#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878
Eric Laurentfeb0db62011-07-22 09:04:31 -07001879 acquireWakeLock();
1880
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 while (!exitPending())
1882 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001883#ifdef DEBUG_CPU_USAGE
1884 cpu.sampleAndEnable();
1885 unsigned n = stats.n();
1886 // cpu.elapsed() is expensive, so don't call it every loop
1887 if ((n & 127) == 1) {
1888 long long elapsed = cpu.elapsed();
1889 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1890 double perLoop = elapsed / (double) n;
1891 double perLoop100 = perLoop * 0.01;
1892 double mean = stats.mean();
1893 double stddev = stats.stddev();
1894 double minimum = stats.minimum();
1895 double maximum = stats.maximum();
1896 cpu.resetStatistics();
1897 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",
1898 elapsed * .000000001, n, perLoop * .000001,
1899 mean * .001,
1900 stddev * .001,
1901 minimum * .001,
1902 maximum * .001,
1903 mean / perLoop100,
1904 stddev / perLoop100,
1905 minimum / perLoop100,
1906 maximum / perLoop100);
1907 }
1908 }
1909#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001910 processConfigEvents();
1911
1912 mixerStatus = MIXER_IDLE;
1913 { // scope for mLock
1914
1915 Mutex::Autolock _l(mLock);
1916
1917 if (checkForNewParameters_l()) {
1918 mixBufferSize = mFrameCount * mFrameSize;
1919 // FIXME: Relaxed timing because of a certain device that can't meet latency
1920 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001921 // increase threshold again due to low power audio mode. The way this warning
1922 // threshold is calculated and its usefulness should be reconsidered anyway.
1923 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001924 activeSleepTime = activeSleepTimeUs();
1925 idleSleepTime = idleSleepTimeUs();
1926 }
1927
1928 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1929
1930 // put audio hardware into standby after short delay
1931 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1932 mSuspended) {
1933 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001934 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001935 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 mStandby = true;
1937 mBytesWritten = 0;
1938 }
1939
1940 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1941 // we're about to wait, flush the binder command buffer
1942 IPCThreadState::self()->flushCommands();
1943
1944 if (exitPending()) break;
1945
Eric Laurentfeb0db62011-07-22 09:04:31 -07001946 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001947 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001948 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001950 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001951 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952
1953 if (mMasterMute == false) {
1954 char value[PROPERTY_VALUE_MAX];
1955 property_get("ro.audio.silent", value, "0");
1956 if (atoi(value)) {
1957 LOGD("Silence is golden");
1958 setMasterMute(true);
1959 }
1960 }
1961
1962 standbyTime = systemTime() + kStandbyTimeInNsecs;
1963 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001964 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965 continue;
1966 }
1967 }
1968
1969 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1970
1971 // prevent any changes in effect chain list and in each effect chain
1972 // during mixing and effect process as the audio buffers could be deleted
1973 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001974 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 }
1976
1977 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1978 // mix buffers...
1979 mAudioMixer->process();
1980 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001981 // increase sleep time progressively when application underrun condition clears
1982 if (sleepTimeShift > 0) {
1983 sleepTimeShift--;
1984 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 standbyTime = systemTime() + kStandbyTimeInNsecs;
1986 //TODO: delay standby when effects have a tail
1987 } else {
1988 // If no tracks are ready, sleep once for the duration of an output
1989 // buffer size, then write 0s to the output
1990 if (sleepTime == 0) {
1991 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001992 sleepTime = activeSleepTime >> sleepTimeShift;
1993 if (sleepTime < kMinThreadSleepTimeUs) {
1994 sleepTime = kMinThreadSleepTimeUs;
1995 }
1996 // reduce sleep time in case of consecutive application underruns to avoid
1997 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1998 // duration we would end up writing less data than needed by the audio HAL if
1999 // the condition persists.
2000 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2001 sleepTimeShift++;
2002 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002003 } else {
2004 sleepTime = idleSleepTime;
2005 }
2006 } else if (mBytesWritten != 0 ||
2007 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2008 memset (mMixBuffer, 0, mixBufferSize);
2009 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002010 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002011 }
2012 // TODO add standby time extension fct of effect tail
2013 }
2014
2015 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002016 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 }
2018 // sleepTime == 0 means we must write to audio hardware
2019 if (sleepTime == 0) {
2020 for (size_t i = 0; i < effectChains.size(); i ++) {
2021 effectChains[i]->process_l();
2022 }
2023 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002024 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002025 mLastWriteTime = systemTime();
2026 mInWrite = true;
2027 mBytesWritten += mixBufferSize;
2028
Dima Zavin799a70e2011-04-18 16:57:27 -07002029 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2031 mNumWrites++;
2032 mInWrite = false;
2033 nsecs_t now = systemTime();
2034 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002035 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002036 mNumDelayedWrites++;
2037 if ((now - lastWarning) > kWarningThrottle) {
2038 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2039 ns2ms(delta), mNumDelayedWrites, this);
2040 lastWarning = now;
2041 }
2042 if (mStandby) {
2043 longStandbyExit = true;
2044 }
2045 }
2046 mStandby = false;
2047 } else {
2048 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002049 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002050 usleep(sleepTime);
2051 }
2052
2053 // finally let go of all our tracks, without the lock held
2054 // since we can't guarantee the destructors won't acquire that
2055 // same lock.
2056 tracksToRemove.clear();
2057
2058 // Effect chains will be actually deleted here if they were removed from
2059 // mEffectChains list during mixing or effects processing
2060 effectChains.clear();
2061 }
2062
2063 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002064 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 }
2066
Eric Laurentfeb0db62011-07-22 09:04:31 -07002067 releaseWakeLock();
2068
Steve Block3856b092011-10-20 11:56:00 +01002069 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002070 return false;
2071}
2072
2073// prepareTracks_l() must be called with ThreadBase::mLock held
2074uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2075{
2076
2077 uint32_t mixerStatus = MIXER_IDLE;
2078 // find out which tracks need to be processed
2079 size_t count = activeTracks.size();
2080 size_t mixedTracks = 0;
2081 size_t tracksWithEffect = 0;
2082
2083 float masterVolume = mMasterVolume;
2084 bool masterMute = mMasterMute;
2085
Eric Laurent571d49c2010-08-11 05:20:11 -07002086 if (masterMute) {
2087 masterVolume = 0;
2088 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002089 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002090 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002092 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002093 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 masterVolume = (float)((v + (1 << 23)) >> 24);
2095 chain.clear();
2096 }
2097
2098 for (size_t i=0 ; i<count ; i++) {
2099 sp<Track> t = activeTracks[i].promote();
2100 if (t == 0) continue;
2101
2102 Track* const track = t.get();
2103 audio_track_cblk_t* cblk = track->cblk();
2104
2105 // The first time a track is added we wait
2106 // for all its buffers to be filled before processing it
2107 mAudioMixer->setActiveTrack(track->name());
Eric Laurenta47b69c2011-11-08 18:10:16 -08002108 // make sure that we have enough frames to mix one full buffer.
2109 // enforce this condition only once to enable draining the buffer in case the client
2110 // app does not call stop() and relies on underrun to stop:
2111 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2112 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002113 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002114 if (!track->isStopped() && !track->isPausing() &&
2115 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002116 if (t->sampleRate() == (int)mSampleRate) {
2117 minFrames = mFrameCount;
2118 } else {
2119 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2120 }
2121 }
2122 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123 !track->isPaused() && !track->isTerminated())
2124 {
Steve Block3856b092011-10-20 11:56:00 +01002125 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126
2127 mixedTracks++;
2128
2129 // track->mainBuffer() != mMixBuffer means there is an effect chain
2130 // connected to the track
2131 chain.clear();
2132 if (track->mainBuffer() != mMixBuffer) {
2133 chain = getEffectChain_l(track->sessionId());
2134 // Delegate volume control to effect in track effect chain if needed
2135 if (chain != 0) {
2136 tracksWithEffect++;
2137 } else {
2138 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2139 track->name(), track->sessionId());
2140 }
2141 }
2142
2143
2144 int param = AudioMixer::VOLUME;
2145 if (track->mFillingUpStatus == Track::FS_FILLED) {
2146 // no ramp for the first volume setting
2147 track->mFillingUpStatus = Track::FS_ACTIVE;
2148 if (track->mState == TrackBase::RESUMING) {
2149 track->mState = TrackBase::ACTIVE;
2150 param = AudioMixer::RAMP_VOLUME;
2151 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002152 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002153 } else if (cblk->server != 0) {
2154 // If the track is stopped before the first frame was mixed,
2155 // do not apply ramp
2156 param = AudioMixer::RAMP_VOLUME;
2157 }
2158
2159 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002160 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002161 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002162 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002163 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 if (track->isPausing()) {
2165 track->setPaused();
2166 }
2167 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002168
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 // read original volumes with volume control
2170 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002172 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2173 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174
Eric Laurente0aed6d2010-09-10 17:44:44 -07002175 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002176 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002177 // Delegate volume control to effect in track effect chain if needed
2178 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2179 // Do not ramp volume if volume is controlled by effect
2180 param = AudioMixer::VOLUME;
2181 track->mHasVolumeController = true;
2182 } else {
2183 // force no volume ramp when volume controller was just disabled or removed
2184 // from effect chain to avoid volume spike
2185 if (track->mHasVolumeController) {
2186 param = AudioMixer::VOLUME;
2187 }
2188 track->mHasVolumeController = false;
2189 }
2190
2191 // Convert volumes from 8.24 to 4.12 format
2192 int16_t left, right, aux;
2193 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2194 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2195 left = int16_t(v_clamped);
2196 v_clamped = (vr + (1 << 11)) >> 12;
2197 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2198 right = int16_t(v_clamped);
2199
2200 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2201 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002202
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 // XXX: these things DON'T need to be done each time
2204 mAudioMixer->setBufferProvider(track);
2205 mAudioMixer->enable(AudioMixer::MIXING);
2206
2207 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2208 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2209 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2210 mAudioMixer->setParameter(
2211 AudioMixer::TRACK,
2212 AudioMixer::FORMAT, (void *)track->format());
2213 mAudioMixer->setParameter(
2214 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002215 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002216 mAudioMixer->setParameter(
2217 AudioMixer::RESAMPLE,
2218 AudioMixer::SAMPLE_RATE,
2219 (void *)(cblk->sampleRate));
2220 mAudioMixer->setParameter(
2221 AudioMixer::TRACK,
2222 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2223 mAudioMixer->setParameter(
2224 AudioMixer::TRACK,
2225 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2226
2227 // reset retry count
2228 track->mRetryCount = kMaxTrackRetries;
2229 mixerStatus = MIXER_TRACKS_READY;
2230 } else {
Steve Block3856b092011-10-20 11:56:00 +01002231 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 if (track->isStopped()) {
2233 track->reset();
2234 }
2235 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2236 // We have consumed all the buffers of this track.
2237 // Remove it from the list of active tracks.
2238 tracksToRemove->add(track);
2239 } else {
2240 // No buffers for this track. Give it a few chances to
2241 // fill a buffer, then remove it from active list.
2242 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002243 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002245 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002246 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002247 } else if (mixerStatus != MIXER_TRACKS_READY) {
2248 mixerStatus = MIXER_TRACKS_ENABLED;
2249 }
2250 }
2251 mAudioMixer->disable(AudioMixer::MIXING);
2252 }
2253 }
2254
2255 // remove all the tracks that need to be...
2256 count = tracksToRemove->size();
2257 if (UNLIKELY(count)) {
2258 for (size_t i=0 ; i<count ; i++) {
2259 const sp<Track>& track = tracksToRemove->itemAt(i);
2260 mActiveTracks.remove(track);
2261 if (track->mainBuffer() != mMixBuffer) {
2262 chain = getEffectChain_l(track->sessionId());
2263 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002264 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002265 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266 }
2267 }
2268 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002269 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002270 }
2271 }
2272 }
2273
2274 // mix buffer must be cleared if all tracks are connected to an
2275 // effect chain as in this case the mixer will not write to
2276 // mix buffer and track effects will accumulate into it
2277 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2278 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2279 }
2280
2281 return mixerStatus;
2282}
2283
2284void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2285{
Steve Block3856b092011-10-20 11:56:00 +01002286 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002287 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002289
Mathias Agopian65ab4712010-07-14 17:59:35 -07002290 size_t size = mTracks.size();
2291 for (size_t i = 0; i < size; i++) {
2292 sp<Track> t = mTracks[i];
2293 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002294 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 }
2297 }
2298}
2299
Eric Laurent9f6530f2011-08-30 10:18:54 -07002300void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2301{
Steve Block3856b092011-10-20 11:56:00 +01002302 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002303 this, streamType, valid);
2304 Mutex::Autolock _l(mLock);
2305
2306 mStreamTypes[streamType].valid = valid;
2307}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002308
2309// getTrackName_l() must be called with ThreadBase::mLock held
2310int AudioFlinger::MixerThread::getTrackName_l()
2311{
2312 return mAudioMixer->getTrackName();
2313}
2314
2315// deleteTrackName_l() must be called with ThreadBase::mLock held
2316void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2317{
Steve Block3856b092011-10-20 11:56:00 +01002318 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319 mAudioMixer->deleteTrackName(name);
2320}
2321
2322// checkForNewParameters_l() must be called with ThreadBase::mLock held
2323bool AudioFlinger::MixerThread::checkForNewParameters_l()
2324{
2325 bool reconfig = false;
2326
2327 while (!mNewParameters.isEmpty()) {
2328 status_t status = NO_ERROR;
2329 String8 keyValuePair = mNewParameters[0];
2330 AudioParameter param = AudioParameter(keyValuePair);
2331 int value;
2332
2333 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2334 reconfig = true;
2335 }
2336 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002337 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002338 status = BAD_VALUE;
2339 } else {
2340 reconfig = true;
2341 }
2342 }
2343 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002344 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345 status = BAD_VALUE;
2346 } else {
2347 reconfig = true;
2348 }
2349 }
2350 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2351 // do not accept frame count changes if tracks are open as the track buffer
2352 // size depends on frame count and correct behavior would not be garantied
2353 // if frame count is changed after track creation
2354 if (!mTracks.isEmpty()) {
2355 status = INVALID_OPERATION;
2356 } else {
2357 reconfig = true;
2358 }
2359 }
2360 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002361 // when changing the audio output device, call addBatteryData to notify
2362 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002363 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002364 uint32_t params = 0;
2365 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002366 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002367 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2368 }
2369
2370 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002371 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002372 // check if any other device (except speaker) is on
2373 if (value & deviceWithoutSpeaker ) {
2374 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2375 }
2376
2377 if (params != 0) {
2378 addBatteryData(params);
2379 }
2380 }
2381
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 // forward device change to effects that have requested to be
2383 // aware of attached audio device.
2384 mDevice = (uint32_t)value;
2385 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002386 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002387 }
2388 }
2389
2390 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002391 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002392 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002394 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 mStandby = true;
2396 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002397 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002398 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002399 }
2400 if (status == NO_ERROR && reconfig) {
2401 delete mAudioMixer;
2402 readOutputParameters();
2403 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2404 for (size_t i = 0; i < mTracks.size() ; i++) {
2405 int name = getTrackName_l();
2406 if (name < 0) break;
2407 mTracks[i]->mName = name;
2408 // limit track sample rate to 2 x new output sample rate
2409 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2410 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2411 }
2412 }
2413 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2414 }
2415 }
2416
2417 mNewParameters.removeAt(0);
2418
2419 mParamStatus = status;
2420 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002421 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2422 // already timed out waiting for the status and will never signal the condition.
2423 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002424 }
2425 return reconfig;
2426}
2427
2428status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2429{
2430 const size_t SIZE = 256;
2431 char buffer[SIZE];
2432 String8 result;
2433
2434 PlaybackThread::dumpInternals(fd, args);
2435
2436 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2437 result.append(buffer);
2438 write(fd, result.string(), result.size());
2439 return NO_ERROR;
2440}
2441
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2443{
Eric Laurent60e18242010-07-29 06:50:24 -07002444 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002445}
2446
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002447uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2448{
2449 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2450}
2451
Mathias Agopian65ab4712010-07-14 17:59:35 -07002452// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002453AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454 : PlaybackThread(audioFlinger, output, id, device)
2455{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002456 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002457}
2458
2459AudioFlinger::DirectOutputThread::~DirectOutputThread()
2460{
2461}
2462
2463
2464static inline int16_t clamp16(int32_t sample)
2465{
2466 if ((sample>>15) ^ (sample>>31))
2467 sample = 0x7FFF ^ (sample>>31);
2468 return sample;
2469}
2470
2471static inline
2472int32_t mul(int16_t in, int16_t v)
2473{
2474#if defined(__arm__) && !defined(__thumb__)
2475 int32_t out;
2476 asm( "smulbb %[out], %[in], %[v] \n"
2477 : [out]"=r"(out)
2478 : [in]"%r"(in), [v]"r"(v)
2479 : );
2480 return out;
2481#else
2482 return in * int32_t(v);
2483#endif
2484}
2485
2486void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2487{
2488 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002489 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 return;
2491 }
2492
2493 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002494 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 size_t count = mFrameCount * mChannelCount;
2496 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2497 int16_t *dst = mMixBuffer + count-1;
2498 while(count--) {
2499 *dst-- = (int16_t)(*src--^0x80) << 8;
2500 }
2501 }
2502
2503 size_t frameCount = mFrameCount;
2504 int16_t *out = mMixBuffer;
2505 if (ramp) {
2506 if (mChannelCount == 1) {
2507 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2508 int32_t vlInc = d / (int32_t)frameCount;
2509 int32_t vl = ((int32_t)mLeftVolShort << 16);
2510 do {
2511 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2512 out++;
2513 vl += vlInc;
2514 } while (--frameCount);
2515
2516 } else {
2517 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2518 int32_t vlInc = d / (int32_t)frameCount;
2519 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2520 int32_t vrInc = d / (int32_t)frameCount;
2521 int32_t vl = ((int32_t)mLeftVolShort << 16);
2522 int32_t vr = ((int32_t)mRightVolShort << 16);
2523 do {
2524 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2525 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2526 out += 2;
2527 vl += vlInc;
2528 vr += vrInc;
2529 } while (--frameCount);
2530 }
2531 } else {
2532 if (mChannelCount == 1) {
2533 do {
2534 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2535 out++;
2536 } while (--frameCount);
2537 } else {
2538 do {
2539 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2540 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2541 out += 2;
2542 } while (--frameCount);
2543 }
2544 }
2545
2546 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002547 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 size_t count = mFrameCount * mChannelCount;
2549 int16_t *src = mMixBuffer;
2550 uint8_t *dst = (uint8_t *)mMixBuffer;
2551 while(count--) {
2552 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2553 }
2554 }
2555
2556 mLeftVolShort = leftVol;
2557 mRightVolShort = rightVol;
2558}
2559
2560bool AudioFlinger::DirectOutputThread::threadLoop()
2561{
2562 uint32_t mixerStatus = MIXER_IDLE;
2563 sp<Track> trackToRemove;
2564 sp<Track> activeTrack;
2565 nsecs_t standbyTime = systemTime();
2566 int8_t *curBuf;
2567 size_t mixBufferSize = mFrameCount*mFrameSize;
2568 uint32_t activeSleepTime = activeSleepTimeUs();
2569 uint32_t idleSleepTime = idleSleepTimeUs();
2570 uint32_t sleepTime = idleSleepTime;
2571 // use shorter standby delay as on normal output to release
2572 // hardware resources as soon as possible
2573 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2574
Eric Laurentfeb0db62011-07-22 09:04:31 -07002575 acquireWakeLock();
2576
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 while (!exitPending())
2578 {
2579 bool rampVolume;
2580 uint16_t leftVol;
2581 uint16_t rightVol;
2582 Vector< sp<EffectChain> > effectChains;
2583
2584 processConfigEvents();
2585
2586 mixerStatus = MIXER_IDLE;
2587
2588 { // scope for the mLock
2589
2590 Mutex::Autolock _l(mLock);
2591
2592 if (checkForNewParameters_l()) {
2593 mixBufferSize = mFrameCount*mFrameSize;
2594 activeSleepTime = activeSleepTimeUs();
2595 idleSleepTime = idleSleepTimeUs();
2596 standbyDelay = microseconds(activeSleepTime*2);
2597 }
2598
2599 // put audio hardware into standby after short delay
2600 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2601 mSuspended) {
2602 // wait until we have something to do...
2603 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002604 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002605 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 mStandby = true;
2607 mBytesWritten = 0;
2608 }
2609
2610 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2611 // we're about to wait, flush the binder command buffer
2612 IPCThreadState::self()->flushCommands();
2613
2614 if (exitPending()) break;
2615
Eric Laurentfeb0db62011-07-22 09:04:31 -07002616 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002617 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002619 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002620 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621
2622 if (mMasterMute == false) {
2623 char value[PROPERTY_VALUE_MAX];
2624 property_get("ro.audio.silent", value, "0");
2625 if (atoi(value)) {
2626 LOGD("Silence is golden");
2627 setMasterMute(true);
2628 }
2629 }
2630
2631 standbyTime = systemTime() + standbyDelay;
2632 sleepTime = idleSleepTime;
2633 continue;
2634 }
2635 }
2636
2637 effectChains = mEffectChains;
2638
2639 // find out which tracks need to be processed
2640 if (mActiveTracks.size() != 0) {
2641 sp<Track> t = mActiveTracks[0].promote();
2642 if (t == 0) continue;
2643
2644 Track* const track = t.get();
2645 audio_track_cblk_t* cblk = track->cblk();
2646
2647 // The first time a track is added we wait
2648 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002649 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 !track->isPaused() && !track->isTerminated())
2651 {
Steve Block3856b092011-10-20 11:56:00 +01002652 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653
2654 if (track->mFillingUpStatus == Track::FS_FILLED) {
2655 track->mFillingUpStatus = Track::FS_ACTIVE;
2656 mLeftVolFloat = mRightVolFloat = 0;
2657 mLeftVolShort = mRightVolShort = 0;
2658 if (track->mState == TrackBase::RESUMING) {
2659 track->mState = TrackBase::ACTIVE;
2660 rampVolume = true;
2661 }
2662 } else if (cblk->server != 0) {
2663 // If the track is stopped before the first frame was mixed,
2664 // do not apply ramp
2665 rampVolume = true;
2666 }
2667 // compute volume for this track
2668 float left, right;
2669 if (track->isMuted() || mMasterMute || track->isPausing() ||
2670 mStreamTypes[track->type()].mute) {
2671 left = right = 0;
2672 if (track->isPausing()) {
2673 track->setPaused();
2674 }
2675 } else {
2676 float typeVolume = mStreamTypes[track->type()].volume;
2677 float v = mMasterVolume * typeVolume;
2678 float v_clamped = v * cblk->volume[0];
2679 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2680 left = v_clamped/MAX_GAIN;
2681 v_clamped = v * cblk->volume[1];
2682 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2683 right = v_clamped/MAX_GAIN;
2684 }
2685
2686 if (left != mLeftVolFloat || right != mRightVolFloat) {
2687 mLeftVolFloat = left;
2688 mRightVolFloat = right;
2689
2690 // If audio HAL implements volume control,
2691 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002692 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 left = 1.0f;
2694 right = 1.0f;
2695 }
2696
2697 // Convert volumes from float to 8.24
2698 uint32_t vl = (uint32_t)(left * (1 << 24));
2699 uint32_t vr = (uint32_t)(right * (1 << 24));
2700
2701 // Delegate volume control to effect in track effect chain if needed
2702 // only one effect chain can be present on DirectOutputThread, so if
2703 // there is one, the track is connected to it
2704 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002705 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002706 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 rampVolume = false;
2708 }
2709 }
2710
2711 // Convert volumes from 8.24 to 4.12 format
2712 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2713 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2714 leftVol = (uint16_t)v_clamped;
2715 v_clamped = (vr + (1 << 11)) >> 12;
2716 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2717 rightVol = (uint16_t)v_clamped;
2718 } else {
2719 leftVol = mLeftVolShort;
2720 rightVol = mRightVolShort;
2721 rampVolume = false;
2722 }
2723
2724 // reset retry count
2725 track->mRetryCount = kMaxTrackRetriesDirect;
2726 activeTrack = t;
2727 mixerStatus = MIXER_TRACKS_READY;
2728 } else {
Steve Block3856b092011-10-20 11:56:00 +01002729 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 if (track->isStopped()) {
2731 track->reset();
2732 }
2733 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2734 // We have consumed all the buffers of this track.
2735 // Remove it from the list of active tracks.
2736 trackToRemove = track;
2737 } else {
2738 // No buffers for this track. Give it a few chances to
2739 // fill a buffer, then remove it from active list.
2740 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002741 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 trackToRemove = track;
2743 } else {
2744 mixerStatus = MIXER_TRACKS_ENABLED;
2745 }
2746 }
2747 }
2748 }
2749
2750 // remove all the tracks that need to be...
2751 if (UNLIKELY(trackToRemove != 0)) {
2752 mActiveTracks.remove(trackToRemove);
2753 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002754 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002755 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002756 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 }
2758 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002759 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 }
2761 }
2762
Eric Laurentde070132010-07-13 04:45:46 -07002763 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764 }
2765
2766 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2767 AudioBufferProvider::Buffer buffer;
2768 size_t frameCount = mFrameCount;
2769 curBuf = (int8_t *)mMixBuffer;
2770 // output audio to hardware
2771 while (frameCount) {
2772 buffer.frameCount = frameCount;
2773 activeTrack->getNextBuffer(&buffer);
2774 if (UNLIKELY(buffer.raw == 0)) {
2775 memset(curBuf, 0, frameCount * mFrameSize);
2776 break;
2777 }
2778 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2779 frameCount -= buffer.frameCount;
2780 curBuf += buffer.frameCount * mFrameSize;
2781 activeTrack->releaseBuffer(&buffer);
2782 }
2783 sleepTime = 0;
2784 standbyTime = systemTime() + standbyDelay;
2785 } else {
2786 if (sleepTime == 0) {
2787 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2788 sleepTime = activeSleepTime;
2789 } else {
2790 sleepTime = idleSleepTime;
2791 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002792 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2794 sleepTime = 0;
2795 }
2796 }
2797
2798 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002799 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 }
2801 // sleepTime == 0 means we must write to audio hardware
2802 if (sleepTime == 0) {
2803 if (mixerStatus == MIXER_TRACKS_READY) {
2804 applyVolume(leftVol, rightVol, rampVolume);
2805 }
2806 for (size_t i = 0; i < effectChains.size(); i ++) {
2807 effectChains[i]->process_l();
2808 }
Eric Laurentde070132010-07-13 04:45:46 -07002809 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810
2811 mLastWriteTime = systemTime();
2812 mInWrite = true;
2813 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002814 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2816 mNumWrites++;
2817 mInWrite = false;
2818 mStandby = false;
2819 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002820 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 usleep(sleepTime);
2822 }
2823
2824 // finally let go of removed track, without the lock held
2825 // since we can't guarantee the destructors won't acquire that
2826 // same lock.
2827 trackToRemove.clear();
2828 activeTrack.clear();
2829
2830 // Effect chains will be actually deleted here if they were removed from
2831 // mEffectChains list during mixing or effects processing
2832 effectChains.clear();
2833 }
2834
2835 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002836 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 }
2838
Eric Laurentfeb0db62011-07-22 09:04:31 -07002839 releaseWakeLock();
2840
Steve Block3856b092011-10-20 11:56:00 +01002841 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 return false;
2843}
2844
2845// getTrackName_l() must be called with ThreadBase::mLock held
2846int AudioFlinger::DirectOutputThread::getTrackName_l()
2847{
2848 return 0;
2849}
2850
2851// deleteTrackName_l() must be called with ThreadBase::mLock held
2852void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2853{
2854}
2855
2856// checkForNewParameters_l() must be called with ThreadBase::mLock held
2857bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2858{
2859 bool reconfig = false;
2860
2861 while (!mNewParameters.isEmpty()) {
2862 status_t status = NO_ERROR;
2863 String8 keyValuePair = mNewParameters[0];
2864 AudioParameter param = AudioParameter(keyValuePair);
2865 int value;
2866
2867 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2868 // do not accept frame count changes if tracks are open as the track buffer
2869 // size depends on frame count and correct behavior would not be garantied
2870 // if frame count is changed after track creation
2871 if (!mTracks.isEmpty()) {
2872 status = INVALID_OPERATION;
2873 } else {
2874 reconfig = true;
2875 }
2876 }
2877 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002878 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002879 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002881 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002882 mStandby = true;
2883 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002884 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002885 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 }
2887 if (status == NO_ERROR && reconfig) {
2888 readOutputParameters();
2889 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2890 }
2891 }
2892
2893 mNewParameters.removeAt(0);
2894
2895 mParamStatus = status;
2896 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002897 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2898 // already timed out waiting for the status and will never signal the condition.
2899 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 }
2901 return reconfig;
2902}
2903
2904uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2905{
2906 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002907 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002908 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 } else {
2910 time = 10000;
2911 }
2912 return time;
2913}
2914
2915uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2916{
2917 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002918 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002919 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 } else {
2921 time = 10000;
2922 }
2923 return time;
2924}
2925
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002926uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2927{
2928 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002929 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002930 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2931 } else {
2932 time = 10000;
2933 }
2934 return time;
2935}
2936
2937
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938// ----------------------------------------------------------------------------
2939
2940AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2941 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2942{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002943 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 addOutputTrack(mainThread);
2945}
2946
2947AudioFlinger::DuplicatingThread::~DuplicatingThread()
2948{
2949 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2950 mOutputTracks[i]->destroy();
2951 }
2952 mOutputTracks.clear();
2953}
2954
2955bool AudioFlinger::DuplicatingThread::threadLoop()
2956{
2957 Vector< sp<Track> > tracksToRemove;
2958 uint32_t mixerStatus = MIXER_IDLE;
2959 nsecs_t standbyTime = systemTime();
2960 size_t mixBufferSize = mFrameCount*mFrameSize;
2961 SortedVector< sp<OutputTrack> > outputTracks;
2962 uint32_t writeFrames = 0;
2963 uint32_t activeSleepTime = activeSleepTimeUs();
2964 uint32_t idleSleepTime = idleSleepTimeUs();
2965 uint32_t sleepTime = idleSleepTime;
2966 Vector< sp<EffectChain> > effectChains;
2967
Eric Laurentfeb0db62011-07-22 09:04:31 -07002968 acquireWakeLock();
2969
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 while (!exitPending())
2971 {
2972 processConfigEvents();
2973
2974 mixerStatus = MIXER_IDLE;
2975 { // scope for the mLock
2976
2977 Mutex::Autolock _l(mLock);
2978
2979 if (checkForNewParameters_l()) {
2980 mixBufferSize = mFrameCount*mFrameSize;
2981 updateWaitTime();
2982 activeSleepTime = activeSleepTimeUs();
2983 idleSleepTime = idleSleepTimeUs();
2984 }
2985
2986 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2987
2988 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2989 outputTracks.add(mOutputTracks[i]);
2990 }
2991
2992 // put audio hardware into standby after short delay
2993 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2994 mSuspended) {
2995 if (!mStandby) {
2996 for (size_t i = 0; i < outputTracks.size(); i++) {
2997 outputTracks[i]->stop();
2998 }
2999 mStandby = true;
3000 mBytesWritten = 0;
3001 }
3002
3003 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3004 // we're about to wait, flush the binder command buffer
3005 IPCThreadState::self()->flushCommands();
3006 outputTracks.clear();
3007
3008 if (exitPending()) break;
3009
Eric Laurentfeb0db62011-07-22 09:04:31 -07003010 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003011 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003013 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003014 acquireWakeLock_l();
3015
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016 if (mMasterMute == false) {
3017 char value[PROPERTY_VALUE_MAX];
3018 property_get("ro.audio.silent", value, "0");
3019 if (atoi(value)) {
3020 LOGD("Silence is golden");
3021 setMasterMute(true);
3022 }
3023 }
3024
3025 standbyTime = systemTime() + kStandbyTimeInNsecs;
3026 sleepTime = idleSleepTime;
3027 continue;
3028 }
3029 }
3030
3031 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3032
3033 // prevent any changes in effect chain list and in each effect chain
3034 // during mixing and effect process as the audio buffers could be deleted
3035 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003036 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 }
3038
3039 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3040 // mix buffers...
3041 if (outputsReady(outputTracks)) {
3042 mAudioMixer->process();
3043 } else {
3044 memset(mMixBuffer, 0, mixBufferSize);
3045 }
3046 sleepTime = 0;
3047 writeFrames = mFrameCount;
3048 } else {
3049 if (sleepTime == 0) {
3050 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3051 sleepTime = activeSleepTime;
3052 } else {
3053 sleepTime = idleSleepTime;
3054 }
3055 } else if (mBytesWritten != 0) {
3056 // flush remaining overflow buffers in output tracks
3057 for (size_t i = 0; i < outputTracks.size(); i++) {
3058 if (outputTracks[i]->isActive()) {
3059 sleepTime = 0;
3060 writeFrames = 0;
3061 memset(mMixBuffer, 0, mixBufferSize);
3062 break;
3063 }
3064 }
3065 }
3066 }
3067
3068 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003069 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 }
3071 // sleepTime == 0 means we must write to audio hardware
3072 if (sleepTime == 0) {
3073 for (size_t i = 0; i < effectChains.size(); i ++) {
3074 effectChains[i]->process_l();
3075 }
3076 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003077 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078
3079 standbyTime = systemTime() + kStandbyTimeInNsecs;
3080 for (size_t i = 0; i < outputTracks.size(); i++) {
3081 outputTracks[i]->write(mMixBuffer, writeFrames);
3082 }
3083 mStandby = false;
3084 mBytesWritten += mixBufferSize;
3085 } else {
3086 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003087 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 usleep(sleepTime);
3089 }
3090
3091 // finally let go of all our tracks, without the lock held
3092 // since we can't guarantee the destructors won't acquire that
3093 // same lock.
3094 tracksToRemove.clear();
3095 outputTracks.clear();
3096
3097 // Effect chains will be actually deleted here if they were removed from
3098 // mEffectChains list during mixing or effects processing
3099 effectChains.clear();
3100 }
3101
Eric Laurentfeb0db62011-07-22 09:04:31 -07003102 releaseWakeLock();
3103
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 return false;
3105}
3106
3107void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3108{
3109 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3110 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3111 this,
3112 mSampleRate,
3113 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003114 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 frameCount);
3116 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003117 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003119 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 updateWaitTime();
3121 }
3122}
3123
3124void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3125{
3126 Mutex::Autolock _l(mLock);
3127 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3128 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3129 mOutputTracks[i]->destroy();
3130 mOutputTracks.removeAt(i);
3131 updateWaitTime();
3132 return;
3133 }
3134 }
Steve Block3856b092011-10-20 11:56:00 +01003135 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136}
3137
3138void AudioFlinger::DuplicatingThread::updateWaitTime()
3139{
3140 mWaitTimeMs = UINT_MAX;
3141 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3142 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3143 if (strong != NULL) {
3144 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3145 if (waitTimeMs < mWaitTimeMs) {
3146 mWaitTimeMs = waitTimeMs;
3147 }
3148 }
3149 }
3150}
3151
3152
3153bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3154{
3155 for (size_t i = 0; i < outputTracks.size(); i++) {
3156 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3157 if (thread == 0) {
3158 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3159 return false;
3160 }
3161 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3162 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003163 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 return false;
3165 }
3166 }
3167 return true;
3168}
3169
3170uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3171{
3172 return (mWaitTimeMs * 1000) / 2;
3173}
3174
3175// ----------------------------------------------------------------------------
3176
3177// TrackBase constructor must be called with AudioFlinger::mLock held
3178AudioFlinger::ThreadBase::TrackBase::TrackBase(
3179 const wp<ThreadBase>& thread,
3180 const sp<Client>& client,
3181 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003182 uint32_t format,
3183 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 int frameCount,
3185 uint32_t flags,
3186 const sp<IMemory>& sharedBuffer,
3187 int sessionId)
3188 : RefBase(),
3189 mThread(thread),
3190 mClient(client),
3191 mCblk(0),
3192 mFrameCount(0),
3193 mState(IDLE),
3194 mClientTid(-1),
3195 mFormat(format),
3196 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3197 mSessionId(sessionId)
3198{
Steve Block3856b092011-10-20 11:56:00 +01003199 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200
3201 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3202 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003203 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3205 if (sharedBuffer == 0) {
3206 size += bufferSize;
3207 }
3208
3209 if (client != NULL) {
3210 mCblkMemory = client->heap()->allocate(size);
3211 if (mCblkMemory != 0) {
3212 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3213 if (mCblk) { // construct the shared structure in-place.
3214 new(mCblk) audio_track_cblk_t();
3215 // clear all buffers
3216 mCblk->frameCount = frameCount;
3217 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003218 mChannelCount = channelCount;
3219 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 if (sharedBuffer == 0) {
3221 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3222 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3223 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003224 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 mCblk->flags = CBLK_UNDERRUN_ON;
3226 } else {
3227 mBuffer = sharedBuffer->pointer();
3228 }
3229 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3230 }
3231 } else {
3232 LOGE("not enough memory for AudioTrack size=%u", size);
3233 client->heap()->dump("AudioTrack");
3234 return;
3235 }
3236 } else {
3237 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3238 if (mCblk) { // construct the shared structure in-place.
3239 new(mCblk) audio_track_cblk_t();
3240 // clear all buffers
3241 mCblk->frameCount = frameCount;
3242 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003243 mChannelCount = channelCount;
3244 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3246 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3247 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003248 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mCblk->flags = CBLK_UNDERRUN_ON;
3250 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3251 }
3252 }
3253}
3254
3255AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3256{
3257 if (mCblk) {
3258 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3259 if (mClient == NULL) {
3260 delete mCblk;
3261 }
3262 }
3263 mCblkMemory.clear(); // and free the shared memory
3264 if (mClient != NULL) {
3265 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3266 mClient.clear();
3267 }
3268}
3269
3270void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3271{
3272 buffer->raw = 0;
3273 mFrameCount = buffer->frameCount;
3274 step();
3275 buffer->frameCount = 0;
3276}
3277
3278bool AudioFlinger::ThreadBase::TrackBase::step() {
3279 bool result;
3280 audio_track_cblk_t* cblk = this->cblk();
3281
3282 result = cblk->stepServer(mFrameCount);
3283 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003284 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 mFlags |= STEPSERVER_FAILED;
3286 }
3287 return result;
3288}
3289
3290void AudioFlinger::ThreadBase::TrackBase::reset() {
3291 audio_track_cblk_t* cblk = this->cblk();
3292
3293 cblk->user = 0;
3294 cblk->server = 0;
3295 cblk->userBase = 0;
3296 cblk->serverBase = 0;
3297 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003298 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299}
3300
3301sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3302{
3303 return mCblkMemory;
3304}
3305
3306int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3307 return (int)mCblk->sampleRate;
3308}
3309
3310int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003311 return (const int)mChannelCount;
3312}
3313
3314uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3315 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316}
3317
3318void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3319 audio_track_cblk_t* cblk = this->cblk();
3320 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3321 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3322
3323 // Check validity of returned pointer in case the track control block would have been corrupted.
3324 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3325 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3326 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 -07003327 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003329 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 return 0;
3331 }
3332
3333 return bufferStart;
3334}
3335
3336// ----------------------------------------------------------------------------
3337
3338// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3339AudioFlinger::PlaybackThread::Track::Track(
3340 const wp<ThreadBase>& thread,
3341 const sp<Client>& client,
3342 int streamType,
3343 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003344 uint32_t format,
3345 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 int frameCount,
3347 const sp<IMemory>& sharedBuffer,
3348 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003349 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003350 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3351 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352{
3353 if (mCblk != NULL) {
3354 sp<ThreadBase> baseThread = thread.promote();
3355 if (baseThread != 0) {
3356 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3357 mName = playbackThread->getTrackName_l();
3358 mMainBuffer = playbackThread->mixBuffer();
3359 }
Steve Block3856b092011-10-20 11:56:00 +01003360 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 if (mName < 0) {
3362 LOGE("no more track names available");
3363 }
3364 mVolume[0] = 1.0f;
3365 mVolume[1] = 1.0f;
3366 mStreamType = streamType;
3367 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3368 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003369 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 }
3371}
3372
3373AudioFlinger::PlaybackThread::Track::~Track()
3374{
Steve Block3856b092011-10-20 11:56:00 +01003375 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 sp<ThreadBase> thread = mThread.promote();
3377 if (thread != 0) {
3378 Mutex::Autolock _l(thread->mLock);
3379 mState = TERMINATED;
3380 }
3381}
3382
3383void AudioFlinger::PlaybackThread::Track::destroy()
3384{
3385 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3386 // by removing it from mTracks vector, so there is a risk that this Tracks's
3387 // desctructor is called. As the destructor needs to lock mLock,
3388 // we must acquire a strong reference on this Track before locking mLock
3389 // here so that the destructor is called only when exiting this function.
3390 // On the other hand, as long as Track::destroy() is only called by
3391 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3392 // this Track with its member mTrack.
3393 sp<Track> keep(this);
3394 { // scope for mLock
3395 sp<ThreadBase> thread = mThread.promote();
3396 if (thread != 0) {
3397 if (!isOutputTrack()) {
3398 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003399 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003400 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003401 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003402
3403 // to track the speaker usage
3404 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 }
3406 AudioSystem::releaseOutput(thread->id());
3407 }
3408 Mutex::Autolock _l(thread->mLock);
3409 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3410 playbackThread->destroyTrack_l(this);
3411 }
3412 }
3413}
3414
3415void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3416{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003417 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 -07003418 mName - AudioMixer::TRACK0,
3419 (mClient == NULL) ? getpid() : mClient->pid(),
3420 mStreamType,
3421 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003422 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 mSessionId,
3424 mFrameCount,
3425 mState,
3426 mMute,
3427 mFillingUpStatus,
3428 mCblk->sampleRate,
3429 mCblk->volume[0],
3430 mCblk->volume[1],
3431 mCblk->server,
3432 mCblk->user,
3433 (int)mMainBuffer,
3434 (int)mAuxBuffer);
3435}
3436
3437status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3438{
3439 audio_track_cblk_t* cblk = this->cblk();
3440 uint32_t framesReady;
3441 uint32_t framesReq = buffer->frameCount;
3442
3443 // Check if last stepServer failed, try to step now
3444 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3445 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003446 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3448 }
3449
3450 framesReady = cblk->framesReady();
3451
3452 if (LIKELY(framesReady)) {
3453 uint32_t s = cblk->server;
3454 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3455
3456 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3457 if (framesReq > framesReady) {
3458 framesReq = framesReady;
3459 }
3460 if (s + framesReq > bufferEnd) {
3461 framesReq = bufferEnd - s;
3462 }
3463
3464 buffer->raw = getBuffer(s, framesReq);
3465 if (buffer->raw == 0) goto getNextBuffer_exit;
3466
3467 buffer->frameCount = framesReq;
3468 return NO_ERROR;
3469 }
3470
3471getNextBuffer_exit:
3472 buffer->raw = 0;
3473 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003474 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 return NOT_ENOUGH_DATA;
3476}
3477
3478bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003479 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480
3481 if (mCblk->framesReady() >= mCblk->frameCount ||
3482 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3483 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003484 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 return true;
3486 }
3487 return false;
3488}
3489
3490status_t AudioFlinger::PlaybackThread::Track::start()
3491{
3492 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003493 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003494 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 sp<ThreadBase> thread = mThread.promote();
3496 if (thread != 0) {
3497 Mutex::Autolock _l(thread->mLock);
3498 int state = mState;
3499 // here the track could be either new, or restarted
3500 // in both cases "unstop" the track
3501 if (mState == PAUSED) {
3502 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003503 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 } else {
3505 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003506 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 }
3508
3509 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3510 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003511 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003512 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003513 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003515
3516 // to track the speaker usage
3517 if (status == NO_ERROR) {
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 }
3521 if (status == NO_ERROR) {
3522 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3523 playbackThread->addTrack_l(this);
3524 } else {
3525 mState = state;
3526 }
3527 } else {
3528 status = BAD_VALUE;
3529 }
3530 return status;
3531}
3532
3533void AudioFlinger::PlaybackThread::Track::stop()
3534{
Steve Block3856b092011-10-20 11:56:00 +01003535 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 sp<ThreadBase> thread = mThread.promote();
3537 if (thread != 0) {
3538 Mutex::Autolock _l(thread->mLock);
3539 int state = mState;
3540 if (mState > STOPPED) {
3541 mState = STOPPED;
3542 // If the track is not active (PAUSED and buffers full), flush buffers
3543 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3544 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3545 reset();
3546 }
Steve Block3856b092011-10-20 11:56:00 +01003547 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 }
3549 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3550 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003551 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003552 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003553 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003555
3556 // to track the speaker usage
3557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 }
3559 }
3560}
3561
3562void AudioFlinger::PlaybackThread::Track::pause()
3563{
Steve Block3856b092011-10-20 11:56:00 +01003564 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 sp<ThreadBase> thread = mThread.promote();
3566 if (thread != 0) {
3567 Mutex::Autolock _l(thread->mLock);
3568 if (mState == ACTIVE || mState == RESUMING) {
3569 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003570 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 if (!isOutputTrack()) {
3572 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003573 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003574 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003575 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003577
3578 // to track the speaker usage
3579 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 }
3581 }
3582 }
3583}
3584
3585void AudioFlinger::PlaybackThread::Track::flush()
3586{
Steve Block3856b092011-10-20 11:56:00 +01003587 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 sp<ThreadBase> thread = mThread.promote();
3589 if (thread != 0) {
3590 Mutex::Autolock _l(thread->mLock);
3591 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3592 return;
3593 }
3594 // No point remaining in PAUSED state after a flush => go to
3595 // STOPPED state
3596 mState = STOPPED;
3597
Eric Laurent38ccae22011-03-28 18:37:07 -07003598 // do not reset the track if it is still in the process of being stopped or paused.
3599 // this will be done by prepareTracks_l() when the track is stopped.
3600 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3601 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3602 reset();
3603 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 }
3605}
3606
3607void AudioFlinger::PlaybackThread::Track::reset()
3608{
3609 // Do not reset twice to avoid discarding data written just after a flush and before
3610 // the audioflinger thread detects the track is stopped.
3611 if (!mResetDone) {
3612 TrackBase::reset();
3613 // Force underrun condition to avoid false underrun callback until first data is
3614 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003615 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3616 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 mFillingUpStatus = FS_FILLING;
3618 mResetDone = true;
3619 }
3620}
3621
3622void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3623{
3624 mMute = muted;
3625}
3626
3627void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3628{
3629 mVolume[0] = left;
3630 mVolume[1] = right;
3631}
3632
3633status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3634{
3635 status_t status = DEAD_OBJECT;
3636 sp<ThreadBase> thread = mThread.promote();
3637 if (thread != 0) {
3638 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3639 status = playbackThread->attachAuxEffect(this, EffectId);
3640 }
3641 return status;
3642}
3643
3644void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3645{
3646 mAuxEffectId = EffectId;
3647 mAuxBuffer = buffer;
3648}
3649
3650// ----------------------------------------------------------------------------
3651
3652// RecordTrack constructor must be called with AudioFlinger::mLock held
3653AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3654 const wp<ThreadBase>& thread,
3655 const sp<Client>& client,
3656 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003657 uint32_t format,
3658 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 int frameCount,
3660 uint32_t flags,
3661 int sessionId)
3662 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003663 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 mOverflow(false)
3665{
3666 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003667 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003668 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003669 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003670 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003671 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 } else {
3673 mCblk->frameSize = sizeof(int8_t);
3674 }
3675 }
3676}
3677
3678AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3679{
3680 sp<ThreadBase> thread = mThread.promote();
3681 if (thread != 0) {
3682 AudioSystem::releaseInput(thread->id());
3683 }
3684}
3685
3686status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3687{
3688 audio_track_cblk_t* cblk = this->cblk();
3689 uint32_t framesAvail;
3690 uint32_t framesReq = buffer->frameCount;
3691
3692 // Check if last stepServer failed, try to step now
3693 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3694 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003695 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3697 }
3698
3699 framesAvail = cblk->framesAvailable_l();
3700
3701 if (LIKELY(framesAvail)) {
3702 uint32_t s = cblk->server;
3703 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3704
3705 if (framesReq > framesAvail) {
3706 framesReq = framesAvail;
3707 }
3708 if (s + framesReq > bufferEnd) {
3709 framesReq = bufferEnd - s;
3710 }
3711
3712 buffer->raw = getBuffer(s, framesReq);
3713 if (buffer->raw == 0) goto getNextBuffer_exit;
3714
3715 buffer->frameCount = framesReq;
3716 return NO_ERROR;
3717 }
3718
3719getNextBuffer_exit:
3720 buffer->raw = 0;
3721 buffer->frameCount = 0;
3722 return NOT_ENOUGH_DATA;
3723}
3724
3725status_t AudioFlinger::RecordThread::RecordTrack::start()
3726{
3727 sp<ThreadBase> thread = mThread.promote();
3728 if (thread != 0) {
3729 RecordThread *recordThread = (RecordThread *)thread.get();
3730 return recordThread->start(this);
3731 } else {
3732 return BAD_VALUE;
3733 }
3734}
3735
3736void AudioFlinger::RecordThread::RecordTrack::stop()
3737{
3738 sp<ThreadBase> thread = mThread.promote();
3739 if (thread != 0) {
3740 RecordThread *recordThread = (RecordThread *)thread.get();
3741 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003742 TrackBase::reset();
3743 // Force overerrun condition to avoid false overrun callback until first data is
3744 // read from buffer
3745 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746 }
3747}
3748
3749void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3750{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003751 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 (mClient == NULL) ? getpid() : mClient->pid(),
3753 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003754 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 mSessionId,
3756 mFrameCount,
3757 mState,
3758 mCblk->sampleRate,
3759 mCblk->server,
3760 mCblk->user);
3761}
3762
3763
3764// ----------------------------------------------------------------------------
3765
3766AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3767 const wp<ThreadBase>& thread,
3768 DuplicatingThread *sourceThread,
3769 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003770 uint32_t format,
3771 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003773 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774 mActive(false), mSourceThread(sourceThread)
3775{
3776
3777 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3778 if (mCblk != NULL) {
3779 mCblk->flags |= CBLK_DIRECTION_OUT;
3780 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3781 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3782 mOutBuffer.frameCount = 0;
3783 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003784 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003785 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3786 mCblk, mBuffer, mCblk->buffers,
3787 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 } else {
3789 LOGW("Error creating output track on thread %p", playbackThread);
3790 }
3791}
3792
3793AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3794{
3795 clearBufferQueue();
3796}
3797
3798status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3799{
3800 status_t status = Track::start();
3801 if (status != NO_ERROR) {
3802 return status;
3803 }
3804
3805 mActive = true;
3806 mRetryCount = 127;
3807 return status;
3808}
3809
3810void AudioFlinger::PlaybackThread::OutputTrack::stop()
3811{
3812 Track::stop();
3813 clearBufferQueue();
3814 mOutBuffer.frameCount = 0;
3815 mActive = false;
3816}
3817
3818bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3819{
3820 Buffer *pInBuffer;
3821 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003822 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823 bool outputBufferFull = false;
3824 inBuffer.frameCount = frames;
3825 inBuffer.i16 = data;
3826
3827 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3828
3829 if (!mActive && frames != 0) {
3830 start();
3831 sp<ThreadBase> thread = mThread.promote();
3832 if (thread != 0) {
3833 MixerThread *mixerThread = (MixerThread *)thread.get();
3834 if (mCblk->frameCount > frames){
3835 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3836 uint32_t startFrames = (mCblk->frameCount - frames);
3837 pInBuffer = new Buffer;
3838 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3839 pInBuffer->frameCount = startFrames;
3840 pInBuffer->i16 = pInBuffer->mBuffer;
3841 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3842 mBufferQueue.add(pInBuffer);
3843 } else {
3844 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3845 }
3846 }
3847 }
3848 }
3849
3850 while (waitTimeLeftMs) {
3851 // First write pending buffers, then new data
3852 if (mBufferQueue.size()) {
3853 pInBuffer = mBufferQueue.itemAt(0);
3854 } else {
3855 pInBuffer = &inBuffer;
3856 }
3857
3858 if (pInBuffer->frameCount == 0) {
3859 break;
3860 }
3861
3862 if (mOutBuffer.frameCount == 0) {
3863 mOutBuffer.frameCount = pInBuffer->frameCount;
3864 nsecs_t startTime = systemTime();
3865 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003866 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867 outputBufferFull = true;
3868 break;
3869 }
3870 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3871 if (waitTimeLeftMs >= waitTimeMs) {
3872 waitTimeLeftMs -= waitTimeMs;
3873 } else {
3874 waitTimeLeftMs = 0;
3875 }
3876 }
3877
3878 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3879 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3880 mCblk->stepUser(outFrames);
3881 pInBuffer->frameCount -= outFrames;
3882 pInBuffer->i16 += outFrames * channelCount;
3883 mOutBuffer.frameCount -= outFrames;
3884 mOutBuffer.i16 += outFrames * channelCount;
3885
3886 if (pInBuffer->frameCount == 0) {
3887 if (mBufferQueue.size()) {
3888 mBufferQueue.removeAt(0);
3889 delete [] pInBuffer->mBuffer;
3890 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003891 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 } else {
3893 break;
3894 }
3895 }
3896 }
3897
3898 // If we could not write all frames, allocate a buffer and queue it for next time.
3899 if (inBuffer.frameCount) {
3900 sp<ThreadBase> thread = mThread.promote();
3901 if (thread != 0 && !thread->standby()) {
3902 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3903 pInBuffer = new Buffer;
3904 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3905 pInBuffer->frameCount = inBuffer.frameCount;
3906 pInBuffer->i16 = pInBuffer->mBuffer;
3907 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3908 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003909 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910 } else {
3911 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3912 }
3913 }
3914 }
3915
3916 // Calling write() with a 0 length buffer, means that no more data will be written:
3917 // If no more buffers are pending, fill output track buffer to make sure it is started
3918 // by output mixer.
3919 if (frames == 0 && mBufferQueue.size() == 0) {
3920 if (mCblk->user < mCblk->frameCount) {
3921 frames = mCblk->frameCount - mCblk->user;
3922 pInBuffer = new Buffer;
3923 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3924 pInBuffer->frameCount = frames;
3925 pInBuffer->i16 = pInBuffer->mBuffer;
3926 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3927 mBufferQueue.add(pInBuffer);
3928 } else if (mActive) {
3929 stop();
3930 }
3931 }
3932
3933 return outputBufferFull;
3934}
3935
3936status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3937{
3938 int active;
3939 status_t result;
3940 audio_track_cblk_t* cblk = mCblk;
3941 uint32_t framesReq = buffer->frameCount;
3942
Steve Block3856b092011-10-20 11:56:00 +01003943// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 buffer->frameCount = 0;
3945
3946 uint32_t framesAvail = cblk->framesAvailable();
3947
3948
3949 if (framesAvail == 0) {
3950 Mutex::Autolock _l(cblk->lock);
3951 goto start_loop_here;
3952 while (framesAvail == 0) {
3953 active = mActive;
3954 if (UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003955 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 return AudioTrack::NO_MORE_BUFFERS;
3957 }
3958 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3959 if (result != NO_ERROR) {
3960 return AudioTrack::NO_MORE_BUFFERS;
3961 }
3962 // read the server count again
3963 start_loop_here:
3964 framesAvail = cblk->framesAvailable_l();
3965 }
3966 }
3967
3968// if (framesAvail < framesReq) {
3969// return AudioTrack::NO_MORE_BUFFERS;
3970// }
3971
3972 if (framesReq > framesAvail) {
3973 framesReq = framesAvail;
3974 }
3975
3976 uint32_t u = cblk->user;
3977 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3978
3979 if (u + framesReq > bufferEnd) {
3980 framesReq = bufferEnd - u;
3981 }
3982
3983 buffer->frameCount = framesReq;
3984 buffer->raw = (void *)cblk->buffer(u);
3985 return NO_ERROR;
3986}
3987
3988
3989void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3990{
3991 size_t size = mBufferQueue.size();
3992 Buffer *pBuffer;
3993
3994 for (size_t i = 0; i < size; i++) {
3995 pBuffer = mBufferQueue.itemAt(i);
3996 delete [] pBuffer->mBuffer;
3997 delete pBuffer;
3998 }
3999 mBufferQueue.clear();
4000}
4001
4002// ----------------------------------------------------------------------------
4003
4004AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4005 : RefBase(),
4006 mAudioFlinger(audioFlinger),
4007 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4008 mPid(pid)
4009{
4010 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4011}
4012
4013// Client destructor must be called with AudioFlinger::mLock held
4014AudioFlinger::Client::~Client()
4015{
4016 mAudioFlinger->removeClient_l(mPid);
4017}
4018
4019const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4020{
4021 return mMemoryDealer;
4022}
4023
4024// ----------------------------------------------------------------------------
4025
4026AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4027 const sp<IAudioFlingerClient>& client,
4028 pid_t pid)
4029 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4030{
4031}
4032
4033AudioFlinger::NotificationClient::~NotificationClient()
4034{
4035 mClient.clear();
4036}
4037
4038void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4039{
4040 sp<NotificationClient> keep(this);
4041 {
4042 mAudioFlinger->removeNotificationClient(mPid);
4043 }
4044}
4045
4046// ----------------------------------------------------------------------------
4047
4048AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4049 : BnAudioTrack(),
4050 mTrack(track)
4051{
4052}
4053
4054AudioFlinger::TrackHandle::~TrackHandle() {
4055 // just stop the track on deletion, associated resources
4056 // will be freed from the main thread once all pending buffers have
4057 // been played. Unless it's not in the active track list, in which
4058 // case we free everything now...
4059 mTrack->destroy();
4060}
4061
4062status_t AudioFlinger::TrackHandle::start() {
4063 return mTrack->start();
4064}
4065
4066void AudioFlinger::TrackHandle::stop() {
4067 mTrack->stop();
4068}
4069
4070void AudioFlinger::TrackHandle::flush() {
4071 mTrack->flush();
4072}
4073
4074void AudioFlinger::TrackHandle::mute(bool e) {
4075 mTrack->mute(e);
4076}
4077
4078void AudioFlinger::TrackHandle::pause() {
4079 mTrack->pause();
4080}
4081
4082void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4083 mTrack->setVolume(left, right);
4084}
4085
4086sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4087 return mTrack->getCblk();
4088}
4089
4090status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4091{
4092 return mTrack->attachAuxEffect(EffectId);
4093}
4094
4095status_t AudioFlinger::TrackHandle::onTransact(
4096 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4097{
4098 return BnAudioTrack::onTransact(code, data, reply, flags);
4099}
4100
4101// ----------------------------------------------------------------------------
4102
4103sp<IAudioRecord> AudioFlinger::openRecord(
4104 pid_t pid,
4105 int input,
4106 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004107 uint32_t format,
4108 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 int frameCount,
4110 uint32_t flags,
4111 int *sessionId,
4112 status_t *status)
4113{
4114 sp<RecordThread::RecordTrack> recordTrack;
4115 sp<RecordHandle> recordHandle;
4116 sp<Client> client;
4117 wp<Client> wclient;
4118 status_t lStatus;
4119 RecordThread *thread;
4120 size_t inFrameCount;
4121 int lSessionId;
4122
4123 // check calling permissions
4124 if (!recordingAllowed()) {
4125 lStatus = PERMISSION_DENIED;
4126 goto Exit;
4127 }
4128
4129 // add client to list
4130 { // scope for mLock
4131 Mutex::Autolock _l(mLock);
4132 thread = checkRecordThread_l(input);
4133 if (thread == NULL) {
4134 lStatus = BAD_VALUE;
4135 goto Exit;
4136 }
4137
4138 wclient = mClients.valueFor(pid);
4139 if (wclient != NULL) {
4140 client = wclient.promote();
4141 } else {
4142 client = new Client(this, pid);
4143 mClients.add(pid, client);
4144 }
4145
4146 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004147 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 lSessionId = *sessionId;
4149 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004150 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 if (sessionId != NULL) {
4152 *sessionId = lSessionId;
4153 }
4154 }
4155 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004156 recordTrack = thread->createRecordTrack_l(client,
4157 sampleRate,
4158 format,
4159 channelMask,
4160 frameCount,
4161 flags,
4162 lSessionId,
4163 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004165 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4167 // destructor is called by the TrackBase destructor with mLock held
4168 client.clear();
4169 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 goto Exit;
4171 }
4172
4173 // return to handle to client
4174 recordHandle = new RecordHandle(recordTrack);
4175 lStatus = NO_ERROR;
4176
4177Exit:
4178 if (status) {
4179 *status = lStatus;
4180 }
4181 return recordHandle;
4182}
4183
4184// ----------------------------------------------------------------------------
4185
4186AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4187 : BnAudioRecord(),
4188 mRecordTrack(recordTrack)
4189{
4190}
4191
4192AudioFlinger::RecordHandle::~RecordHandle() {
4193 stop();
4194}
4195
4196status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004197 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 return mRecordTrack->start();
4199}
4200
4201void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004202 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 mRecordTrack->stop();
4204}
4205
4206sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4207 return mRecordTrack->getCblk();
4208}
4209
4210status_t AudioFlinger::RecordHandle::onTransact(
4211 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4212{
4213 return BnAudioRecord::onTransact(code, data, reply, flags);
4214}
4215
4216// ----------------------------------------------------------------------------
4217
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004218AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4219 AudioStreamIn *input,
4220 uint32_t sampleRate,
4221 uint32_t channels,
4222 int id,
4223 uint32_t device) :
4224 ThreadBase(audioFlinger, id, device),
4225 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004227 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004228
4229 snprintf(mName, kNameLength, "AudioIn_%d", id);
4230
Dima Zavinfce7a472011-04-19 22:30:36 -07004231 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 mReqSampleRate = sampleRate;
4233 readInputParameters();
4234}
4235
4236
4237AudioFlinger::RecordThread::~RecordThread()
4238{
4239 delete[] mRsmpInBuffer;
4240 if (mResampler != 0) {
4241 delete mResampler;
4242 delete[] mRsmpOutBuffer;
4243 }
4244}
4245
4246void AudioFlinger::RecordThread::onFirstRef()
4247{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004248 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249}
4250
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004251status_t AudioFlinger::RecordThread::readyToRun()
4252{
4253 status_t status = initCheck();
4254 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4255 return status;
4256}
4257
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258bool AudioFlinger::RecordThread::threadLoop()
4259{
4260 AudioBufferProvider::Buffer buffer;
4261 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004262 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263
Eric Laurent44d98482010-09-30 16:12:31 -07004264 nsecs_t lastWarning = 0;
4265
Eric Laurentfeb0db62011-07-22 09:04:31 -07004266 acquireWakeLock();
4267
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 // start recording
4269 while (!exitPending()) {
4270
4271 processConfigEvents();
4272
4273 { // scope for mLock
4274 Mutex::Autolock _l(mLock);
4275 checkForNewParameters_l();
4276 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4277 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004278 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 mStandby = true;
4280 }
4281
4282 if (exitPending()) break;
4283
Eric Laurentfeb0db62011-07-22 09:04:31 -07004284 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004285 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 // go to sleep
4287 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004288 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004289 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 continue;
4291 }
4292 if (mActiveTrack != 0) {
4293 if (mActiveTrack->mState == TrackBase::PAUSING) {
4294 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004295 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 mStandby = true;
4297 }
4298 mActiveTrack.clear();
4299 mStartStopCond.broadcast();
4300 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4301 if (mReqChannelCount != mActiveTrack->channelCount()) {
4302 mActiveTrack.clear();
4303 mStartStopCond.broadcast();
4304 } else if (mBytesRead != 0) {
4305 // record start succeeds only if first read from audio input
4306 // succeeds
4307 if (mBytesRead > 0) {
4308 mActiveTrack->mState = TrackBase::ACTIVE;
4309 } else {
4310 mActiveTrack.clear();
4311 }
4312 mStartStopCond.broadcast();
4313 }
4314 mStandby = false;
4315 }
4316 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004317 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318 }
4319
4320 if (mActiveTrack != 0) {
4321 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4322 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004323 unlockEffectChains(effectChains);
4324 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 continue;
4326 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004327 for (size_t i = 0; i < effectChains.size(); i ++) {
4328 effectChains[i]->process_l();
4329 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004330
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 buffer.frameCount = mFrameCount;
4332 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4333 size_t framesOut = buffer.frameCount;
4334 if (mResampler == 0) {
4335 // no resampling
4336 while (framesOut) {
4337 size_t framesIn = mFrameCount - mRsmpInIndex;
4338 if (framesIn) {
4339 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4340 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4341 if (framesIn > framesOut)
4342 framesIn = framesOut;
4343 mRsmpInIndex += framesIn;
4344 framesOut -= framesIn;
4345 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004346 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 memcpy(dst, src, framesIn * mFrameSize);
4348 } else {
4349 int16_t *src16 = (int16_t *)src;
4350 int16_t *dst16 = (int16_t *)dst;
4351 if (mChannelCount == 1) {
4352 while (framesIn--) {
4353 *dst16++ = *src16;
4354 *dst16++ = *src16++;
4355 }
4356 } else {
4357 while (framesIn--) {
4358 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4359 src16 += 2;
4360 }
4361 }
4362 }
4363 }
4364 if (framesOut && mFrameCount == mRsmpInIndex) {
4365 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004366 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004367 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 framesOut = 0;
4369 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004370 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 mRsmpInIndex = 0;
4372 }
4373 if (mBytesRead < 0) {
4374 LOGE("Error reading audio input");
4375 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4376 // Force input into standby so that it tries to
4377 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004378 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004379 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 }
4381 mRsmpInIndex = mFrameCount;
4382 framesOut = 0;
4383 buffer.frameCount = 0;
4384 }
4385 }
4386 }
4387 } else {
4388 // resampling
4389
4390 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4391 // alter output frame count as if we were expecting stereo samples
4392 if (mChannelCount == 1 && mReqChannelCount == 1) {
4393 framesOut >>= 1;
4394 }
4395 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4396 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4397 // are 32 bit aligned which should be always true.
4398 if (mChannelCount == 2 && mReqChannelCount == 1) {
4399 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4400 // the resampler always outputs stereo samples: do post stereo to mono conversion
4401 int16_t *src = (int16_t *)mRsmpOutBuffer;
4402 int16_t *dst = buffer.i16;
4403 while (framesOut--) {
4404 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4405 src += 2;
4406 }
4407 } else {
4408 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4409 }
4410
4411 }
4412 mActiveTrack->releaseBuffer(&buffer);
4413 mActiveTrack->overflow();
4414 }
4415 // client isn't retrieving buffers fast enough
4416 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004417 if (!mActiveTrack->setOverflow()) {
4418 nsecs_t now = systemTime();
4419 if ((now - lastWarning) > kWarningThrottle) {
4420 LOGW("RecordThread: buffer overflow");
4421 lastWarning = now;
4422 }
4423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 // Release the processor for a while before asking for a new buffer.
4425 // This will give the application more chance to read from the buffer and
4426 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004427 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 }
4429 }
Eric Laurentec437d82011-07-26 20:54:46 -07004430 // enable changes in effect chain
4431 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004432 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 }
4434
4435 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004436 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 }
4438 mActiveTrack.clear();
4439
4440 mStartStopCond.broadcast();
4441
Eric Laurentfeb0db62011-07-22 09:04:31 -07004442 releaseWakeLock();
4443
Steve Block3856b092011-10-20 11:56:00 +01004444 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 return false;
4446}
4447
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004448
4449sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4450 const sp<AudioFlinger::Client>& client,
4451 uint32_t sampleRate,
4452 int format,
4453 int channelMask,
4454 int frameCount,
4455 uint32_t flags,
4456 int sessionId,
4457 status_t *status)
4458{
4459 sp<RecordTrack> track;
4460 status_t lStatus;
4461
4462 lStatus = initCheck();
4463 if (lStatus != NO_ERROR) {
4464 LOGE("Audio driver not initialized.");
4465 goto Exit;
4466 }
4467
4468 { // scope for mLock
4469 Mutex::Autolock _l(mLock);
4470
4471 track = new RecordTrack(this, client, sampleRate,
4472 format, channelMask, frameCount, flags, sessionId);
4473
4474 if (track->getCblk() == NULL) {
4475 lStatus = NO_MEMORY;
4476 goto Exit;
4477 }
4478
4479 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004480 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4481 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004482 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004483 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4484 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004485 }
4486 lStatus = NO_ERROR;
4487
4488Exit:
4489 if (status) {
4490 *status = lStatus;
4491 }
4492 return track;
4493}
4494
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4496{
Steve Block3856b092011-10-20 11:56:00 +01004497 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 sp <ThreadBase> strongMe = this;
4499 status_t status = NO_ERROR;
4500 {
4501 AutoMutex lock(&mLock);
4502 if (mActiveTrack != 0) {
4503 if (recordTrack != mActiveTrack.get()) {
4504 status = -EBUSY;
4505 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4506 mActiveTrack->mState = TrackBase::ACTIVE;
4507 }
4508 return status;
4509 }
4510
4511 recordTrack->mState = TrackBase::IDLE;
4512 mActiveTrack = recordTrack;
4513 mLock.unlock();
4514 status_t status = AudioSystem::startInput(mId);
4515 mLock.lock();
4516 if (status != NO_ERROR) {
4517 mActiveTrack.clear();
4518 return status;
4519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 mRsmpInIndex = mFrameCount;
4521 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004522 if (mResampler != NULL) {
4523 mResampler->reset();
4524 }
4525 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004527 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 mWaitWorkCV.signal();
4529 // do not wait for mStartStopCond if exiting
4530 if (mExiting) {
4531 mActiveTrack.clear();
4532 status = INVALID_OPERATION;
4533 goto startError;
4534 }
4535 mStartStopCond.wait(mLock);
4536 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004537 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 status = BAD_VALUE;
4539 goto startError;
4540 }
Steve Block3856b092011-10-20 11:56:00 +01004541 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 return status;
4543 }
4544startError:
4545 AudioSystem::stopInput(mId);
4546 return status;
4547}
4548
4549void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 sp <ThreadBase> strongMe = this;
4552 {
4553 AutoMutex lock(&mLock);
4554 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4555 mActiveTrack->mState = TrackBase::PAUSING;
4556 // do not wait for mStartStopCond if exiting
4557 if (mExiting) {
4558 return;
4559 }
4560 mStartStopCond.wait(mLock);
4561 // if we have been restarted, recordTrack == mActiveTrack.get() here
4562 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4563 mLock.unlock();
4564 AudioSystem::stopInput(mId);
4565 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004566 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 }
4568 }
4569 }
4570}
4571
4572status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4573{
4574 const size_t SIZE = 256;
4575 char buffer[SIZE];
4576 String8 result;
4577 pid_t pid = 0;
4578
4579 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4580 result.append(buffer);
4581
4582 if (mActiveTrack != 0) {
4583 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004584 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 mActiveTrack->dump(buffer, SIZE);
4586 result.append(buffer);
4587
4588 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4589 result.append(buffer);
4590 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4591 result.append(buffer);
4592 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4593 result.append(buffer);
4594 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4595 result.append(buffer);
4596 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4597 result.append(buffer);
4598
4599
4600 } else {
4601 result.append("No record client\n");
4602 }
4603 write(fd, result.string(), result.size());
4604
4605 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004606 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607
4608 return NO_ERROR;
4609}
4610
4611status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4612{
4613 size_t framesReq = buffer->frameCount;
4614 size_t framesReady = mFrameCount - mRsmpInIndex;
4615 int channelCount;
4616
4617 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004618 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 if (mBytesRead < 0) {
4620 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4621 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4622 // Force input into standby so that it tries to
4623 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004624 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004625 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 }
4627 buffer->raw = 0;
4628 buffer->frameCount = 0;
4629 return NOT_ENOUGH_DATA;
4630 }
4631 mRsmpInIndex = 0;
4632 framesReady = mFrameCount;
4633 }
4634
4635 if (framesReq > framesReady) {
4636 framesReq = framesReady;
4637 }
4638
4639 if (mChannelCount == 1 && mReqChannelCount == 2) {
4640 channelCount = 1;
4641 } else {
4642 channelCount = 2;
4643 }
4644 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4645 buffer->frameCount = framesReq;
4646 return NO_ERROR;
4647}
4648
4649void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4650{
4651 mRsmpInIndex += buffer->frameCount;
4652 buffer->frameCount = 0;
4653}
4654
4655bool AudioFlinger::RecordThread::checkForNewParameters_l()
4656{
4657 bool reconfig = false;
4658
4659 while (!mNewParameters.isEmpty()) {
4660 status_t status = NO_ERROR;
4661 String8 keyValuePair = mNewParameters[0];
4662 AudioParameter param = AudioParameter(keyValuePair);
4663 int value;
4664 int reqFormat = mFormat;
4665 int reqSamplingRate = mReqSampleRate;
4666 int reqChannelCount = mReqChannelCount;
4667
4668 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4669 reqSamplingRate = value;
4670 reconfig = true;
4671 }
4672 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4673 reqFormat = value;
4674 reconfig = true;
4675 }
4676 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004677 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004678 reconfig = true;
4679 }
4680 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4681 // do not accept frame count changes if tracks are open as the track buffer
4682 // size depends on frame count and correct behavior would not be garantied
4683 // if frame count is changed after track creation
4684 if (mActiveTrack != 0) {
4685 status = INVALID_OPERATION;
4686 } else {
4687 reconfig = true;
4688 }
4689 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004690 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4691 // forward device change to effects that have requested to be
4692 // aware of attached audio device.
4693 for (size_t i = 0; i < mEffectChains.size(); i++) {
4694 mEffectChains[i]->setDevice_l(value);
4695 }
4696 // store input device and output device but do not forward output device to audio HAL.
4697 // Note that status is ignored by the caller for output device
4698 // (see AudioFlinger::setParameters()
4699 if (value & AUDIO_DEVICE_OUT_ALL) {
4700 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4701 status = BAD_VALUE;
4702 } else {
4703 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004704 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4705 if (mTrack != NULL) {
4706 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004707 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004708 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4709 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4710 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004711 }
4712 mDevice |= (uint32_t)value;
4713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004714 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004715 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004717 mInput->stream->common.standby(&mInput->stream->common);
4718 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 }
4720 if (reconfig) {
4721 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004722 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004723 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004724 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4725 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004726 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 status = NO_ERROR;
4728 }
4729 if (status == NO_ERROR) {
4730 readInputParameters();
4731 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4732 }
4733 }
4734 }
4735
4736 mNewParameters.removeAt(0);
4737
4738 mParamStatus = status;
4739 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004740 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4741 // already timed out waiting for the status and will never signal the condition.
4742 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743 }
4744 return reconfig;
4745}
4746
4747String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4748{
Dima Zavinfce7a472011-04-19 22:30:36 -07004749 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004750 String8 out_s8 = String8();
4751
4752 Mutex::Autolock _l(mLock);
4753 if (initCheck() != NO_ERROR) {
4754 return out_s8;
4755 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004756
Dima Zavin799a70e2011-04-18 16:57:27 -07004757 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004758 out_s8 = String8(s);
4759 free(s);
4760 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761}
4762
4763void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4764 AudioSystem::OutputDescriptor desc;
4765 void *param2 = 0;
4766
4767 switch (event) {
4768 case AudioSystem::INPUT_OPENED:
4769 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004770 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771 desc.samplingRate = mSampleRate;
4772 desc.format = mFormat;
4773 desc.frameCount = mFrameCount;
4774 desc.latency = 0;
4775 param2 = &desc;
4776 break;
4777
4778 case AudioSystem::INPUT_CLOSED:
4779 default:
4780 break;
4781 }
4782 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4783}
4784
4785void AudioFlinger::RecordThread::readInputParameters()
4786{
4787 if (mRsmpInBuffer) delete mRsmpInBuffer;
4788 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4789 if (mResampler) delete mResampler;
4790 mResampler = 0;
4791
Dima Zavin799a70e2011-04-18 16:57:27 -07004792 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004793 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4794 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004795 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4796 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4797 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004798 mFrameCount = mInputBytes / mFrameSize;
4799 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4800
4801 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4802 {
4803 int channelCount;
4804 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4805 // stereo to mono post process as the resampler always outputs stereo.
4806 if (mChannelCount == 1 && mReqChannelCount == 2) {
4807 channelCount = 1;
4808 } else {
4809 channelCount = 2;
4810 }
4811 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4812 mResampler->setSampleRate(mSampleRate);
4813 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4814 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4815
4816 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4817 if (mChannelCount == 1 && mReqChannelCount == 1) {
4818 mFrameCount >>= 1;
4819 }
4820
4821 }
4822 mRsmpInIndex = mFrameCount;
4823}
4824
4825unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4826{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004827 Mutex::Autolock _l(mLock);
4828 if (initCheck() != NO_ERROR) {
4829 return 0;
4830 }
4831
Dima Zavin799a70e2011-04-18 16:57:27 -07004832 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004833}
4834
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004835uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4836{
4837 Mutex::Autolock _l(mLock);
4838 uint32_t result = 0;
4839 if (getEffectChain_l(sessionId) != 0) {
4840 result = EFFECT_SESSION;
4841 }
4842
4843 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4844 result |= TRACK_SESSION;
4845 }
4846
4847 return result;
4848}
4849
Eric Laurent59bd0da2011-08-01 09:52:20 -07004850AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4851{
4852 Mutex::Autolock _l(mLock);
4853 return mTrack;
4854}
4855
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004856AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4857{
4858 Mutex::Autolock _l(mLock);
4859 return mInput;
4860}
4861
4862AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4863{
4864 Mutex::Autolock _l(mLock);
4865 AudioStreamIn *input = mInput;
4866 mInput = NULL;
4867 return input;
4868}
4869
4870// this method must always be called either with ThreadBase mLock held or inside the thread loop
4871audio_stream_t* AudioFlinger::RecordThread::stream()
4872{
4873 if (mInput == NULL) {
4874 return NULL;
4875 }
4876 return &mInput->stream->common;
4877}
4878
4879
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880// ----------------------------------------------------------------------------
4881
4882int AudioFlinger::openOutput(uint32_t *pDevices,
4883 uint32_t *pSamplingRate,
4884 uint32_t *pFormat,
4885 uint32_t *pChannels,
4886 uint32_t *pLatencyMs,
4887 uint32_t flags)
4888{
4889 status_t status;
4890 PlaybackThread *thread = NULL;
4891 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4892 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4893 uint32_t format = pFormat ? *pFormat : 0;
4894 uint32_t channels = pChannels ? *pChannels : 0;
4895 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004896 audio_stream_out_t *outStream;
4897 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898
Steve Block3856b092011-10-20 11:56:00 +01004899 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900 pDevices ? *pDevices : 0,
4901 samplingRate,
4902 format,
4903 channels,
4904 flags);
4905
4906 if (pDevices == NULL || *pDevices == 0) {
4907 return 0;
4908 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004909
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910 Mutex::Autolock _l(mLock);
4911
Dima Zavin799a70e2011-04-18 16:57:27 -07004912 outHwDev = findSuitableHwDev_l(*pDevices);
4913 if (outHwDev == NULL)
4914 return 0;
4915
4916 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4917 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004918 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004919 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 samplingRate,
4921 format,
4922 channels,
4923 status);
4924
4925 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004926 if (outStream != NULL) {
4927 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004928 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004929
Dima Zavinfce7a472011-04-19 22:30:36 -07004930 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4931 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4932 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004934 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 } else {
4936 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004937 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 }
4939 mPlaybackThreads.add(id, thread);
4940
4941 if (pSamplingRate) *pSamplingRate = samplingRate;
4942 if (pFormat) *pFormat = format;
4943 if (pChannels) *pChannels = channels;
4944 if (pLatencyMs) *pLatencyMs = thread->latency();
4945
4946 // notify client processes of the new output creation
4947 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4948 return id;
4949 }
4950
4951 return 0;
4952}
4953
4954int AudioFlinger::openDuplicateOutput(int output1, int output2)
4955{
4956 Mutex::Autolock _l(mLock);
4957 MixerThread *thread1 = checkMixerThread_l(output1);
4958 MixerThread *thread2 = checkMixerThread_l(output2);
4959
4960 if (thread1 == NULL || thread2 == NULL) {
4961 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4962 return 0;
4963 }
4964
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004965 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004966 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4967 thread->addOutputTrack(thread2);
4968 mPlaybackThreads.add(id, thread);
4969 // notify client processes of the new output creation
4970 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4971 return id;
4972}
4973
4974status_t AudioFlinger::closeOutput(int output)
4975{
4976 // keep strong reference on the playback thread so that
4977 // it is not destroyed while exit() is executed
4978 sp <PlaybackThread> thread;
4979 {
4980 Mutex::Autolock _l(mLock);
4981 thread = checkPlaybackThread_l(output);
4982 if (thread == NULL) {
4983 return BAD_VALUE;
4984 }
4985
Steve Block3856b092011-10-20 11:56:00 +01004986 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004988 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4992 dupThread->removeOutputTrack((MixerThread *)thread.get());
4993 }
4994 }
4995 }
4996 void *param2 = 0;
4997 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4998 mPlaybackThreads.removeItem(output);
4999 }
5000 thread->exit();
5001
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005002 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005003 AudioStreamOut *out = thread->clearOutput();
5004 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005005 out->hwDev->close_output_stream(out->hwDev, out->stream);
5006 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 }
5008 return NO_ERROR;
5009}
5010
5011status_t AudioFlinger::suspendOutput(int output)
5012{
5013 Mutex::Autolock _l(mLock);
5014 PlaybackThread *thread = checkPlaybackThread_l(output);
5015
5016 if (thread == NULL) {
5017 return BAD_VALUE;
5018 }
5019
Steve Block3856b092011-10-20 11:56:00 +01005020 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 thread->suspend();
5022
5023 return NO_ERROR;
5024}
5025
5026status_t AudioFlinger::restoreOutput(int output)
5027{
5028 Mutex::Autolock _l(mLock);
5029 PlaybackThread *thread = checkPlaybackThread_l(output);
5030
5031 if (thread == NULL) {
5032 return BAD_VALUE;
5033 }
5034
Steve Block3856b092011-10-20 11:56:00 +01005035 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036
5037 thread->restore();
5038
5039 return NO_ERROR;
5040}
5041
5042int AudioFlinger::openInput(uint32_t *pDevices,
5043 uint32_t *pSamplingRate,
5044 uint32_t *pFormat,
5045 uint32_t *pChannels,
5046 uint32_t acoustics)
5047{
5048 status_t status;
5049 RecordThread *thread = NULL;
5050 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5051 uint32_t format = pFormat ? *pFormat : 0;
5052 uint32_t channels = pChannels ? *pChannels : 0;
5053 uint32_t reqSamplingRate = samplingRate;
5054 uint32_t reqFormat = format;
5055 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005056 audio_stream_in_t *inStream;
5057 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058
5059 if (pDevices == NULL || *pDevices == 0) {
5060 return 0;
5061 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005062
Mathias Agopian65ab4712010-07-14 17:59:35 -07005063 Mutex::Autolock _l(mLock);
5064
Dima Zavin799a70e2011-04-18 16:57:27 -07005065 inHwDev = findSuitableHwDev_l(*pDevices);
5066 if (inHwDev == NULL)
5067 return 0;
5068
5069 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5070 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005071 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005073 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005074 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 samplingRate,
5076 format,
5077 channels,
5078 acoustics,
5079 status);
5080
5081 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5082 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5083 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005085 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005087 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005088 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5090 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005091 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005092 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 }
5094
Dima Zavin799a70e2011-04-18 16:57:27 -07005095 if (inStream != NULL) {
5096 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5097
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005098 int id = nextUniqueId();
5099 // Start record thread
5100 // RecorThread require both input and output device indication to forward to audio
5101 // pre processing modules
5102 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5103 thread = new RecordThread(this,
5104 input,
5105 reqSamplingRate,
5106 reqChannels,
5107 id,
5108 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005110 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5112 if (pFormat) *pFormat = format;
5113 if (pChannels) *pChannels = reqChannels;
5114
Dima Zavin799a70e2011-04-18 16:57:27 -07005115 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116
5117 // notify client processes of the new input creation
5118 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5119 return id;
5120 }
5121
5122 return 0;
5123}
5124
5125status_t AudioFlinger::closeInput(int input)
5126{
5127 // keep strong reference on the record thread so that
5128 // it is not destroyed while exit() is executed
5129 sp <RecordThread> thread;
5130 {
5131 Mutex::Autolock _l(mLock);
5132 thread = checkRecordThread_l(input);
5133 if (thread == NULL) {
5134 return BAD_VALUE;
5135 }
5136
Steve Block3856b092011-10-20 11:56:00 +01005137 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 void *param2 = 0;
5139 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5140 mRecordThreads.removeItem(input);
5141 }
5142 thread->exit();
5143
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005144 AudioStreamIn *in = thread->clearInput();
5145 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005146 in->hwDev->close_input_stream(in->hwDev, in->stream);
5147 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148
5149 return NO_ERROR;
5150}
5151
5152status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5153{
5154 Mutex::Autolock _l(mLock);
5155 MixerThread *dstThread = checkMixerThread_l(output);
5156 if (dstThread == NULL) {
5157 LOGW("setStreamOutput() bad output id %d", output);
5158 return BAD_VALUE;
5159 }
5160
Steve Block3856b092011-10-20 11:56:00 +01005161 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5163
Eric Laurent9f6530f2011-08-30 10:18:54 -07005164 dstThread->setStreamValid(stream, true);
5165
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5167 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5168 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005169 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005171 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 }
Eric Laurentde070132010-07-13 04:45:46 -07005174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175
5176 return NO_ERROR;
5177}
5178
5179
5180int AudioFlinger::newAudioSessionId()
5181{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005182 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183}
5184
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005185void AudioFlinger::acquireAudioSessionId(int audioSession)
5186{
5187 Mutex::Autolock _l(mLock);
5188 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005189 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005190 int num = mAudioSessionRefs.size();
5191 for (int i = 0; i< num; i++) {
5192 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5193 if (ref->sessionid == audioSession && ref->pid == caller) {
5194 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005195 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005196 return;
5197 }
5198 }
5199 AudioSessionRef *ref = new AudioSessionRef();
5200 ref->sessionid = audioSession;
5201 ref->pid = caller;
5202 ref->cnt = 1;
5203 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005204 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005205}
5206
5207void AudioFlinger::releaseAudioSessionId(int audioSession)
5208{
5209 Mutex::Autolock _l(mLock);
5210 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005211 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005212 int num = mAudioSessionRefs.size();
5213 for (int i = 0; i< num; i++) {
5214 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5215 if (ref->sessionid == audioSession && ref->pid == caller) {
5216 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005217 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005218 if (ref->cnt == 0) {
5219 mAudioSessionRefs.removeAt(i);
5220 delete ref;
5221 purgeStaleEffects_l();
5222 }
5223 return;
5224 }
5225 }
5226 LOGW("session id %d not found for pid %d", audioSession, caller);
5227}
5228
5229void AudioFlinger::purgeStaleEffects_l() {
5230
Steve Block3856b092011-10-20 11:56:00 +01005231 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005232
5233 Vector< sp<EffectChain> > chains;
5234
5235 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5236 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5237 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5238 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005239 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5240 chains.push(ec);
5241 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005242 }
5243 }
5244 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5245 sp<RecordThread> t = mRecordThreads.valueAt(i);
5246 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5247 sp<EffectChain> ec = t->mEffectChains[j];
5248 chains.push(ec);
5249 }
5250 }
5251
5252 for (size_t i = 0; i < chains.size(); i++) {
5253 sp<EffectChain> ec = chains[i];
5254 int sessionid = ec->sessionId();
5255 sp<ThreadBase> t = ec->mThread.promote();
5256 if (t == 0) {
5257 continue;
5258 }
5259 size_t numsessionrefs = mAudioSessionRefs.size();
5260 bool found = false;
5261 for (size_t k = 0; k < numsessionrefs; k++) {
5262 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5263 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005264 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005265 sessionid, ref->pid, ref->cnt);
5266 found = true;
5267 break;
5268 }
5269 }
5270 if (!found) {
5271 // remove all effects from the chain
5272 while (ec->mEffects.size()) {
5273 sp<EffectModule> effect = ec->mEffects[0];
5274 effect->unPin();
5275 Mutex::Autolock _l (t->mLock);
5276 t->removeEffect_l(effect);
5277 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5278 sp<EffectHandle> handle = effect->mHandles[j].promote();
5279 if (handle != 0) {
5280 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005281 if (handle->mHasControl && handle->mEnabled) {
5282 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5283 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005284 }
5285 }
5286 AudioSystem::unregisterEffect(effect->id());
5287 }
5288 }
5289 }
5290 return;
5291}
5292
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5294AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5295{
5296 PlaybackThread *thread = NULL;
5297 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5298 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5299 }
5300 return thread;
5301}
5302
5303// checkMixerThread_l() must be called with AudioFlinger::mLock held
5304AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5305{
5306 PlaybackThread *thread = checkPlaybackThread_l(output);
5307 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005308 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309 thread = NULL;
5310 }
5311 }
5312 return (MixerThread *)thread;
5313}
5314
5315// checkRecordThread_l() must be called with AudioFlinger::mLock held
5316AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5317{
5318 RecordThread *thread = NULL;
5319 if (mRecordThreads.indexOfKey(input) >= 0) {
5320 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5321 }
5322 return thread;
5323}
5324
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005325uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005327 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328}
5329
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005330AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5331{
5332 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5333 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005334 AudioStreamOut *output = thread->getOutput();
5335 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005336 return thread;
5337 }
5338 }
5339 return NULL;
5340}
5341
5342uint32_t AudioFlinger::primaryOutputDevice_l()
5343{
5344 PlaybackThread *thread = primaryPlaybackThread_l();
5345
5346 if (thread == NULL) {
5347 return 0;
5348 }
5349
5350 return thread->device();
5351}
5352
5353
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354// ----------------------------------------------------------------------------
5355// Effect management
5356// ----------------------------------------------------------------------------
5357
5358
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5360{
5361 Mutex::Autolock _l(mLock);
5362 return EffectQueryNumberEffects(numEffects);
5363}
5364
5365status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5366{
5367 Mutex::Autolock _l(mLock);
5368 return EffectQueryEffect(index, descriptor);
5369}
5370
5371status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5372{
5373 Mutex::Autolock _l(mLock);
5374 return EffectGetDescriptor(pUuid, descriptor);
5375}
5376
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5379 effect_descriptor_t *pDesc,
5380 const sp<IEffectClient>& effectClient,
5381 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005382 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 int sessionId,
5384 status_t *status,
5385 int *id,
5386 int *enabled)
5387{
5388 status_t lStatus = NO_ERROR;
5389 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 effect_descriptor_t desc;
5391 sp<Client> client;
5392 wp<Client> wclient;
5393
Steve Block3856b092011-10-20 11:56:00 +01005394 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005395 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396
5397 if (pDesc == NULL) {
5398 lStatus = BAD_VALUE;
5399 goto Exit;
5400 }
5401
Eric Laurent84e9a102010-09-23 16:10:16 -07005402 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005403 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005404 lStatus = PERMISSION_DENIED;
5405 goto Exit;
5406 }
5407
Dima Zavinfce7a472011-04-19 22:30:36 -07005408 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005409 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005410 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005411 lStatus = PERMISSION_DENIED;
5412 goto Exit;
5413 }
5414
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005415 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005416 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005417 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005418 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005419 lStatus = BAD_VALUE;
5420 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005423 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005425 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005426 }
5427 }
5428
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 {
5430 Mutex::Autolock _l(mLock);
5431
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432
5433 if (!EffectIsNullUuid(&pDesc->uuid)) {
5434 // if uuid is specified, request effect descriptor
5435 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5436 if (lStatus < 0) {
5437 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5438 goto Exit;
5439 }
5440 } else {
5441 // if uuid is not specified, look for an available implementation
5442 // of the required type in effect factory
5443 if (EffectIsNullUuid(&pDesc->type)) {
5444 LOGW("createEffect() no effect type");
5445 lStatus = BAD_VALUE;
5446 goto Exit;
5447 }
5448 uint32_t numEffects = 0;
5449 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005450 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 bool found = false;
5452
5453 lStatus = EffectQueryNumberEffects(&numEffects);
5454 if (lStatus < 0) {
5455 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5456 goto Exit;
5457 }
5458 for (uint32_t i = 0; i < numEffects; i++) {
5459 lStatus = EffectQueryEffect(i, &desc);
5460 if (lStatus < 0) {
5461 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5462 continue;
5463 }
5464 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5465 // If matching type found save effect descriptor. If the session is
5466 // 0 and the effect is not auxiliary, continue enumeration in case
5467 // an auxiliary version of this effect type is available
5468 found = true;
5469 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005470 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5472 break;
5473 }
5474 }
5475 }
5476 if (!found) {
5477 lStatus = BAD_VALUE;
5478 LOGW("createEffect() effect not found");
5479 goto Exit;
5480 }
5481 // For same effect type, chose auxiliary version over insert version if
5482 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005483 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5485 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5486 }
5487 }
5488
5489 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005490 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5492 lStatus = INVALID_OPERATION;
5493 goto Exit;
5494 }
5495
Eric Laurent59255e42011-07-27 19:49:51 -07005496 // check recording permission for visualizer
5497 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5498 !recordingAllowed()) {
5499 lStatus = PERMISSION_DENIED;
5500 goto Exit;
5501 }
5502
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 // return effect descriptor
5504 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5505
5506 // If output is not specified try to find a matching audio session ID in one of the
5507 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005508 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5509 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005510 // Note: io is never 0 when creating an effect on an input
5511 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005512 // look for the thread where the specified audio session is present
5513 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5514 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005515 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005516 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005519 if (io == 0) {
5520 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5521 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5522 io = mRecordThreads.keyAt(i);
5523 break;
5524 }
5525 }
5526 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005527 // If no output thread contains the requested session ID, default to
5528 // first output. The effect chain will be moved to the correct output
5529 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005530 if (io == 0 && mPlaybackThreads.size()) {
5531 io = mPlaybackThreads.keyAt(0);
5532 }
Steve Block3856b092011-10-20 11:56:00 +01005533 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005534 }
5535 ThreadBase *thread = checkRecordThread_l(io);
5536 if (thread == NULL) {
5537 thread = checkPlaybackThread_l(io);
5538 if (thread == NULL) {
5539 LOGE("createEffect() unknown output thread");
5540 lStatus = BAD_VALUE;
5541 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005542 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005544
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 wclient = mClients.valueFor(pid);
5546
5547 if (wclient != NULL) {
5548 client = wclient.promote();
5549 } else {
5550 client = new Client(this, pid);
5551 mClients.add(pid, client);
5552 }
5553
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005554 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005555 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5556 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 if (handle != 0 && id != NULL) {
5558 *id = handle->id();
5559 }
5560 }
5561
5562Exit:
5563 if(status) {
5564 *status = lStatus;
5565 }
5566 return handle;
5567}
5568
Eric Laurent59255e42011-07-27 19:49:51 -07005569status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005570{
Steve Block3856b092011-10-20 11:56:00 +01005571 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005572 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005573 Mutex::Autolock _l(mLock);
5574 if (srcOutput == dstOutput) {
5575 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5576 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 }
Eric Laurentde070132010-07-13 04:45:46 -07005578 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5579 if (srcThread == NULL) {
5580 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5581 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 }
Eric Laurentde070132010-07-13 04:45:46 -07005583 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5584 if (dstThread == NULL) {
5585 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5586 return BAD_VALUE;
5587 }
5588
5589 Mutex::Autolock _dl(dstThread->mLock);
5590 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005591 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005592
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 return NO_ERROR;
5594}
5595
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005596// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005597status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005598 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005599 AudioFlinger::PlaybackThread *dstThread,
5600 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005601{
Steve Block3856b092011-10-20 11:56:00 +01005602 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005603 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005604
Eric Laurent59255e42011-07-27 19:49:51 -07005605 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005606 if (chain == 0) {
5607 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005608 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005609 return INVALID_OPERATION;
5610 }
5611
Eric Laurent39e94f82010-07-28 01:32:47 -07005612 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005613 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005614 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005615 // removed.
5616 srcThread->removeEffectChain_l(chain);
5617
5618 // transfer all effects one by one so that new effect chain is created on new thread with
5619 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005620 int dstOutput = dstThread->id();
5621 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005622 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005623 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5624 while (effect != 0) {
5625 srcThread->removeEffect_l(effect);
5626 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005627 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5628 if (effect->state() == EffectModule::ACTIVE ||
5629 effect->state() == EffectModule::STOPPING) {
5630 effect->start();
5631 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005632 // if the move request is not received from audio policy manager, the effect must be
5633 // re-registered with the new strategy and output
5634 if (dstChain == 0) {
5635 dstChain = effect->chain().promote();
5636 if (dstChain == 0) {
5637 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5638 srcThread->addEffect_l(effect);
5639 return NO_INIT;
5640 }
5641 strategy = dstChain->strategy();
5642 }
5643 if (reRegister) {
5644 AudioSystem::unregisterEffect(effect->id());
5645 AudioSystem::registerEffect(&effect->desc(),
5646 dstOutput,
5647 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005648 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005649 effect->id());
5650 }
Eric Laurentde070132010-07-13 04:45:46 -07005651 effect = chain->getEffectFromId_l(0);
5652 }
5653
5654 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655}
5656
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005657
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005659sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 const sp<AudioFlinger::Client>& client,
5661 const sp<IEffectClient>& effectClient,
5662 int32_t priority,
5663 int sessionId,
5664 effect_descriptor_t *desc,
5665 int *enabled,
5666 status_t *status
5667 )
5668{
5669 sp<EffectModule> effect;
5670 sp<EffectHandle> handle;
5671 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005673 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 bool effectCreated = false;
5675 bool effectRegistered = false;
5676
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005677 lStatus = initCheck();
5678 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 goto Exit;
5681 }
5682
5683 // Do not allow effects with session ID 0 on direct output or duplicating threads
5684 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005685 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005686 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5687 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 lStatus = BAD_VALUE;
5689 goto Exit;
5690 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005691 // Only Pre processor effects are allowed on input threads and only on input threads
5692 if ((mType == RECORD &&
5693 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5694 (mType != RECORD &&
5695 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5696 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5697 desc->name, desc->flags, mType);
5698 lStatus = BAD_VALUE;
5699 goto Exit;
5700 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701
Steve Block3856b092011-10-20 11:56:00 +01005702 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703
5704 { // scope for mLock
5705 Mutex::Autolock _l(mLock);
5706
5707 // check for existing effect chain with the requested audio session
5708 chain = getEffectChain_l(sessionId);
5709 if (chain == 0) {
5710 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005711 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 chain = new EffectChain(this, sessionId);
5713 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005714 chain->setStrategy(getStrategyForSession_l(sessionId));
5715 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005717 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 }
5719
Steve Block3856b092011-10-20 11:56:00 +01005720 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721
5722 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005723 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005725 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 if (lStatus != NO_ERROR) {
5727 goto Exit;
5728 }
5729 effectRegistered = true;
5730 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005731 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 lStatus = effect->status();
5733 if (lStatus != NO_ERROR) {
5734 goto Exit;
5735 }
Eric Laurentcab11242010-07-15 12:50:15 -07005736 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 if (lStatus != NO_ERROR) {
5738 goto Exit;
5739 }
5740 effectCreated = true;
5741
5742 effect->setDevice(mDevice);
5743 effect->setMode(mAudioFlinger->getMode());
5744 }
5745 // create effect handle and connect it to effect module
5746 handle = new EffectHandle(effect, client, effectClient, priority);
5747 lStatus = effect->addHandle(handle);
5748 if (enabled) {
5749 *enabled = (int)effect->isEnabled();
5750 }
5751 }
5752
5753Exit:
5754 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005755 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005757 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 }
5759 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005760 AudioSystem::unregisterEffect(effect->id());
5761 }
5762 if (chainCreated) {
5763 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 }
5765 handle.clear();
5766 }
5767
5768 if(status) {
5769 *status = lStatus;
5770 }
5771 return handle;
5772}
5773
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005774sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5775{
5776 sp<EffectModule> effect;
5777
5778 sp<EffectChain> chain = getEffectChain_l(sessionId);
5779 if (chain != 0) {
5780 effect = chain->getEffectFromId_l(effectId);
5781 }
5782 return effect;
5783}
5784
Eric Laurentde070132010-07-13 04:45:46 -07005785// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5786// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005787status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005788{
5789 // check for existing effect chain with the requested audio session
5790 int sessionId = effect->sessionId();
5791 sp<EffectChain> chain = getEffectChain_l(sessionId);
5792 bool chainCreated = false;
5793
5794 if (chain == 0) {
5795 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005796 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005797 chain = new EffectChain(this, sessionId);
5798 addEffectChain_l(chain);
5799 chain->setStrategy(getStrategyForSession_l(sessionId));
5800 chainCreated = true;
5801 }
Steve Block3856b092011-10-20 11:56:00 +01005802 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005803
5804 if (chain->getEffectFromId_l(effect->id()) != 0) {
5805 LOGW("addEffect_l() %p effect %s already present in chain %p",
5806 this, effect->desc().name, chain.get());
5807 return BAD_VALUE;
5808 }
5809
5810 status_t status = chain->addEffect_l(effect);
5811 if (status != NO_ERROR) {
5812 if (chainCreated) {
5813 removeEffectChain_l(chain);
5814 }
5815 return status;
5816 }
5817
5818 effect->setDevice(mDevice);
5819 effect->setMode(mAudioFlinger->getMode());
5820 return NO_ERROR;
5821}
5822
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005823void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005824
Steve Block3856b092011-10-20 11:56:00 +01005825 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005827 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5828 detachAuxEffect_l(effect->id());
5829 }
5830
5831 sp<EffectChain> chain = effect->chain().promote();
5832 if (chain != 0) {
5833 // remove effect chain if removing last effect
5834 if (chain->removeEffect_l(effect) == 0) {
5835 removeEffectChain_l(chain);
5836 }
5837 } else {
5838 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5839 }
5840}
5841
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005842void AudioFlinger::ThreadBase::lockEffectChains_l(
5843 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5844{
5845 effectChains = mEffectChains;
5846 for (size_t i = 0; i < mEffectChains.size(); i++) {
5847 mEffectChains[i]->lock();
5848 }
5849}
5850
5851void AudioFlinger::ThreadBase::unlockEffectChains(
5852 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5853{
5854 for (size_t i = 0; i < effectChains.size(); i++) {
5855 effectChains[i]->unlock();
5856 }
5857}
5858
5859sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5860{
5861 Mutex::Autolock _l(mLock);
5862 return getEffectChain_l(sessionId);
5863}
5864
5865sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5866{
5867 sp<EffectChain> chain;
5868
5869 size_t size = mEffectChains.size();
5870 for (size_t i = 0; i < size; i++) {
5871 if (mEffectChains[i]->sessionId() == sessionId) {
5872 chain = mEffectChains[i];
5873 break;
5874 }
5875 }
5876 return chain;
5877}
5878
5879void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5880{
5881 Mutex::Autolock _l(mLock);
5882 size_t size = mEffectChains.size();
5883 for (size_t i = 0; i < size; i++) {
5884 mEffectChains[i]->setMode_l(mode);
5885 }
5886}
5887
5888void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005889 const wp<EffectHandle>& handle,
5890 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005891
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005893 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 // delete the effect module if removing last handle on it
5895 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005896 if (!effect->isPinned() || unpiniflast) {
5897 removeEffect_l(effect);
5898 AudioSystem::unregisterEffect(effect->id());
5899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 }
5901}
5902
5903status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5904{
5905 int session = chain->sessionId();
5906 int16_t *buffer = mMixBuffer;
5907 bool ownsBuffer = false;
5908
Steve Block3856b092011-10-20 11:56:00 +01005909 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 if (session > 0) {
5911 // Only one effect chain can be present in direct output thread and it uses
5912 // the mix buffer as input
5913 if (mType != DIRECT) {
5914 size_t numSamples = mFrameCount * mChannelCount;
5915 buffer = new int16_t[numSamples];
5916 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005917 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 ownsBuffer = true;
5919 }
5920
5921 // Attach all tracks with same session ID to this chain.
5922 for (size_t i = 0; i < mTracks.size(); ++i) {
5923 sp<Track> track = mTracks[i];
5924 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005927 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 }
5929 }
5930
5931 // indicate all active tracks in the chain
5932 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5933 sp<Track> track = mActiveTracks[i].promote();
5934 if (track == 0) continue;
5935 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005936 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005937 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 }
5939 }
5940 }
5941
5942 chain->setInBuffer(buffer, ownsBuffer);
5943 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005944 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005945 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005946 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5947 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005949 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5950 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005951 // Effect chain for other sessions are inserted at beginning of effect
5952 // chains list to be processed before output mix effects. Relative order between other
5953 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 size_t size = mEffectChains.size();
5955 size_t i = 0;
5956 for (i = 0; i < size; i++) {
5957 if (mEffectChains[i]->sessionId() < session) break;
5958 }
5959 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005960 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961
5962 return NO_ERROR;
5963}
5964
5965size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5966{
5967 int session = chain->sessionId();
5968
Steve Block3856b092011-10-20 11:56:00 +01005969 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970
5971 for (size_t i = 0; i < mEffectChains.size(); i++) {
5972 if (chain == mEffectChains[i]) {
5973 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005974 // detach all active tracks from the chain
5975 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5976 sp<Track> track = mActiveTracks[i].promote();
5977 if (track == 0) continue;
5978 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005979 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005980 chain.get(), session);
5981 chain->decActiveTrackCnt();
5982 }
5983 }
5984
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 // detach all tracks with same session ID from this chain
5986 for (size_t i = 0; i < mTracks.size(); ++i) {
5987 sp<Track> track = mTracks[i];
5988 if (session == track->sessionId()) {
5989 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005990 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 }
5992 }
Eric Laurentde070132010-07-13 04:45:46 -07005993 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994 }
5995 }
5996 return mEffectChains.size();
5997}
5998
Eric Laurentde070132010-07-13 04:45:46 -07005999status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6000 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001{
6002 Mutex::Autolock _l(mLock);
6003 return attachAuxEffect_l(track, EffectId);
6004}
6005
Eric Laurentde070132010-07-13 04:45:46 -07006006status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6007 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008{
6009 status_t status = NO_ERROR;
6010
6011 if (EffectId == 0) {
6012 track->setAuxBuffer(0, NULL);
6013 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006014 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6015 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006016 if (effect != 0) {
6017 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6018 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6019 } else {
6020 status = INVALID_OPERATION;
6021 }
6022 } else {
6023 status = BAD_VALUE;
6024 }
6025 }
6026 return status;
6027}
6028
6029void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6030{
6031 for (size_t i = 0; i < mTracks.size(); ++i) {
6032 sp<Track> track = mTracks[i];
6033 if (track->auxEffectId() == effectId) {
6034 attachAuxEffect_l(track, 0);
6035 }
6036 }
6037}
6038
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6040{
6041 // only one chain per input thread
6042 if (mEffectChains.size() != 0) {
6043 return INVALID_OPERATION;
6044 }
Steve Block3856b092011-10-20 11:56:00 +01006045 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006046
6047 chain->setInBuffer(NULL);
6048 chain->setOutBuffer(NULL);
6049
Eric Laurent59255e42011-07-27 19:49:51 -07006050 checkSuspendOnAddEffectChain_l(chain);
6051
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052 mEffectChains.add(chain);
6053
6054 return NO_ERROR;
6055}
6056
6057size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6058{
Steve Block3856b092011-10-20 11:56:00 +01006059 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006060 LOGW_IF(mEffectChains.size() != 1,
6061 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6062 chain.get(), mEffectChains.size(), this);
6063 if (mEffectChains.size() == 1) {
6064 mEffectChains.removeAt(0);
6065 }
6066 return 0;
6067}
6068
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069// ----------------------------------------------------------------------------
6070// EffectModule implementation
6071// ----------------------------------------------------------------------------
6072
6073#undef LOG_TAG
6074#define LOG_TAG "AudioFlinger::EffectModule"
6075
6076AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6077 const wp<AudioFlinger::EffectChain>& chain,
6078 effect_descriptor_t *desc,
6079 int id,
6080 int sessionId)
6081 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006082 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083{
Steve Block3856b092011-10-20 11:56:00 +01006084 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 int lStatus;
6086 sp<ThreadBase> thread = mThread.promote();
6087 if (thread == 0) {
6088 return;
6089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090
6091 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6092
6093 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006094 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095
6096 if (mStatus != NO_ERROR) {
6097 return;
6098 }
6099 lStatus = init();
6100 if (lStatus < 0) {
6101 mStatus = lStatus;
6102 goto Error;
6103 }
6104
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006105 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6106 mPinned = true;
6107 }
Steve Block3856b092011-10-20 11:56:00 +01006108 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 return;
6110Error:
6111 EffectRelease(mEffectInterface);
6112 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006113 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114}
6115
6116AudioFlinger::EffectModule::~EffectModule()
6117{
Steve Block3856b092011-10-20 11:56:00 +01006118 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006120 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6121 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6122 sp<ThreadBase> thread = mThread.promote();
6123 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006124 audio_stream_t *stream = thread->stream();
6125 if (stream != NULL) {
6126 stream->remove_audio_effect(stream, mEffectInterface);
6127 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006128 }
6129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 // release effect engine
6131 EffectRelease(mEffectInterface);
6132 }
6133}
6134
6135status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6136{
6137 status_t status;
6138
6139 Mutex::Autolock _l(mLock);
6140 // First handle in mHandles has highest priority and controls the effect module
6141 int priority = handle->priority();
6142 size_t size = mHandles.size();
6143 sp<EffectHandle> h;
6144 size_t i;
6145 for (i = 0; i < size; i++) {
6146 h = mHandles[i].promote();
6147 if (h == 0) continue;
6148 if (h->priority() <= priority) break;
6149 }
6150 // if inserted in first place, move effect control from previous owner to this handle
6151 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006152 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006154 enabled = h->enabled();
6155 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 }
Eric Laurent59255e42011-07-27 19:49:51 -07006157 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 status = NO_ERROR;
6159 } else {
6160 status = ALREADY_EXISTS;
6161 }
Steve Block3856b092011-10-20 11:56:00 +01006162 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 mHandles.insertAt(handle, i);
6164 return status;
6165}
6166
6167size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6168{
6169 Mutex::Autolock _l(mLock);
6170 size_t size = mHandles.size();
6171 size_t i;
6172 for (i = 0; i < size; i++) {
6173 if (mHandles[i] == handle) break;
6174 }
6175 if (i == size) {
6176 return size;
6177 }
Steve Block3856b092011-10-20 11:56:00 +01006178 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006179
6180 bool enabled = false;
6181 EffectHandle *hdl = handle.unsafe_get();
6182 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006183 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006184 enabled = hdl->enabled();
6185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 mHandles.removeAt(i);
6187 size = mHandles.size();
6188 // if removed from first place, move effect control from this handle to next in line
6189 if (i == 0 && size != 0) {
6190 sp<EffectHandle> h = mHandles[0].promote();
6191 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006192 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 }
6194 }
6195
Eric Laurentec437d82011-07-26 20:54:46 -07006196 // Prevent calls to process() and other functions on effect interface from now on.
6197 // The effect engine will be released by the destructor when the last strong reference on
6198 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006199 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006200 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006201 }
6202
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 return size;
6204}
6205
Eric Laurent59255e42011-07-27 19:49:51 -07006206sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6207{
6208 Mutex::Autolock _l(mLock);
6209 sp<EffectHandle> handle;
6210 if (mHandles.size() != 0) {
6211 handle = mHandles[0].promote();
6212 }
6213 return handle;
6214}
6215
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006216void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217{
Steve Block3856b092011-10-20 11:56:00 +01006218 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 // keep a strong reference on this EffectModule to avoid calling the
6220 // destructor before we exit
6221 sp<EffectModule> keep(this);
6222 {
6223 sp<ThreadBase> thread = mThread.promote();
6224 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006225 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 }
6227 }
6228}
6229
6230void AudioFlinger::EffectModule::updateState() {
6231 Mutex::Autolock _l(mLock);
6232
6233 switch (mState) {
6234 case RESTART:
6235 reset_l();
6236 // FALL THROUGH
6237
6238 case STARTING:
6239 // clear auxiliary effect input buffer for next accumulation
6240 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6241 memset(mConfig.inputCfg.buffer.raw,
6242 0,
6243 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6244 }
6245 start_l();
6246 mState = ACTIVE;
6247 break;
6248 case STOPPING:
6249 stop_l();
6250 mDisableWaitCnt = mMaxDisableWaitCnt;
6251 mState = STOPPED;
6252 break;
6253 case STOPPED:
6254 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6255 // turn off sequence.
6256 if (--mDisableWaitCnt == 0) {
6257 reset_l();
6258 mState = IDLE;
6259 }
6260 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006261 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 break;
6263 }
6264}
6265
6266void AudioFlinger::EffectModule::process()
6267{
6268 Mutex::Autolock _l(mLock);
6269
Eric Laurentec437d82011-07-26 20:54:46 -07006270 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 mConfig.inputCfg.buffer.raw == NULL ||
6272 mConfig.outputCfg.buffer.raw == NULL) {
6273 return;
6274 }
6275
Eric Laurent8f45bd72010-08-31 13:50:07 -07006276 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6278 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6279 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6280 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006281 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 }
6283
6284 // do the actual processing in the effect engine
6285 int ret = (*mEffectInterface)->process(mEffectInterface,
6286 &mConfig.inputCfg.buffer,
6287 &mConfig.outputCfg.buffer);
6288
6289 // force transition to IDLE state when engine is ready
6290 if (mState == STOPPED && ret == -ENODATA) {
6291 mDisableWaitCnt = 1;
6292 }
6293
6294 // clear auxiliary effect input buffer for next accumulation
6295 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006296 memset(mConfig.inputCfg.buffer.raw, 0,
6297 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298 }
6299 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006300 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6301 // If an insert effect is idle and input buffer is different from output buffer,
6302 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006304 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006305 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6306 int16_t *in = mConfig.inputCfg.buffer.s16;
6307 int16_t *out = mConfig.outputCfg.buffer.s16;
6308 for (size_t i = 0; i < frameCnt; i++) {
6309 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 }
6312 }
6313}
6314
6315void AudioFlinger::EffectModule::reset_l()
6316{
6317 if (mEffectInterface == NULL) {
6318 return;
6319 }
6320 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6321}
6322
6323status_t AudioFlinger::EffectModule::configure()
6324{
6325 uint32_t channels;
6326 if (mEffectInterface == NULL) {
6327 return NO_INIT;
6328 }
6329
6330 sp<ThreadBase> thread = mThread.promote();
6331 if (thread == 0) {
6332 return DEAD_OBJECT;
6333 }
6334
6335 // TODO: handle configuration of effects replacing track process
6336 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006337 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006339 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 }
6341
6342 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006343 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 } else {
6345 mConfig.inputCfg.channels = channels;
6346 }
6347 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006348 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6349 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 mConfig.inputCfg.samplingRate = thread->sampleRate();
6351 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6352 mConfig.inputCfg.bufferProvider.cookie = NULL;
6353 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6354 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6355 mConfig.outputCfg.bufferProvider.cookie = NULL;
6356 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6357 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6358 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6359 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006360 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006361 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006362 // - in other sessions:
6363 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6364 // other effect: overwrites output buffer: input buffer == output buffer
6365 // Auxiliary effect:
6366 // accumulates in output buffer: input buffer != output buffer
6367 // Therefore: accumulate <=> input buffer != output buffer
6368 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6369 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6370 } else {
6371 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6372 }
6373 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6374 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6375 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6376 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6377
Steve Block3856b092011-10-20 11:56:00 +01006378 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006379 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6380
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006382 uint32_t size = sizeof(int);
6383 status_t status = (*mEffectInterface)->command(mEffectInterface,
6384 EFFECT_CMD_CONFIGURE,
6385 sizeof(effect_config_t),
6386 &mConfig,
6387 &size,
6388 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389 if (status == 0) {
6390 status = cmdStatus;
6391 }
6392
6393 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6394 (1000 * mConfig.outputCfg.buffer.frameCount);
6395
6396 return status;
6397}
6398
6399status_t AudioFlinger::EffectModule::init()
6400{
6401 Mutex::Autolock _l(mLock);
6402 if (mEffectInterface == NULL) {
6403 return NO_INIT;
6404 }
6405 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006406 uint32_t size = sizeof(status_t);
6407 status_t status = (*mEffectInterface)->command(mEffectInterface,
6408 EFFECT_CMD_INIT,
6409 0,
6410 NULL,
6411 &size,
6412 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 if (status == 0) {
6414 status = cmdStatus;
6415 }
6416 return status;
6417}
6418
Eric Laurentec35a142011-10-05 17:42:25 -07006419status_t AudioFlinger::EffectModule::start()
6420{
6421 Mutex::Autolock _l(mLock);
6422 return start_l();
6423}
6424
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425status_t AudioFlinger::EffectModule::start_l()
6426{
6427 if (mEffectInterface == NULL) {
6428 return NO_INIT;
6429 }
6430 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006431 uint32_t size = sizeof(status_t);
6432 status_t status = (*mEffectInterface)->command(mEffectInterface,
6433 EFFECT_CMD_ENABLE,
6434 0,
6435 NULL,
6436 &size,
6437 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438 if (status == 0) {
6439 status = cmdStatus;
6440 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006441 if (status == 0 &&
6442 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6443 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6444 sp<ThreadBase> thread = mThread.promote();
6445 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006446 audio_stream_t *stream = thread->stream();
6447 if (stream != NULL) {
6448 stream->add_audio_effect(stream, mEffectInterface);
6449 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006450 }
6451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 return status;
6453}
6454
Eric Laurentec437d82011-07-26 20:54:46 -07006455status_t AudioFlinger::EffectModule::stop()
6456{
6457 Mutex::Autolock _l(mLock);
6458 return stop_l();
6459}
6460
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461status_t AudioFlinger::EffectModule::stop_l()
6462{
6463 if (mEffectInterface == NULL) {
6464 return NO_INIT;
6465 }
6466 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006467 uint32_t size = sizeof(status_t);
6468 status_t status = (*mEffectInterface)->command(mEffectInterface,
6469 EFFECT_CMD_DISABLE,
6470 0,
6471 NULL,
6472 &size,
6473 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474 if (status == 0) {
6475 status = cmdStatus;
6476 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006477 if (status == 0 &&
6478 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6479 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6480 sp<ThreadBase> thread = mThread.promote();
6481 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006482 audio_stream_t *stream = thread->stream();
6483 if (stream != NULL) {
6484 stream->remove_audio_effect(stream, mEffectInterface);
6485 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006486 }
6487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 return status;
6489}
6490
Eric Laurent25f43952010-07-28 05:40:18 -07006491status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6492 uint32_t cmdSize,
6493 void *pCmdData,
6494 uint32_t *replySize,
6495 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496{
6497 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006498// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499
Eric Laurentec437d82011-07-26 20:54:46 -07006500 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 return NO_INIT;
6502 }
Eric Laurent25f43952010-07-28 05:40:18 -07006503 status_t status = (*mEffectInterface)->command(mEffectInterface,
6504 cmdCode,
6505 cmdSize,
6506 pCmdData,
6507 replySize,
6508 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006510 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 for (size_t i = 1; i < mHandles.size(); i++) {
6512 sp<EffectHandle> h = mHandles[i].promote();
6513 if (h != 0) {
6514 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6515 }
6516 }
6517 }
6518 return status;
6519}
6520
6521status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6522{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006523
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006525 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526
6527 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006528 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6529 if (enabled && status != NO_ERROR) {
6530 return status;
6531 }
6532
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533 switch (mState) {
6534 // going from disabled to enabled
6535 case IDLE:
6536 mState = STARTING;
6537 break;
6538 case STOPPED:
6539 mState = RESTART;
6540 break;
6541 case STOPPING:
6542 mState = ACTIVE;
6543 break;
6544
6545 // going from enabled to disabled
6546 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006547 mState = STOPPED;
6548 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 case STARTING:
6550 mState = IDLE;
6551 break;
6552 case ACTIVE:
6553 mState = STOPPING;
6554 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006555 case DESTROYED:
6556 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 }
6558 for (size_t i = 1; i < mHandles.size(); i++) {
6559 sp<EffectHandle> h = mHandles[i].promote();
6560 if (h != 0) {
6561 h->setEnabled(enabled);
6562 }
6563 }
6564 }
6565 return NO_ERROR;
6566}
6567
6568bool AudioFlinger::EffectModule::isEnabled()
6569{
6570 switch (mState) {
6571 case RESTART:
6572 case STARTING:
6573 case ACTIVE:
6574 return true;
6575 case IDLE:
6576 case STOPPING:
6577 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006578 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 default:
6580 return false;
6581 }
6582}
6583
Eric Laurent8f45bd72010-08-31 13:50:07 -07006584bool AudioFlinger::EffectModule::isProcessEnabled()
6585{
6586 switch (mState) {
6587 case RESTART:
6588 case ACTIVE:
6589 case STOPPING:
6590 case STOPPED:
6591 return true;
6592 case IDLE:
6593 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006594 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006595 default:
6596 return false;
6597 }
6598}
6599
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6601{
6602 Mutex::Autolock _l(mLock);
6603 status_t status = NO_ERROR;
6604
6605 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6606 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006607 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006608 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6609 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 status_t cmdStatus;
6611 uint32_t volume[2];
6612 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006613 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 volume[0] = *left;
6615 volume[1] = *right;
6616 if (controller) {
6617 pVolume = volume;
6618 }
Eric Laurent25f43952010-07-28 05:40:18 -07006619 status = (*mEffectInterface)->command(mEffectInterface,
6620 EFFECT_CMD_SET_VOLUME,
6621 size,
6622 volume,
6623 &size,
6624 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6626 *left = volume[0];
6627 *right = volume[1];
6628 }
6629 }
6630 return status;
6631}
6632
6633status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6634{
6635 Mutex::Autolock _l(mLock);
6636 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006637 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6638 // audio pre processing modules on RecordThread can receive both output and
6639 // input device indication in the same call
6640 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6641 if (dev) {
6642 status_t cmdStatus;
6643 uint32_t size = sizeof(status_t);
6644
6645 status = (*mEffectInterface)->command(mEffectInterface,
6646 EFFECT_CMD_SET_DEVICE,
6647 sizeof(uint32_t),
6648 &dev,
6649 &size,
6650 &cmdStatus);
6651 if (status == NO_ERROR) {
6652 status = cmdStatus;
6653 }
6654 }
6655 dev = device & AUDIO_DEVICE_IN_ALL;
6656 if (dev) {
6657 status_t cmdStatus;
6658 uint32_t size = sizeof(status_t);
6659
6660 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6661 EFFECT_CMD_SET_INPUT_DEVICE,
6662 sizeof(uint32_t),
6663 &dev,
6664 &size,
6665 &cmdStatus);
6666 if (status2 == NO_ERROR) {
6667 status2 = cmdStatus;
6668 }
6669 if (status == NO_ERROR) {
6670 status = status2;
6671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672 }
6673 }
6674 return status;
6675}
6676
6677status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6678{
6679 Mutex::Autolock _l(mLock);
6680 status_t status = NO_ERROR;
6681 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006683 uint32_t size = sizeof(status_t);
6684 status = (*mEffectInterface)->command(mEffectInterface,
6685 EFFECT_CMD_SET_AUDIO_MODE,
6686 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006687 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006688 &size,
6689 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690 if (status == NO_ERROR) {
6691 status = cmdStatus;
6692 }
6693 }
6694 return status;
6695}
6696
Eric Laurent59255e42011-07-27 19:49:51 -07006697void AudioFlinger::EffectModule::setSuspended(bool suspended)
6698{
6699 Mutex::Autolock _l(mLock);
6700 mSuspended = suspended;
6701}
6702bool AudioFlinger::EffectModule::suspended()
6703{
6704 Mutex::Autolock _l(mLock);
6705 return mSuspended;
6706}
6707
Mathias Agopian65ab4712010-07-14 17:59:35 -07006708status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6709{
6710 const size_t SIZE = 256;
6711 char buffer[SIZE];
6712 String8 result;
6713
6714 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6715 result.append(buffer);
6716
6717 bool locked = tryLock(mLock);
6718 // failed to lock - AudioFlinger is probably deadlocked
6719 if (!locked) {
6720 result.append("\t\tCould not lock Fx mutex:\n");
6721 }
6722
6723 result.append("\t\tSession Status State Engine:\n");
6724 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6725 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6726 result.append(buffer);
6727
6728 result.append("\t\tDescriptor:\n");
6729 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6730 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6731 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6732 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6733 result.append(buffer);
6734 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6735 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6736 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6737 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6738 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006739 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 mDescriptor.apiVersion,
6741 mDescriptor.flags);
6742 result.append(buffer);
6743 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6744 mDescriptor.name);
6745 result.append(buffer);
6746 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6747 mDescriptor.implementor);
6748 result.append(buffer);
6749
6750 result.append("\t\t- Input configuration:\n");
6751 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6752 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6753 (uint32_t)mConfig.inputCfg.buffer.raw,
6754 mConfig.inputCfg.buffer.frameCount,
6755 mConfig.inputCfg.samplingRate,
6756 mConfig.inputCfg.channels,
6757 mConfig.inputCfg.format);
6758 result.append(buffer);
6759
6760 result.append("\t\t- Output configuration:\n");
6761 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6762 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6763 (uint32_t)mConfig.outputCfg.buffer.raw,
6764 mConfig.outputCfg.buffer.frameCount,
6765 mConfig.outputCfg.samplingRate,
6766 mConfig.outputCfg.channels,
6767 mConfig.outputCfg.format);
6768 result.append(buffer);
6769
6770 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6771 result.append(buffer);
6772 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6773 for (size_t i = 0; i < mHandles.size(); ++i) {
6774 sp<EffectHandle> handle = mHandles[i].promote();
6775 if (handle != 0) {
6776 handle->dump(buffer, SIZE);
6777 result.append(buffer);
6778 }
6779 }
6780
6781 result.append("\n");
6782
6783 write(fd, result.string(), result.length());
6784
6785 if (locked) {
6786 mLock.unlock();
6787 }
6788
6789 return NO_ERROR;
6790}
6791
6792// ----------------------------------------------------------------------------
6793// EffectHandle implementation
6794// ----------------------------------------------------------------------------
6795
6796#undef LOG_TAG
6797#define LOG_TAG "AudioFlinger::EffectHandle"
6798
6799AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6800 const sp<AudioFlinger::Client>& client,
6801 const sp<IEffectClient>& effectClient,
6802 int32_t priority)
6803 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006804 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006805 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806{
Steve Block3856b092011-10-20 11:56:00 +01006807 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006809 if (client == 0) {
6810 return;
6811 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6813 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6814 if (mCblkMemory != 0) {
6815 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6816
6817 if (mCblk) {
6818 new(mCblk) effect_param_cblk_t();
6819 mBuffer = (uint8_t *)mCblk + bufOffset;
6820 }
6821 } else {
6822 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6823 return;
6824 }
6825}
6826
6827AudioFlinger::EffectHandle::~EffectHandle()
6828{
Steve Block3856b092011-10-20 11:56:00 +01006829 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006830 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006831 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832}
6833
6834status_t AudioFlinger::EffectHandle::enable()
6835{
Steve Block3856b092011-10-20 11:56:00 +01006836 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (!mHasControl) return INVALID_OPERATION;
6838 if (mEffect == 0) return DEAD_OBJECT;
6839
Eric Laurentdb7c0792011-08-10 10:37:50 -07006840 if (mEnabled) {
6841 return NO_ERROR;
6842 }
6843
Eric Laurent59255e42011-07-27 19:49:51 -07006844 mEnabled = true;
6845
6846 sp<ThreadBase> thread = mEffect->thread().promote();
6847 if (thread != 0) {
6848 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6849 }
6850
6851 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6852 if (mEffect->suspended()) {
6853 return NO_ERROR;
6854 }
6855
Eric Laurentdb7c0792011-08-10 10:37:50 -07006856 status_t status = mEffect->setEnabled(true);
6857 if (status != NO_ERROR) {
6858 if (thread != 0) {
6859 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6860 }
6861 mEnabled = false;
6862 }
6863 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864}
6865
6866status_t AudioFlinger::EffectHandle::disable()
6867{
Steve Block3856b092011-10-20 11:56:00 +01006868 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006870 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871
Eric Laurentdb7c0792011-08-10 10:37:50 -07006872 if (!mEnabled) {
6873 return NO_ERROR;
6874 }
Eric Laurent59255e42011-07-27 19:49:51 -07006875 mEnabled = false;
6876
6877 if (mEffect->suspended()) {
6878 return NO_ERROR;
6879 }
6880
6881 status_t status = mEffect->setEnabled(false);
6882
6883 sp<ThreadBase> thread = mEffect->thread().promote();
6884 if (thread != 0) {
6885 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6886 }
6887
6888 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889}
6890
6891void AudioFlinger::EffectHandle::disconnect()
6892{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006893 disconnect(true);
6894}
6895
6896void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6897{
Steve Block3856b092011-10-20 11:56:00 +01006898 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 if (mEffect == 0) {
6900 return;
6901 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006902 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006903
Eric Laurenta85a74a2011-10-19 11:44:54 -07006904 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006905 sp<ThreadBase> thread = mEffect->thread().promote();
6906 if (thread != 0) {
6907 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6908 }
Eric Laurent59255e42011-07-27 19:49:51 -07006909 }
6910
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 // release sp on module => module destructor can be called now
6912 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006914 if (mCblk) {
6915 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6916 }
6917 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6919 mClient.clear();
6920 }
6921}
6922
Eric Laurent25f43952010-07-28 05:40:18 -07006923status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6924 uint32_t cmdSize,
6925 void *pCmdData,
6926 uint32_t *replySize,
6927 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928{
Steve Block3856b092011-10-20 11:56:00 +01006929// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006930// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931
6932 // only get parameter command is permitted for applications not controlling the effect
6933 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6934 return INVALID_OPERATION;
6935 }
6936 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006937 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938
6939 // handle commands that are not forwarded transparently to effect engine
6940 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6941 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6942 // no risk to block the whole media server process or mixer threads is we are stuck here
6943 Mutex::Autolock _l(mCblk->lock);
6944 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6945 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6946 mCblk->serverIndex = 0;
6947 mCblk->clientIndex = 0;
6948 return BAD_VALUE;
6949 }
6950 status_t status = NO_ERROR;
6951 while (mCblk->serverIndex < mCblk->clientIndex) {
6952 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006953 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954 int *p = (int *)(mBuffer + mCblk->serverIndex);
6955 int size = *p++;
6956 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6957 LOGW("command(): invalid parameter block size");
6958 break;
6959 }
6960 effect_param_t *param = (effect_param_t *)p;
6961 if (param->psize == 0 || param->vsize == 0) {
6962 LOGW("command(): null parameter or value size");
6963 mCblk->serverIndex += size;
6964 continue;
6965 }
Eric Laurent25f43952010-07-28 05:40:18 -07006966 uint32_t psize = sizeof(effect_param_t) +
6967 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6968 param->vsize;
6969 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6970 psize,
6971 p,
6972 &rsize,
6973 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006974 // stop at first error encountered
6975 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006977 *(int *)pReplyData = reply;
6978 break;
6979 } else if (reply != NO_ERROR) {
6980 *(int *)pReplyData = reply;
6981 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 }
6983 mCblk->serverIndex += size;
6984 }
6985 mCblk->serverIndex = 0;
6986 mCblk->clientIndex = 0;
6987 return status;
6988 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006989 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990 return enable();
6991 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006992 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 return disable();
6994 }
6995
6996 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6997}
6998
6999sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7000 return mCblkMemory;
7001}
7002
Eric Laurent59255e42011-07-27 19:49:51 -07007003void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004{
Steve Block3856b092011-10-20 11:56:00 +01007005 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006
7007 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007008 mEnabled = enabled;
7009
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010 if (signal && mEffectClient != 0) {
7011 mEffectClient->controlStatusChanged(hasControl);
7012 }
7013}
7014
Eric Laurent25f43952010-07-28 05:40:18 -07007015void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7016 uint32_t cmdSize,
7017 void *pCmdData,
7018 uint32_t replySize,
7019 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020{
7021 if (mEffectClient != 0) {
7022 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7023 }
7024}
7025
7026
7027
7028void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7029{
7030 if (mEffectClient != 0) {
7031 mEffectClient->enableStatusChanged(enabled);
7032 }
7033}
7034
7035status_t AudioFlinger::EffectHandle::onTransact(
7036 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7037{
7038 return BnEffect::onTransact(code, data, reply, flags);
7039}
7040
7041
7042void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7043{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007044 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045
7046 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7047 (mClient == NULL) ? getpid() : mClient->pid(),
7048 mPriority,
7049 mHasControl,
7050 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007051 mCblk ? mCblk->clientIndex : 0,
7052 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 );
7054
7055 if (locked) {
7056 mCblk->lock.unlock();
7057 }
7058}
7059
7060#undef LOG_TAG
7061#define LOG_TAG "AudioFlinger::EffectChain"
7062
7063AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7064 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007065 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007066 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7067 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068{
Dima Zavinfce7a472011-04-19 22:30:36 -07007069 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007070 sp<ThreadBase> thread = mThread.promote();
7071 if (thread == 0) {
7072 return;
7073 }
7074 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7075 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076}
7077
7078AudioFlinger::EffectChain::~EffectChain()
7079{
7080 if (mOwnInBuffer) {
7081 delete mInBuffer;
7082 }
7083
7084}
7085
Eric Laurent59255e42011-07-27 19:49:51 -07007086// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007087sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088{
7089 sp<EffectModule> effect;
7090 size_t size = mEffects.size();
7091
7092 for (size_t i = 0; i < size; i++) {
7093 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7094 effect = mEffects[i];
7095 break;
7096 }
7097 }
7098 return effect;
7099}
7100
Eric Laurent59255e42011-07-27 19:49:51 -07007101// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007102sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103{
7104 sp<EffectModule> effect;
7105 size_t size = mEffects.size();
7106
7107 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007108 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7109 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110 effect = mEffects[i];
7111 break;
7112 }
7113 }
7114 return effect;
7115}
7116
Eric Laurent59255e42011-07-27 19:49:51 -07007117// getEffectFromType_l() must be called with ThreadBase::mLock held
7118sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7119 const effect_uuid_t *type)
7120{
7121 sp<EffectModule> effect;
7122 size_t size = mEffects.size();
7123
7124 for (size_t i = 0; i < size; i++) {
7125 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7126 effect = mEffects[i];
7127 break;
7128 }
7129 }
7130 return effect;
7131}
7132
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133// Must be called with EffectChain::mLock locked
7134void AudioFlinger::EffectChain::process_l()
7135{
Eric Laurentdac69112010-09-28 14:09:57 -07007136 sp<ThreadBase> thread = mThread.promote();
7137 if (thread == 0) {
7138 LOGW("process_l(): cannot promote mixer thread");
7139 return;
7140 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007141 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7142 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007143 // always process effects unless no more tracks are on the session and the effect tail
7144 // has been rendered
7145 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007146 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007147 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007148
Eric Laurent544fe9b2011-11-11 15:42:52 -08007149 if (!tracksOnSession && mTailBufferCount == 0) {
7150 doProcess = false;
7151 }
7152
7153 if (activeTrackCnt() == 0) {
7154 // if no track is active and the effect tail has not been rendered,
7155 // the input buffer must be cleared here as the mixer process will not do it
7156 if (tracksOnSession || mTailBufferCount > 0) {
7157 size_t numSamples = thread->frameCount() * thread->channelCount();
7158 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7159 if (mTailBufferCount > 0) {
7160 mTailBufferCount--;
7161 }
7162 }
7163 }
Eric Laurentdac69112010-09-28 14:09:57 -07007164 }
7165
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007167 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007168 for (size_t i = 0; i < size; i++) {
7169 mEffects[i]->process();
7170 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 }
7172 for (size_t i = 0; i < size; i++) {
7173 mEffects[i]->updateState();
7174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175}
7176
Eric Laurentcab11242010-07-15 12:50:15 -07007177// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007178status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179{
7180 effect_descriptor_t desc = effect->desc();
7181 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7182
7183 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007184 effect->setChain(this);
7185 sp<ThreadBase> thread = mThread.promote();
7186 if (thread == 0) {
7187 return NO_INIT;
7188 }
7189 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190
7191 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7192 // Auxiliary effects are inserted at the beginning of mEffects vector as
7193 // they are processed first and accumulated in chain input buffer
7194 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007195
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196 // the input buffer for auxiliary effect contains mono samples in
7197 // 32 bit format. This is to avoid saturation in AudoMixer
7198 // accumulation stage. Saturation is done in EffectModule::process() before
7199 // calling the process in effect engine
7200 size_t numSamples = thread->frameCount();
7201 int32_t *buffer = new int32_t[numSamples];
7202 memset(buffer, 0, numSamples * sizeof(int32_t));
7203 effect->setInBuffer((int16_t *)buffer);
7204 // auxiliary effects output samples to chain input buffer for further processing
7205 // by insert effects
7206 effect->setOutBuffer(mInBuffer);
7207 } else {
7208 // Insert effects are inserted at the end of mEffects vector as they are processed
7209 // after track and auxiliary effects.
7210 // Insert effect order as a function of indicated preference:
7211 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7212 // another effect is present
7213 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7214 // last effect claiming first position
7215 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7216 // first effect claiming last position
7217 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7218 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7219 // already present
7220
7221 int size = (int)mEffects.size();
7222 int idx_insert = size;
7223 int idx_insert_first = -1;
7224 int idx_insert_last = -1;
7225
7226 for (int i = 0; i < size; i++) {
7227 effect_descriptor_t d = mEffects[i]->desc();
7228 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7229 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7230 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7231 // check invalid effect chaining combinations
7232 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7233 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007234 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235 return INVALID_OPERATION;
7236 }
7237 // remember position of first insert effect and by default
7238 // select this as insert position for new effect
7239 if (idx_insert == size) {
7240 idx_insert = i;
7241 }
7242 // remember position of last insert effect claiming
7243 // first position
7244 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7245 idx_insert_first = i;
7246 }
7247 // remember position of first insert effect claiming
7248 // last position
7249 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7250 idx_insert_last == -1) {
7251 idx_insert_last = i;
7252 }
7253 }
7254 }
7255
7256 // modify idx_insert from first position if needed
7257 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7258 if (idx_insert_last != -1) {
7259 idx_insert = idx_insert_last;
7260 } else {
7261 idx_insert = size;
7262 }
7263 } else {
7264 if (idx_insert_first != -1) {
7265 idx_insert = idx_insert_first + 1;
7266 }
7267 }
7268
7269 // always read samples from chain input buffer
7270 effect->setInBuffer(mInBuffer);
7271
7272 // if last effect in the chain, output samples to chain
7273 // output buffer, otherwise to chain input buffer
7274 if (idx_insert == size) {
7275 if (idx_insert != 0) {
7276 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7277 mEffects[idx_insert-1]->configure();
7278 }
7279 effect->setOutBuffer(mOutBuffer);
7280 } else {
7281 effect->setOutBuffer(mInBuffer);
7282 }
7283 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284
Steve Block3856b092011-10-20 11:56:00 +01007285 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 }
7287 effect->configure();
7288 return NO_ERROR;
7289}
7290
Eric Laurentcab11242010-07-15 12:50:15 -07007291// removeEffect_l() must be called with PlaybackThread::mLock held
7292size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293{
7294 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 int size = (int)mEffects.size();
7296 int i;
7297 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7298
7299 for (i = 0; i < size; i++) {
7300 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007301 // calling stop here will remove pre-processing effect from the audio HAL.
7302 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7303 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007304 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7305 mEffects[i]->state() == EffectModule::STOPPING) {
7306 mEffects[i]->stop();
7307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7309 delete[] effect->inBuffer();
7310 } else {
7311 if (i == size - 1 && i != 0) {
7312 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7313 mEffects[i - 1]->configure();
7314 }
7315 }
7316 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007317 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 break;
7319 }
7320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321
7322 return mEffects.size();
7323}
7324
Eric Laurentcab11242010-07-15 12:50:15 -07007325// setDevice_l() must be called with PlaybackThread::mLock held
7326void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327{
7328 size_t size = mEffects.size();
7329 for (size_t i = 0; i < size; i++) {
7330 mEffects[i]->setDevice(device);
7331 }
7332}
7333
Eric Laurentcab11242010-07-15 12:50:15 -07007334// setMode_l() must be called with PlaybackThread::mLock held
7335void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336{
7337 size_t size = mEffects.size();
7338 for (size_t i = 0; i < size; i++) {
7339 mEffects[i]->setMode(mode);
7340 }
7341}
7342
Eric Laurentcab11242010-07-15 12:50:15 -07007343// setVolume_l() must be called with PlaybackThread::mLock held
7344bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345{
7346 uint32_t newLeft = *left;
7347 uint32_t newRight = *right;
7348 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007349 int ctrlIdx = -1;
7350 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351
Eric Laurentcab11242010-07-15 12:50:15 -07007352 // first update volume controller
7353 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007354 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007355 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7356 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007357 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007358 break;
7359 }
7360 }
7361
7362 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007363 if (hasControl) {
7364 *left = mNewLeftVolume;
7365 *right = mNewRightVolume;
7366 }
7367 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007368 }
7369
7370 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007371 mLeftVolume = newLeft;
7372 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007373
7374 // second get volume update from volume controller
7375 if (ctrlIdx >= 0) {
7376 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007377 mNewLeftVolume = newLeft;
7378 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 }
7380 // then indicate volume to all other effects in chain.
7381 // Pass altered volume to effects before volume controller
7382 // and requested volume to effects after controller
7383 uint32_t lVol = newLeft;
7384 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007385
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007387 if ((int)i == ctrlIdx) continue;
7388 // this also works for ctrlIdx == -1 when there is no volume controller
7389 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 lVol = *left;
7391 rVol = *right;
7392 }
7393 mEffects[i]->setVolume(&lVol, &rVol, false);
7394 }
7395 *left = newLeft;
7396 *right = newRight;
7397
7398 return hasControl;
7399}
7400
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7402{
7403 const size_t SIZE = 256;
7404 char buffer[SIZE];
7405 String8 result;
7406
7407 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7408 result.append(buffer);
7409
7410 bool locked = tryLock(mLock);
7411 // failed to lock - AudioFlinger is probably deadlocked
7412 if (!locked) {
7413 result.append("\tCould not lock mutex:\n");
7414 }
7415
Eric Laurentcab11242010-07-15 12:50:15 -07007416 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7417 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 mEffects.size(),
7419 (uint32_t)mInBuffer,
7420 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 mActiveTrackCnt);
7422 result.append(buffer);
7423 write(fd, result.string(), result.size());
7424
7425 for (size_t i = 0; i < mEffects.size(); ++i) {
7426 sp<EffectModule> effect = mEffects[i];
7427 if (effect != 0) {
7428 effect->dump(fd, args);
7429 }
7430 }
7431
7432 if (locked) {
7433 mLock.unlock();
7434 }
7435
7436 return NO_ERROR;
7437}
7438
Eric Laurent59255e42011-07-27 19:49:51 -07007439// must be called with ThreadBase::mLock held
7440void AudioFlinger::EffectChain::setEffectSuspended_l(
7441 const effect_uuid_t *type, bool suspend)
7442{
7443 sp<SuspendedEffectDesc> desc;
7444 // use effect type UUID timelow as key as there is no real risk of identical
7445 // timeLow fields among effect type UUIDs.
7446 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7447 if (suspend) {
7448 if (index >= 0) {
7449 desc = mSuspendedEffects.valueAt(index);
7450 } else {
7451 desc = new SuspendedEffectDesc();
7452 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7453 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007454 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007455 }
7456 if (desc->mRefCount++ == 0) {
7457 sp<EffectModule> effect = getEffectIfEnabled(type);
7458 if (effect != 0) {
7459 desc->mEffect = effect;
7460 effect->setSuspended(true);
7461 effect->setEnabled(false);
7462 }
7463 }
7464 } else {
7465 if (index < 0) {
7466 return;
7467 }
7468 desc = mSuspendedEffects.valueAt(index);
7469 if (desc->mRefCount <= 0) {
7470 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7471 desc->mRefCount = 1;
7472 }
7473 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007474 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007475 if (desc->mEffect != 0) {
7476 sp<EffectModule> effect = desc->mEffect.promote();
7477 if (effect != 0) {
7478 effect->setSuspended(false);
7479 sp<EffectHandle> handle = effect->controlHandle();
7480 if (handle != 0) {
7481 effect->setEnabled(handle->enabled());
7482 }
7483 }
7484 desc->mEffect.clear();
7485 }
7486 mSuspendedEffects.removeItemsAt(index);
7487 }
7488 }
7489}
7490
7491// must be called with ThreadBase::mLock held
7492void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7493{
7494 sp<SuspendedEffectDesc> desc;
7495
7496 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7497 if (suspend) {
7498 if (index >= 0) {
7499 desc = mSuspendedEffects.valueAt(index);
7500 } else {
7501 desc = new SuspendedEffectDesc();
7502 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007503 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007504 }
7505 if (desc->mRefCount++ == 0) {
7506 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7507 for (size_t i = 0; i < effects.size(); i++) {
7508 setEffectSuspended_l(&effects[i]->desc().type, true);
7509 }
7510 }
7511 } else {
7512 if (index < 0) {
7513 return;
7514 }
7515 desc = mSuspendedEffects.valueAt(index);
7516 if (desc->mRefCount <= 0) {
7517 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7518 desc->mRefCount = 1;
7519 }
7520 if (--desc->mRefCount == 0) {
7521 Vector<const effect_uuid_t *> types;
7522 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7523 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7524 continue;
7525 }
7526 types.add(&mSuspendedEffects.valueAt(i)->mType);
7527 }
7528 for (size_t i = 0; i < types.size(); i++) {
7529 setEffectSuspended_l(types[i], false);
7530 }
Steve Block3856b092011-10-20 11:56:00 +01007531 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007532 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7533 }
7534 }
7535}
7536
Eric Laurent6bffdb82011-09-23 08:40:41 -07007537
7538// The volume effect is used for automated tests only
7539#ifndef OPENSL_ES_H_
7540static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7541 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7542const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7543#endif //OPENSL_ES_H_
7544
Eric Laurentdb7c0792011-08-10 10:37:50 -07007545bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7546{
7547 // auxiliary effects and visualizer are never suspended on output mix
7548 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7549 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007550 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7551 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007552 return false;
7553 }
7554 return true;
7555}
7556
Eric Laurent59255e42011-07-27 19:49:51 -07007557Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7558{
7559 Vector< sp<EffectModule> > effects;
7560 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007561 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007562 continue;
7563 }
7564 effects.add(mEffects[i]);
7565 }
7566 return effects;
7567}
7568
7569sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7570 const effect_uuid_t *type)
7571{
7572 sp<EffectModule> effect;
7573 effect = getEffectFromType_l(type);
7574 if (effect != 0 && !effect->isEnabled()) {
7575 effect.clear();
7576 }
7577 return effect;
7578}
7579
7580void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7581 bool enabled)
7582{
7583 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7584 if (enabled) {
7585 if (index < 0) {
7586 // if the effect is not suspend check if all effects are suspended
7587 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7588 if (index < 0) {
7589 return;
7590 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007591 if (!isEffectEligibleForSuspend(effect->desc())) {
7592 return;
7593 }
Eric Laurent59255e42011-07-27 19:49:51 -07007594 setEffectSuspended_l(&effect->desc().type, enabled);
7595 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007596 if (index < 0) {
7597 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7598 return;
7599 }
Eric Laurent59255e42011-07-27 19:49:51 -07007600 }
Steve Block3856b092011-10-20 11:56:00 +01007601 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007602 effect->desc().type.timeLow);
7603 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7604 // if effect is requested to suspended but was not yet enabled, supend it now.
7605 if (desc->mEffect == 0) {
7606 desc->mEffect = effect;
7607 effect->setEnabled(false);
7608 effect->setSuspended(true);
7609 }
7610 } else {
7611 if (index < 0) {
7612 return;
7613 }
Steve Block3856b092011-10-20 11:56:00 +01007614 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007615 effect->desc().type.timeLow);
7616 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7617 desc->mEffect.clear();
7618 effect->setSuspended(false);
7619 }
7620}
7621
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622#undef LOG_TAG
7623#define LOG_TAG "AudioFlinger"
7624
7625// ----------------------------------------------------------------------------
7626
7627status_t AudioFlinger::onTransact(
7628 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7629{
7630 return BnAudioFlinger::onTransact(code, data, reply, flags);
7631}
7632
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633}; // namespace android