blob: 60d27731f1d4f397dc79c769960e01be0f309e06 [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;
Glenn Kasten7dede872011-12-13 11:04:14 -080083static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070084
Glenn Kasten7dede872011-12-13 11:04:14 -080085// don't warn about blocked writes or record buffer overflows more often than this
86static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Eric Laurent7c7f10b2011-06-17 21:29:58 -070088// RecordThread loop sleep time upon application overrun or audio HAL read error
89static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Glenn Kasten7dede872011-12-13 11:04:14 -080091// maximum time to wait for setParameters to complete
92static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070093
Eric Laurent7cafbb32011-11-22 18:50:29 -080094// minimum sleep time for the mixer thread loop when tracks are active but in underrun
95static const uint32_t kMinThreadSleepTimeUs = 5000;
96// maximum divider applied to the active sleep time in the mixer thread loop
97static const uint32_t kMaxThreadSleepTimeShift = 2;
98
99
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100// ----------------------------------------------------------------------------
101
102static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
105 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
106 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107}
108
109static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
111 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
112 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
113 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114}
115
Gloria Wang9ee159b2011-02-24 14:51:45 -0800116// To collect the amplifier usage
117static void addBatteryData(uint32_t params) {
118 sp<IBinder> binder =
119 defaultServiceManager()->getService(String16("media.player"));
120 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
121 if (service.get() == NULL) {
122 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
123 return;
124 }
125
126 service->addBatteryData(params);
127}
128
Dima Zavin799a70e2011-04-18 16:57:27 -0700129static int load_audio_interface(const char *if_name, const hw_module_t **mod,
130 audio_hw_device_t **dev)
131{
132 int rc;
133
134 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
135 if (rc)
136 goto out;
137
138 rc = audio_hw_device_open(*mod, dev);
139 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
140 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
141 if (rc)
142 goto out;
143
144 return 0;
145
146out:
147 *mod = NULL;
148 *dev = NULL;
149 return rc;
150}
151
152static const char *audio_interfaces[] = {
153 "primary",
154 "a2dp",
155 "usb",
156};
157#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
158
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159// ----------------------------------------------------------------------------
160
161AudioFlinger::AudioFlinger()
162 : BnAudioFlinger(),
Eric Laurent59bd0da2011-08-01 09:52:20 -0700163 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700164 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700165{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700166}
167
168void AudioFlinger::onFirstRef()
169{
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700171
Eric Laurent93575202011-01-18 18:39:02 -0800172 Mutex::Autolock _l(mLock);
173
Dima Zavin799a70e2011-04-18 16:57:27 -0700174 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175 mHardwareStatus = AUDIO_HW_IDLE;
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
178 const hw_module_t *mod;
179 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700180
Dima Zavin799a70e2011-04-18 16:57:27 -0700181 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
182 if (rc)
183 continue;
184
185 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
186 mod->name, mod->id);
187 mAudioHwDevs.push(dev);
188
189 if (!mPrimaryHardwareDev) {
190 mPrimaryHardwareDev = dev;
191 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700192 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700193 }
194 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700195
196 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700197
Dima Zavin799a70e2011-04-18 16:57:27 -0700198 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
199 LOGE("Primary audio interface not found");
200 return;
201 }
202
203 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
204 audio_hw_device_t *dev = mAudioHwDevs[i];
205
206 mHardwareStatus = AUDIO_HW_INIT;
207 rc = dev->init_check(dev);
208 if (rc == 0) {
209 AutoMutex lock(mHardwareLock);
210
211 mMode = AUDIO_MODE_NORMAL;
212 mHardwareStatus = AUDIO_HW_SET_MODE;
213 dev->set_mode(dev, mMode);
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 dev->set_master_volume(dev, 1.0f);
216 mHardwareStatus = AUDIO_HW_IDLE;
217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700218 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219}
220
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700221status_t AudioFlinger::initCheck() const
222{
223 Mutex::Autolock _l(mLock);
224 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
225 return NO_INIT;
226 return NO_ERROR;
227}
228
Mathias Agopian65ab4712010-07-14 17:59:35 -0700229AudioFlinger::~AudioFlinger()
230{
Dima Zavin799a70e2011-04-18 16:57:27 -0700231 int num_devs = mAudioHwDevs.size();
232
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 while (!mRecordThreads.isEmpty()) {
234 // closeInput() will remove first entry from mRecordThreads
235 closeInput(mRecordThreads.keyAt(0));
236 }
237 while (!mPlaybackThreads.isEmpty()) {
238 // closeOutput() will remove first entry from mPlaybackThreads
239 closeOutput(mPlaybackThreads.keyAt(0));
240 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700241
242 for (int i = 0; i < num_devs; i++) {
243 audio_hw_device_t *dev = mAudioHwDevs[i];
244 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700246 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247}
248
Dima Zavin799a70e2011-04-18 16:57:27 -0700249audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
250{
251 /* first matching HW device is returned */
252 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
253 audio_hw_device_t *dev = mAudioHwDevs[i];
254 if ((dev->get_supported_devices(dev) & devices) == devices)
255 return dev;
256 }
257 return NULL;
258}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700259
260status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
261{
262 const size_t SIZE = 256;
263 char buffer[SIZE];
264 String8 result;
265
266 result.append("Clients:\n");
267 for (size_t i = 0; i < mClients.size(); ++i) {
268 wp<Client> wClient = mClients.valueAt(i);
269 if (wClient != 0) {
270 sp<Client> client = wClient.promote();
271 if (client != 0) {
272 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
273 result.append(buffer);
274 }
275 }
276 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700277
278 result.append("Global session refs:\n");
279 result.append(" session pid cnt\n");
280 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
281 AudioSessionRef *r = mAudioSessionRefs[i];
282 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
283 result.append(buffer);
284 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700285 write(fd, result.string(), result.size());
286 return NO_ERROR;
287}
288
289
290status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
291{
292 const size_t SIZE = 256;
293 char buffer[SIZE];
294 String8 result;
295 int hardwareStatus = mHardwareStatus;
296
297 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
298 result.append(buffer);
299 write(fd, result.string(), result.size());
300 return NO_ERROR;
301}
302
303status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
304{
305 const size_t SIZE = 256;
306 char buffer[SIZE];
307 String8 result;
308 snprintf(buffer, SIZE, "Permission Denial: "
309 "can't dump AudioFlinger from pid=%d, uid=%d\n",
310 IPCThreadState::self()->getCallingPid(),
311 IPCThreadState::self()->getCallingUid());
312 result.append(buffer);
313 write(fd, result.string(), result.size());
314 return NO_ERROR;
315}
316
317static bool tryLock(Mutex& mutex)
318{
319 bool locked = false;
320 for (int i = 0; i < kDumpLockRetries; ++i) {
321 if (mutex.tryLock() == NO_ERROR) {
322 locked = true;
323 break;
324 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800325 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700326 }
327 return locked;
328}
329
330status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
331{
332 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
333 dumpPermissionDenial(fd, args);
334 } else {
335 // get state of hardware lock
336 bool hardwareLocked = tryLock(mHardwareLock);
337 if (!hardwareLocked) {
338 String8 result(kHardwareLockedString);
339 write(fd, result.string(), result.size());
340 } else {
341 mHardwareLock.unlock();
342 }
343
344 bool locked = tryLock(mLock);
345
346 // failed to lock - AudioFlinger is probably deadlocked
347 if (!locked) {
348 String8 result(kDeadlockedString);
349 write(fd, result.string(), result.size());
350 }
351
352 dumpClients(fd, args);
353 dumpInternals(fd, args);
354
355 // dump playback threads
356 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
357 mPlaybackThreads.valueAt(i)->dump(fd, args);
358 }
359
360 // dump record threads
361 for (size_t i = 0; i < mRecordThreads.size(); i++) {
362 mRecordThreads.valueAt(i)->dump(fd, args);
363 }
364
Dima Zavin799a70e2011-04-18 16:57:27 -0700365 // dump all hardware devs
366 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
367 audio_hw_device_t *dev = mAudioHwDevs[i];
368 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369 }
370 if (locked) mLock.unlock();
371 }
372 return NO_ERROR;
373}
374
375
376// IAudioFlinger interface
377
378
379sp<IAudioTrack> AudioFlinger::createTrack(
380 pid_t pid,
381 int streamType,
382 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700383 uint32_t format,
384 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700385 int frameCount,
386 uint32_t flags,
387 const sp<IMemory>& sharedBuffer,
388 int output,
389 int *sessionId,
390 status_t *status)
391{
392 sp<PlaybackThread::Track> track;
393 sp<TrackHandle> trackHandle;
394 sp<Client> client;
395 wp<Client> wclient;
396 status_t lStatus;
397 int lSessionId;
398
Dima Zavinfce7a472011-04-19 22:30:36 -0700399 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700400 LOGE("invalid stream type");
401 lStatus = BAD_VALUE;
402 goto Exit;
403 }
404
405 {
406 Mutex::Autolock _l(mLock);
407 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700408 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700409 if (thread == NULL) {
410 LOGE("unknown output thread");
411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414
415 wclient = mClients.valueFor(pid);
416
417 if (wclient != NULL) {
418 client = wclient.promote();
419 } else {
420 client = new Client(this, pid);
421 mClients.add(pid, client);
422 }
423
Steve Block3856b092011-10-20 11:56:00 +0100424 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700425 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700426 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700427 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
428 if (mPlaybackThreads.keyAt(i) != output) {
429 // prevent same audio session on different output threads
430 uint32_t sessions = t->hasAudioSession(*sessionId);
431 if (sessions & PlaybackThread::TRACK_SESSION) {
432 lStatus = BAD_VALUE;
433 goto Exit;
434 }
435 // check if an effect with same session ID is waiting for a track to be created
436 if (sessions & PlaybackThread::EFFECT_SESSION) {
437 effectThread = t.get();
438 }
Eric Laurentde070132010-07-13 04:45:46 -0700439 }
440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 lSessionId = *sessionId;
442 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700443 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700444 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 if (sessionId != NULL) {
446 *sessionId = lSessionId;
447 }
448 }
Steve Block3856b092011-10-20 11:56:00 +0100449 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700450
451 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700452 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700453
454 // move effect chain to this output thread if an effect on same session was waiting
455 // for a track to be created
456 if (lStatus == NO_ERROR && effectThread != NULL) {
457 Mutex::Autolock _dl(thread->mLock);
458 Mutex::Autolock _sl(effectThread->mLock);
459 moveEffectChain_l(lSessionId, effectThread, thread, true);
460 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700461 }
462 if (lStatus == NO_ERROR) {
463 trackHandle = new TrackHandle(track);
464 } else {
465 // remove local strong reference to Client before deleting the Track so that the Client
466 // destructor is called by the TrackBase destructor with mLock held
467 client.clear();
468 track.clear();
469 }
470
471Exit:
472 if(status) {
473 *status = lStatus;
474 }
475 return trackHandle;
476}
477
478uint32_t AudioFlinger::sampleRate(int output) const
479{
480 Mutex::Autolock _l(mLock);
481 PlaybackThread *thread = checkPlaybackThread_l(output);
482 if (thread == NULL) {
483 LOGW("sampleRate() unknown thread %d", output);
484 return 0;
485 }
486 return thread->sampleRate();
487}
488
489int AudioFlinger::channelCount(int output) const
490{
491 Mutex::Autolock _l(mLock);
492 PlaybackThread *thread = checkPlaybackThread_l(output);
493 if (thread == NULL) {
494 LOGW("channelCount() unknown thread %d", output);
495 return 0;
496 }
497 return thread->channelCount();
498}
499
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700500uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700501{
502 Mutex::Autolock _l(mLock);
503 PlaybackThread *thread = checkPlaybackThread_l(output);
504 if (thread == NULL) {
505 LOGW("format() unknown thread %d", output);
506 return 0;
507 }
508 return thread->format();
509}
510
511size_t AudioFlinger::frameCount(int output) const
512{
513 Mutex::Autolock _l(mLock);
514 PlaybackThread *thread = checkPlaybackThread_l(output);
515 if (thread == NULL) {
516 LOGW("frameCount() unknown thread %d", output);
517 return 0;
518 }
519 return thread->frameCount();
520}
521
522uint32_t AudioFlinger::latency(int output) const
523{
524 Mutex::Autolock _l(mLock);
525 PlaybackThread *thread = checkPlaybackThread_l(output);
526 if (thread == NULL) {
527 LOGW("latency() unknown thread %d", output);
528 return 0;
529 }
530 return thread->latency();
531}
532
533status_t AudioFlinger::setMasterVolume(float value)
534{
Eric Laurenta1884f92011-08-23 08:25:03 -0700535 status_t ret = initCheck();
536 if (ret != NO_ERROR) {
537 return ret;
538 }
539
Mathias Agopian65ab4712010-07-14 17:59:35 -0700540 // check calling permissions
541 if (!settingsAllowed()) {
542 return PERMISSION_DENIED;
543 }
544
545 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800546 { // scope for the lock
547 AutoMutex lock(mHardwareLock);
548 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700549 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800550 value = 1.0f;
551 }
552 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554
Eric Laurent93575202011-01-18 18:39:02 -0800555 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 mMasterVolume = value;
557 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
558 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
559
560 return NO_ERROR;
561}
562
563status_t AudioFlinger::setMode(int mode)
564{
Eric Laurenta1884f92011-08-23 08:25:03 -0700565 status_t ret = initCheck();
566 if (ret != NO_ERROR) {
567 return ret;
568 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700569
570 // check calling permissions
571 if (!settingsAllowed()) {
572 return PERMISSION_DENIED;
573 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700574 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 LOGW("Illegal value: setMode(%d)", mode);
576 return BAD_VALUE;
577 }
578
579 { // scope for the lock
580 AutoMutex lock(mHardwareLock);
581 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700582 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 mHardwareStatus = AUDIO_HW_IDLE;
584 }
585
586 if (NO_ERROR == ret) {
587 Mutex::Autolock _l(mLock);
588 mMode = mode;
589 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
590 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700591 }
592
593 return ret;
594}
595
596status_t AudioFlinger::setMicMute(bool state)
597{
Eric Laurenta1884f92011-08-23 08:25:03 -0700598 status_t ret = initCheck();
599 if (ret != NO_ERROR) {
600 return ret;
601 }
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
608 AutoMutex lock(mHardwareLock);
609 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700610 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611 mHardwareStatus = AUDIO_HW_IDLE;
612 return ret;
613}
614
615bool AudioFlinger::getMicMute() const
616{
Eric Laurenta1884f92011-08-23 08:25:03 -0700617 status_t ret = initCheck();
618 if (ret != NO_ERROR) {
619 return false;
620 }
621
Dima Zavinfce7a472011-04-19 22:30:36 -0700622 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700624 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 return state;
627}
628
629status_t AudioFlinger::setMasterMute(bool muted)
630{
631 // check calling permissions
632 if (!settingsAllowed()) {
633 return PERMISSION_DENIED;
634 }
635
Eric Laurent93575202011-01-18 18:39:02 -0800636 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700637 mMasterMute = muted;
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
639 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
640
641 return NO_ERROR;
642}
643
644float AudioFlinger::masterVolume() const
645{
646 return mMasterVolume;
647}
648
649bool AudioFlinger::masterMute() const
650{
651 return mMasterMute;
652}
653
654status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
655{
656 // check calling permissions
657 if (!settingsAllowed()) {
658 return PERMISSION_DENIED;
659 }
660
Dima Zavinfce7a472011-04-19 22:30:36 -0700661 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 return BAD_VALUE;
663 }
664
665 AutoMutex lock(mLock);
666 PlaybackThread *thread = NULL;
667 if (output) {
668 thread = checkPlaybackThread_l(output);
669 if (thread == NULL) {
670 return BAD_VALUE;
671 }
672 }
673
674 mStreamTypes[stream].volume = value;
675
676 if (thread == NULL) {
677 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
678 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
679 }
680 } else {
681 thread->setStreamVolume(stream, value);
682 }
683
684 return NO_ERROR;
685}
686
687status_t AudioFlinger::setStreamMute(int stream, bool muted)
688{
689 // check calling permissions
690 if (!settingsAllowed()) {
691 return PERMISSION_DENIED;
692 }
693
Dima Zavinfce7a472011-04-19 22:30:36 -0700694 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
695 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700696 return BAD_VALUE;
697 }
698
Eric Laurent93575202011-01-18 18:39:02 -0800699 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700700 mStreamTypes[stream].mute = muted;
701 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
702 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
703
704 return NO_ERROR;
705}
706
707float AudioFlinger::streamVolume(int stream, int output) const
708{
Dima Zavinfce7a472011-04-19 22:30:36 -0700709 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 return 0.0f;
711 }
712
713 AutoMutex lock(mLock);
714 float volume;
715 if (output) {
716 PlaybackThread *thread = checkPlaybackThread_l(output);
717 if (thread == NULL) {
718 return 0.0f;
719 }
720 volume = thread->streamVolume(stream);
721 } else {
722 volume = mStreamTypes[stream].volume;
723 }
724
725 return volume;
726}
727
728bool AudioFlinger::streamMute(int stream) const
729{
Dima Zavinfce7a472011-04-19 22:30:36 -0700730 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700731 return true;
732 }
733
734 return mStreamTypes[stream].mute;
735}
736
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
738{
739 status_t result;
740
Steve Block3856b092011-10-20 11:56:00 +0100741 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
743 // check calling permissions
744 if (!settingsAllowed()) {
745 return PERMISSION_DENIED;
746 }
747
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 // ioHandle == 0 means the parameters are global to the audio hardware interface
749 if (ioHandle == 0) {
750 AutoMutex lock(mHardwareLock);
751 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700752 status_t final_result = NO_ERROR;
753 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
754 audio_hw_device_t *dev = mAudioHwDevs[i];
755 result = dev->set_parameters(dev, keyValuePairs.string());
756 final_result = result ?: final_result;
757 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700759 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
760 AudioParameter param = AudioParameter(keyValuePairs);
761 String8 value;
762 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
763 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700764 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
765 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700766 for (size_t i = 0; i < mRecordThreads.size(); i++) {
767 sp<RecordThread> thread = mRecordThreads.valueAt(i);
768 RecordThread::RecordTrack *track = thread->track();
769 if (track != NULL) {
770 audio_devices_t device = (audio_devices_t)(
771 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700772 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700773 thread->setEffectSuspended(FX_IID_AEC,
774 suspend,
775 track->sessionId());
776 thread->setEffectSuspended(FX_IID_NS,
777 suspend,
778 track->sessionId());
779 }
780 }
Eric Laurentbee53372011-08-29 12:42:48 -0700781 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700782 }
783 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700784 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700785 }
786
787 // hold a strong ref on thread in case closeOutput() or closeInput() is called
788 // and the thread is exited once the lock is released
789 sp<ThreadBase> thread;
790 {
791 Mutex::Autolock _l(mLock);
792 thread = checkPlaybackThread_l(ioHandle);
793 if (thread == NULL) {
794 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700795 } else if (thread.get() == primaryPlaybackThread_l()) {
796 // indicate output device change to all input threads for pre processing
797 AudioParameter param = AudioParameter(keyValuePairs);
798 int value;
799 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
800 for (size_t i = 0; i < mRecordThreads.size(); i++) {
801 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
802 }
803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700804 }
805 }
806 if (thread != NULL) {
807 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 return result;
809 }
810 return BAD_VALUE;
811}
812
813String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
814{
Steve Block3856b092011-10-20 11:56:00 +0100815// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700816// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
817
818 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700819 String8 out_s8;
820
Dima Zavin799a70e2011-04-18 16:57:27 -0700821 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
822 audio_hw_device_t *dev = mAudioHwDevs[i];
823 char *s = dev->get_parameters(dev, keys.string());
824 out_s8 += String8(s);
825 free(s);
826 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700827 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700828 }
829
830 Mutex::Autolock _l(mLock);
831
832 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
833 if (playbackThread != NULL) {
834 return playbackThread->getParameters(keys);
835 }
836 RecordThread *recordThread = checkRecordThread_l(ioHandle);
837 if (recordThread != NULL) {
838 return recordThread->getParameters(keys);
839 }
840 return String8("");
841}
842
843size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
844{
Eric Laurenta1884f92011-08-23 08:25:03 -0700845 status_t ret = initCheck();
846 if (ret != NO_ERROR) {
847 return 0;
848 }
849
Dima Zavin799a70e2011-04-18 16:57:27 -0700850 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851}
852
853unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
854{
855 if (ioHandle == 0) {
856 return 0;
857 }
858
859 Mutex::Autolock _l(mLock);
860
861 RecordThread *recordThread = checkRecordThread_l(ioHandle);
862 if (recordThread != NULL) {
863 return recordThread->getInputFramesLost();
864 }
865 return 0;
866}
867
868status_t AudioFlinger::setVoiceVolume(float value)
869{
Eric Laurenta1884f92011-08-23 08:25:03 -0700870 status_t ret = initCheck();
871 if (ret != NO_ERROR) {
872 return ret;
873 }
874
Mathias Agopian65ab4712010-07-14 17:59:35 -0700875 // check calling permissions
876 if (!settingsAllowed()) {
877 return PERMISSION_DENIED;
878 }
879
880 AutoMutex lock(mHardwareLock);
881 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700882 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883 mHardwareStatus = AUDIO_HW_IDLE;
884
885 return ret;
886}
887
888status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
889{
890 status_t status;
891
892 Mutex::Autolock _l(mLock);
893
894 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
895 if (playbackThread != NULL) {
896 return playbackThread->getRenderPosition(halFrames, dspFrames);
897 }
898
899 return BAD_VALUE;
900}
901
902void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
903{
904
905 Mutex::Autolock _l(mLock);
906
907 int pid = IPCThreadState::self()->getCallingPid();
908 if (mNotificationClients.indexOfKey(pid) < 0) {
909 sp<NotificationClient> notificationClient = new NotificationClient(this,
910 client,
911 pid);
Steve Block3856b092011-10-20 11:56:00 +0100912 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913
914 mNotificationClients.add(pid, notificationClient);
915
916 sp<IBinder> binder = client->asBinder();
917 binder->linkToDeath(notificationClient);
918
919 // the config change is always sent from playback or record threads to avoid deadlock
920 // with AudioSystem::gLock
921 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
922 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
923 }
924
925 for (size_t i = 0; i < mRecordThreads.size(); i++) {
926 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
927 }
928 }
929}
930
931void AudioFlinger::removeNotificationClient(pid_t pid)
932{
933 Mutex::Autolock _l(mLock);
934
935 int index = mNotificationClients.indexOfKey(pid);
936 if (index >= 0) {
937 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100938 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700939 mNotificationClients.removeItem(pid);
940 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700941
Steve Block3856b092011-10-20 11:56:00 +0100942 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700943 int num = mAudioSessionRefs.size();
944 bool removed = false;
945 for (int i = 0; i< num; i++) {
946 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100949 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700950 mAudioSessionRefs.removeAt(i);
951 delete ref;
952 removed = true;
953 i--;
954 num--;
955 }
956 }
957 if (removed) {
958 purgeStaleEffects_l();
959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700960}
961
962// audioConfigChanged_l() must be called with AudioFlinger::mLock held
963void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
964{
965 size_t size = mNotificationClients.size();
966 for (size_t i = 0; i < size; i++) {
967 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
968 }
969}
970
971// removeClient_l() must be called with AudioFlinger::mLock held
972void AudioFlinger::removeClient_l(pid_t pid)
973{
Steve Block3856b092011-10-20 11:56:00 +0100974 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700975 mClients.removeItem(pid);
976}
977
978
979// ----------------------------------------------------------------------------
980
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700981AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700982 : Thread(false),
983 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700984 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
985 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700986{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700987 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988}
989
990AudioFlinger::ThreadBase::~ThreadBase()
991{
992 mParamCond.broadcast();
993 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700994 // do not lock the mutex in destructor
995 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -0700996 if (mPowerManager != 0) {
997 sp<IBinder> binder = mPowerManager->asBinder();
998 binder->unlinkToDeath(mDeathRecipient);
999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001000}
1001
1002void AudioFlinger::ThreadBase::exit()
1003{
1004 // keep a strong ref on ourself so that we wont get
1005 // destroyed in the middle of requestExitAndWait()
1006 sp <ThreadBase> strongMe = this;
1007
Steve Block3856b092011-10-20 11:56:00 +01001008 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 {
1010 AutoMutex lock(&mLock);
1011 mExiting = true;
1012 requestExit();
1013 mWaitWorkCV.signal();
1014 }
1015 requestExitAndWait();
1016}
1017
1018uint32_t AudioFlinger::ThreadBase::sampleRate() const
1019{
1020 return mSampleRate;
1021}
1022
1023int AudioFlinger::ThreadBase::channelCount() const
1024{
1025 return (int)mChannelCount;
1026}
1027
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001028uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001029{
1030 return mFormat;
1031}
1032
1033size_t AudioFlinger::ThreadBase::frameCount() const
1034{
1035 return mFrameCount;
1036}
1037
1038status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1039{
1040 status_t status;
1041
Steve Block3856b092011-10-20 11:56:00 +01001042 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 Mutex::Autolock _l(mLock);
1044
1045 mNewParameters.add(keyValuePairs);
1046 mWaitWorkCV.signal();
1047 // wait condition with timeout in case the thread loop has exited
1048 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001049 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050 status = mParamStatus;
1051 mWaitWorkCV.signal();
1052 } else {
1053 status = TIMED_OUT;
1054 }
1055 return status;
1056}
1057
1058void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1059{
1060 Mutex::Autolock _l(mLock);
1061 sendConfigEvent_l(event, param);
1062}
1063
1064// sendConfigEvent_l() must be called with ThreadBase::mLock held
1065void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1066{
1067 ConfigEvent *configEvent = new ConfigEvent();
1068 configEvent->mEvent = event;
1069 configEvent->mParam = param;
1070 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001071 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 mWaitWorkCV.signal();
1073}
1074
1075void AudioFlinger::ThreadBase::processConfigEvents()
1076{
1077 mLock.lock();
1078 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001079 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001080 ConfigEvent *configEvent = mConfigEvents[0];
1081 mConfigEvents.removeAt(0);
1082 // release mLock before locking AudioFlinger mLock: lock order is always
1083 // AudioFlinger then ThreadBase to avoid cross deadlock
1084 mLock.unlock();
1085 mAudioFlinger->mLock.lock();
1086 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1087 mAudioFlinger->mLock.unlock();
1088 delete configEvent;
1089 mLock.lock();
1090 }
1091 mLock.unlock();
1092}
1093
1094status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1095{
1096 const size_t SIZE = 256;
1097 char buffer[SIZE];
1098 String8 result;
1099
1100 bool locked = tryLock(mLock);
1101 if (!locked) {
1102 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1103 write(fd, buffer, strlen(buffer));
1104 }
1105
1106 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1113 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001114 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1115 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001116 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1117 result.append(buffer);
1118 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1119 result.append(buffer);
1120
1121 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1122 result.append(buffer);
1123 result.append(" Index Command");
1124 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1125 snprintf(buffer, SIZE, "\n %02d ", i);
1126 result.append(buffer);
1127 result.append(mNewParameters[i]);
1128 }
1129
1130 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, " Index event param\n");
1133 result.append(buffer);
1134 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1135 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1136 result.append(buffer);
1137 }
1138 result.append("\n");
1139
1140 write(fd, result.string(), result.size());
1141
1142 if (locked) {
1143 mLock.unlock();
1144 }
1145 return NO_ERROR;
1146}
1147
Eric Laurent1d2bff02011-07-24 17:49:51 -07001148status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1149{
1150 const size_t SIZE = 256;
1151 char buffer[SIZE];
1152 String8 result;
1153
1154 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1155 write(fd, buffer, strlen(buffer));
1156
1157 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1158 sp<EffectChain> chain = mEffectChains[i];
1159 if (chain != 0) {
1160 chain->dump(fd, args);
1161 }
1162 }
1163 return NO_ERROR;
1164}
1165
Eric Laurentfeb0db62011-07-22 09:04:31 -07001166void AudioFlinger::ThreadBase::acquireWakeLock()
1167{
1168 Mutex::Autolock _l(mLock);
1169 acquireWakeLock_l();
1170}
1171
1172void AudioFlinger::ThreadBase::acquireWakeLock_l()
1173{
1174 if (mPowerManager == 0) {
1175 // use checkService() to avoid blocking if power service is not up yet
1176 sp<IBinder> binder =
1177 defaultServiceManager()->checkService(String16("power"));
1178 if (binder == 0) {
1179 LOGW("Thread %s cannot connect to the power manager service", mName);
1180 } else {
1181 mPowerManager = interface_cast<IPowerManager>(binder);
1182 binder->linkToDeath(mDeathRecipient);
1183 }
1184 }
1185 if (mPowerManager != 0) {
1186 sp<IBinder> binder = new BBinder();
1187 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1188 binder,
1189 String16(mName));
1190 if (status == NO_ERROR) {
1191 mWakeLockToken = binder;
1192 }
Steve Block3856b092011-10-20 11:56:00 +01001193 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001194 }
1195}
1196
1197void AudioFlinger::ThreadBase::releaseWakeLock()
1198{
1199 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001200 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001201}
1202
1203void AudioFlinger::ThreadBase::releaseWakeLock_l()
1204{
1205 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001206 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001207 if (mPowerManager != 0) {
1208 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1209 }
1210 mWakeLockToken.clear();
1211 }
1212}
1213
1214void AudioFlinger::ThreadBase::clearPowerManager()
1215{
1216 Mutex::Autolock _l(mLock);
1217 releaseWakeLock_l();
1218 mPowerManager.clear();
1219}
1220
1221void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1222{
1223 sp<ThreadBase> thread = mThread.promote();
1224 if (thread != 0) {
1225 thread->clearPowerManager();
1226 }
1227 LOGW("power manager service died !!!");
1228}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001229
Eric Laurent59255e42011-07-27 19:49:51 -07001230void AudioFlinger::ThreadBase::setEffectSuspended(
1231 const effect_uuid_t *type, bool suspend, int sessionId)
1232{
1233 Mutex::Autolock _l(mLock);
1234 setEffectSuspended_l(type, suspend, sessionId);
1235}
1236
1237void AudioFlinger::ThreadBase::setEffectSuspended_l(
1238 const effect_uuid_t *type, bool suspend, int sessionId)
1239{
1240 sp<EffectChain> chain;
1241 chain = getEffectChain_l(sessionId);
1242 if (chain != 0) {
1243 if (type != NULL) {
1244 chain->setEffectSuspended_l(type, suspend);
1245 } else {
1246 chain->setEffectSuspendedAll_l(suspend);
1247 }
1248 }
1249
1250 updateSuspendedSessions_l(type, suspend, sessionId);
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1254{
1255 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1256 if (index < 0) {
1257 return;
1258 }
1259
1260 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1261 mSuspendedSessions.editValueAt(index);
1262
1263 for (size_t i = 0; i < sessionEffects.size(); i++) {
1264 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1265 for (int j = 0; j < desc->mRefCount; j++) {
1266 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1267 chain->setEffectSuspendedAll_l(true);
1268 } else {
Steve Block3856b092011-10-20 11:56:00 +01001269 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001270 desc->mType.timeLow);
1271 chain->setEffectSuspended_l(&desc->mType, true);
1272 }
1273 }
1274 }
1275}
1276
Eric Laurent59255e42011-07-27 19:49:51 -07001277void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1278 bool suspend,
1279 int sessionId)
1280{
1281 int index = mSuspendedSessions.indexOfKey(sessionId);
1282
1283 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1284
1285 if (suspend) {
1286 if (index >= 0) {
1287 sessionEffects = mSuspendedSessions.editValueAt(index);
1288 } else {
1289 mSuspendedSessions.add(sessionId, sessionEffects);
1290 }
1291 } else {
1292 if (index < 0) {
1293 return;
1294 }
1295 sessionEffects = mSuspendedSessions.editValueAt(index);
1296 }
1297
1298
1299 int key = EffectChain::kKeyForSuspendAll;
1300 if (type != NULL) {
1301 key = type->timeLow;
1302 }
1303 index = sessionEffects.indexOfKey(key);
1304
1305 sp <SuspendedSessionDesc> desc;
1306 if (suspend) {
1307 if (index >= 0) {
1308 desc = sessionEffects.valueAt(index);
1309 } else {
1310 desc = new SuspendedSessionDesc();
1311 if (type != NULL) {
1312 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1313 }
1314 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001315 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001316 }
1317 desc->mRefCount++;
1318 } else {
1319 if (index < 0) {
1320 return;
1321 }
1322 desc = sessionEffects.valueAt(index);
1323 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001324 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001325 sessionEffects.removeItemsAt(index);
1326 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001328 sessionId);
1329 mSuspendedSessions.removeItem(sessionId);
1330 }
1331 }
1332 }
1333 if (!sessionEffects.isEmpty()) {
1334 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1335 }
1336}
1337
1338void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1339 bool enabled,
1340 int sessionId)
1341{
1342 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001343 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1344}
Eric Laurent59255e42011-07-27 19:49:51 -07001345
Eric Laurenta85a74a2011-10-19 11:44:54 -07001346void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1347 bool enabled,
1348 int sessionId)
1349{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001350 if (mType != RECORD) {
1351 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1352 // another session. This gives the priority to well behaved effect control panels
1353 // and applications not using global effects.
1354 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1355 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1356 }
1357 }
Eric Laurent59255e42011-07-27 19:49:51 -07001358
1359 sp<EffectChain> chain = getEffectChain_l(sessionId);
1360 if (chain != 0) {
1361 chain->checkSuspendOnEffectEnabled(effect, enabled);
1362 }
1363}
1364
Mathias Agopian65ab4712010-07-14 17:59:35 -07001365// ----------------------------------------------------------------------------
1366
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001367AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1368 AudioStreamOut* output,
1369 int id,
1370 uint32_t device)
1371 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001372 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001373 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001374{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001375 snprintf(mName, kNameLength, "AudioOut_%d", id);
1376
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377 readOutputParameters();
1378
1379 mMasterVolume = mAudioFlinger->masterVolume();
1380 mMasterMute = mAudioFlinger->masterMute();
1381
Dima Zavinfce7a472011-04-19 22:30:36 -07001382 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001383 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1384 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001385 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 }
1387}
1388
1389AudioFlinger::PlaybackThread::~PlaybackThread()
1390{
1391 delete [] mMixBuffer;
1392}
1393
1394status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1395{
1396 dumpInternals(fd, args);
1397 dumpTracks(fd, args);
1398 dumpEffectChains(fd, args);
1399 return NO_ERROR;
1400}
1401
1402status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1403{
1404 const size_t SIZE = 256;
1405 char buffer[SIZE];
1406 String8 result;
1407
1408 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1409 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001410 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001411 for (size_t i = 0; i < mTracks.size(); ++i) {
1412 sp<Track> track = mTracks[i];
1413 if (track != 0) {
1414 track->dump(buffer, SIZE);
1415 result.append(buffer);
1416 }
1417 }
1418
1419 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1420 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001421 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1423 wp<Track> wTrack = mActiveTracks[i];
1424 if (wTrack != 0) {
1425 sp<Track> track = wTrack.promote();
1426 if (track != 0) {
1427 track->dump(buffer, SIZE);
1428 result.append(buffer);
1429 }
1430 }
1431 }
1432 write(fd, result.string(), result.size());
1433 return NO_ERROR;
1434}
1435
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1437{
1438 const size_t SIZE = 256;
1439 char buffer[SIZE];
1440 String8 result;
1441
1442 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1443 result.append(buffer);
1444 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1445 result.append(buffer);
1446 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1455 result.append(buffer);
1456 write(fd, result.string(), result.size());
1457
1458 dumpBase(fd, args);
1459
1460 return NO_ERROR;
1461}
1462
1463// Thread virtuals
1464status_t AudioFlinger::PlaybackThread::readyToRun()
1465{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001466 status_t status = initCheck();
1467 if (status == NO_ERROR) {
1468 LOGI("AudioFlinger's thread %p ready to run", this);
1469 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001471 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001472 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473}
1474
1475void AudioFlinger::PlaybackThread::onFirstRef()
1476{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001477 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001478}
1479
1480// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1481sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1482 const sp<AudioFlinger::Client>& client,
1483 int streamType,
1484 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001485 uint32_t format,
1486 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 int frameCount,
1488 const sp<IMemory>& sharedBuffer,
1489 int sessionId,
1490 status_t *status)
1491{
1492 sp<Track> track;
1493 status_t lStatus;
1494
1495 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001496 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1497 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1498 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1499 "for output %p with format %d",
1500 sampleRate, format, channelMask, mOutput, mFormat);
1501 lStatus = BAD_VALUE;
1502 goto Exit;
1503 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 }
1505 } else {
1506 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1507 if (sampleRate > mSampleRate*2) {
1508 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1509 lStatus = BAD_VALUE;
1510 goto Exit;
1511 }
1512 }
1513
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001514 lStatus = initCheck();
1515 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001517 goto Exit;
1518 }
1519
1520 { // scope for mLock
1521 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001522
1523 // all tracks in same audio session must share the same routing strategy otherwise
1524 // conflicts will happen when tracks are moved from one output to another by audio policy
1525 // manager
1526 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001527 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001528 for (size_t i = 0; i < mTracks.size(); ++i) {
1529 sp<Track> t = mTracks[i];
1530 if (t != 0) {
1531 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001532 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001533 lStatus = BAD_VALUE;
1534 goto Exit;
1535 }
1536 }
1537 }
1538
Mathias Agopian65ab4712010-07-14 17:59:35 -07001539 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001540 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 if (track->getCblk() == NULL || track->name() < 0) {
1542 lStatus = NO_MEMORY;
1543 goto Exit;
1544 }
1545 mTracks.add(track);
1546
1547 sp<EffectChain> chain = getEffectChain_l(sessionId);
1548 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001549 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001551 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001552 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001554
1555 // invalidate track immediately if the stream type was moved to another thread since
1556 // createTrack() was called by the client process.
1557 if (!mStreamTypes[streamType].valid) {
1558 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1559 this, streamType);
1560 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1561 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001562 }
1563 lStatus = NO_ERROR;
1564
1565Exit:
1566 if(status) {
1567 *status = lStatus;
1568 }
1569 return track;
1570}
1571
1572uint32_t AudioFlinger::PlaybackThread::latency() const
1573{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001574 Mutex::Autolock _l(mLock);
1575 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001576 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001577 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 return 0;
1579 }
1580}
1581
1582status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1583{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 mMasterVolume = value;
1585 return NO_ERROR;
1586}
1587
1588status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 mMasterMute = muted;
1591 return NO_ERROR;
1592}
1593
1594float AudioFlinger::PlaybackThread::masterVolume() const
1595{
1596 return mMasterVolume;
1597}
1598
1599bool AudioFlinger::PlaybackThread::masterMute() const
1600{
1601 return mMasterMute;
1602}
1603
1604status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1605{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001606 mStreamTypes[stream].volume = value;
1607 return NO_ERROR;
1608}
1609
1610status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1611{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 mStreamTypes[stream].mute = muted;
1613 return NO_ERROR;
1614}
1615
1616float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1617{
1618 return mStreamTypes[stream].volume;
1619}
1620
1621bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1622{
1623 return mStreamTypes[stream].mute;
1624}
1625
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626// addTrack_l() must be called with ThreadBase::mLock held
1627status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1628{
1629 status_t status = ALREADY_EXISTS;
1630
1631 // set retry count for buffer fill
1632 track->mRetryCount = kMaxTrackStartupRetries;
1633 if (mActiveTracks.indexOf(track) < 0) {
1634 // the track is newly added, make sure it fills up all its
1635 // buffers before playing. This is to ensure the client will
1636 // effectively get the latency it requested.
1637 track->mFillingUpStatus = Track::FS_FILLING;
1638 track->mResetDone = false;
1639 mActiveTracks.add(track);
1640 if (track->mainBuffer() != mMixBuffer) {
1641 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1642 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001643 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001644 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 }
1646 }
1647
1648 status = NO_ERROR;
1649 }
1650
Steve Block3856b092011-10-20 11:56:00 +01001651 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 mWaitWorkCV.broadcast();
1653
1654 return status;
1655}
1656
1657// destroyTrack_l() must be called with ThreadBase::mLock held
1658void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1659{
1660 track->mState = TrackBase::TERMINATED;
1661 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001662 removeTrack_l(track);
1663 }
1664}
1665
1666void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1667{
1668 mTracks.remove(track);
1669 deleteTrackName_l(track->name());
1670 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1671 if (chain != 0) {
1672 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 }
1674}
1675
1676String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1677{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001678 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001679 char *s;
1680
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001681 Mutex::Autolock _l(mLock);
1682 if (initCheck() != NO_ERROR) {
1683 return out_s8;
1684 }
1685
Dima Zavin799a70e2011-04-18 16:57:27 -07001686 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001687 out_s8 = String8(s);
1688 free(s);
1689 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690}
1691
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001692// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1694 AudioSystem::OutputDescriptor desc;
1695 void *param2 = 0;
1696
Steve Block3856b092011-10-20 11:56:00 +01001697 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698
1699 switch (event) {
1700 case AudioSystem::OUTPUT_OPENED:
1701 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001702 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703 desc.samplingRate = mSampleRate;
1704 desc.format = mFormat;
1705 desc.frameCount = mFrameCount;
1706 desc.latency = latency();
1707 param2 = &desc;
1708 break;
1709
1710 case AudioSystem::STREAM_CONFIG_CHANGED:
1711 param2 = &param;
1712 case AudioSystem::OUTPUT_CLOSED:
1713 default:
1714 break;
1715 }
1716 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1717}
1718
1719void AudioFlinger::PlaybackThread::readOutputParameters()
1720{
Dima Zavin799a70e2011-04-18 16:57:27 -07001721 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001722 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1723 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001724 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1725 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1726 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727
1728 // FIXME - Current mixer implementation only supports stereo output: Always
1729 // Allocate a stereo buffer even if HW output is mono.
1730 if (mMixBuffer != NULL) delete[] mMixBuffer;
1731 mMixBuffer = new int16_t[mFrameCount * 2];
1732 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1733
Eric Laurentde070132010-07-13 04:45:46 -07001734 // force reconfiguration of effect chains and engines to take new buffer size and audio
1735 // parameters into account
1736 // Note that mLock is not held when readOutputParameters() is called from the constructor
1737 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1738 // matter.
1739 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1740 Vector< sp<EffectChain> > effectChains = mEffectChains;
1741 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001742 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001743 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744}
1745
1746status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1747{
1748 if (halFrames == 0 || dspFrames == 0) {
1749 return BAD_VALUE;
1750 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001751 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001752 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 return INVALID_OPERATION;
1754 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001755 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756
Dima Zavin799a70e2011-04-18 16:57:27 -07001757 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758}
1759
Eric Laurent39e94f82010-07-28 01:32:47 -07001760uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761{
1762 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001763 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001765 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 }
1767
1768 for (size_t i = 0; i < mTracks.size(); ++i) {
1769 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001770 if (sessionId == track->sessionId() &&
1771 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001772 result |= TRACK_SESSION;
1773 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001774 }
1775 }
1776
Eric Laurent39e94f82010-07-28 01:32:47 -07001777 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778}
1779
Eric Laurentde070132010-07-13 04:45:46 -07001780uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1781{
Dima Zavinfce7a472011-04-19 22:30:36 -07001782 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001783 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001784 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1785 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001786 }
1787 for (size_t i = 0; i < mTracks.size(); i++) {
1788 sp<Track> track = mTracks[i];
1789 if (sessionId == track->sessionId() &&
1790 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001791 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001792 }
1793 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001794 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001795}
1796
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001798AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1799{
1800 Mutex::Autolock _l(mLock);
1801 return mOutput;
1802}
1803
1804AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1805{
1806 Mutex::Autolock _l(mLock);
1807 AudioStreamOut *output = mOutput;
1808 mOutput = NULL;
1809 return output;
1810}
1811
1812// this method must always be called either with ThreadBase mLock held or inside the thread loop
1813audio_stream_t* AudioFlinger::PlaybackThread::stream()
1814{
1815 if (mOutput == NULL) {
1816 return NULL;
1817 }
1818 return &mOutput->stream->common;
1819}
1820
Eric Laurent162b40b2011-12-05 09:47:19 -08001821uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1822{
1823 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1824 // decoding and transfer time. So sleeping for half of the latency would likely cause
1825 // underruns
1826 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1827 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1828 } else {
1829 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1830 }
1831}
1832
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833// ----------------------------------------------------------------------------
1834
Dima Zavin799a70e2011-04-18 16:57:27 -07001835AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001836 : PlaybackThread(audioFlinger, output, id, device),
1837 mAudioMixer(0)
1838{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001839 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001840 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1841
1842 // FIXME - Current mixer implementation only supports stereo output
1843 if (mChannelCount == 1) {
1844 LOGE("Invalid audio hardware channel count");
1845 }
1846}
1847
1848AudioFlinger::MixerThread::~MixerThread()
1849{
1850 delete mAudioMixer;
1851}
1852
1853bool AudioFlinger::MixerThread::threadLoop()
1854{
1855 Vector< sp<Track> > tracksToRemove;
1856 uint32_t mixerStatus = MIXER_IDLE;
1857 nsecs_t standbyTime = systemTime();
1858 size_t mixBufferSize = mFrameCount * mFrameSize;
1859 // FIXME: Relaxed timing because of a certain device that can't meet latency
1860 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001861 // increase threshold again due to low power audio mode. The way this warning threshold is
1862 // calculated and its usefulness should be reconsidered anyway.
1863 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001864 nsecs_t lastWarning = 0;
1865 bool longStandbyExit = false;
1866 uint32_t activeSleepTime = activeSleepTimeUs();
1867 uint32_t idleSleepTime = idleSleepTimeUs();
1868 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001869 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001871#ifdef DEBUG_CPU_USAGE
1872 ThreadCpuUsage cpu;
1873 const CentralTendencyStatistics& stats = cpu.statistics();
1874#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875
Eric Laurentfeb0db62011-07-22 09:04:31 -07001876 acquireWakeLock();
1877
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 while (!exitPending())
1879 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001880#ifdef DEBUG_CPU_USAGE
1881 cpu.sampleAndEnable();
1882 unsigned n = stats.n();
1883 // cpu.elapsed() is expensive, so don't call it every loop
1884 if ((n & 127) == 1) {
1885 long long elapsed = cpu.elapsed();
1886 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1887 double perLoop = elapsed / (double) n;
1888 double perLoop100 = perLoop * 0.01;
1889 double mean = stats.mean();
1890 double stddev = stats.stddev();
1891 double minimum = stats.minimum();
1892 double maximum = stats.maximum();
1893 cpu.resetStatistics();
1894 LOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1895 elapsed * .000000001, n, perLoop * .000001,
1896 mean * .001,
1897 stddev * .001,
1898 minimum * .001,
1899 maximum * .001,
1900 mean / perLoop100,
1901 stddev / perLoop100,
1902 minimum / perLoop100,
1903 maximum / perLoop100);
1904 }
1905 }
1906#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001907 processConfigEvents();
1908
1909 mixerStatus = MIXER_IDLE;
1910 { // scope for mLock
1911
1912 Mutex::Autolock _l(mLock);
1913
1914 if (checkForNewParameters_l()) {
1915 mixBufferSize = mFrameCount * mFrameSize;
1916 // FIXME: Relaxed timing because of a certain device that can't meet latency
1917 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001918 // increase threshold again due to low power audio mode. The way this warning
1919 // threshold is calculated and its usefulness should be reconsidered anyway.
1920 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 activeSleepTime = activeSleepTimeUs();
1922 idleSleepTime = idleSleepTimeUs();
1923 }
1924
1925 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1926
1927 // put audio hardware into standby after short delay
1928 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1929 mSuspended) {
1930 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001931 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001932 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 mStandby = true;
1934 mBytesWritten = 0;
1935 }
1936
1937 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1938 // we're about to wait, flush the binder command buffer
1939 IPCThreadState::self()->flushCommands();
1940
1941 if (exitPending()) break;
1942
Eric Laurentfeb0db62011-07-22 09:04:31 -07001943 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001945 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001947 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001948 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949
1950 if (mMasterMute == false) {
1951 char value[PROPERTY_VALUE_MAX];
1952 property_get("ro.audio.silent", value, "0");
1953 if (atoi(value)) {
1954 LOGD("Silence is golden");
1955 setMasterMute(true);
1956 }
1957 }
1958
1959 standbyTime = systemTime() + kStandbyTimeInNsecs;
1960 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001961 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001962 continue;
1963 }
1964 }
1965
1966 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1967
1968 // prevent any changes in effect chain list and in each effect chain
1969 // during mixing and effect process as the audio buffers could be deleted
1970 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001971 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973
1974 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1975 // mix buffers...
1976 mAudioMixer->process();
1977 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001978 // increase sleep time progressively when application underrun condition clears
1979 if (sleepTimeShift > 0) {
1980 sleepTimeShift--;
1981 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 standbyTime = systemTime() + kStandbyTimeInNsecs;
1983 //TODO: delay standby when effects have a tail
1984 } else {
1985 // If no tracks are ready, sleep once for the duration of an output
1986 // buffer size, then write 0s to the output
1987 if (sleepTime == 0) {
1988 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001989 sleepTime = activeSleepTime >> sleepTimeShift;
1990 if (sleepTime < kMinThreadSleepTimeUs) {
1991 sleepTime = kMinThreadSleepTimeUs;
1992 }
1993 // reduce sleep time in case of consecutive application underruns to avoid
1994 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
1995 // duration we would end up writing less data than needed by the audio HAL if
1996 // the condition persists.
1997 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
1998 sleepTimeShift++;
1999 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 } else {
2001 sleepTime = idleSleepTime;
2002 }
2003 } else if (mBytesWritten != 0 ||
2004 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2005 memset (mMixBuffer, 0, mixBufferSize);
2006 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002007 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002008 }
2009 // TODO add standby time extension fct of effect tail
2010 }
2011
2012 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002013 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 }
2015 // sleepTime == 0 means we must write to audio hardware
2016 if (sleepTime == 0) {
2017 for (size_t i = 0; i < effectChains.size(); i ++) {
2018 effectChains[i]->process_l();
2019 }
2020 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002021 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 mLastWriteTime = systemTime();
2023 mInWrite = true;
2024 mBytesWritten += mixBufferSize;
2025
Dima Zavin799a70e2011-04-18 16:57:27 -07002026 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2028 mNumWrites++;
2029 mInWrite = false;
2030 nsecs_t now = systemTime();
2031 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002032 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002034 if ((now - lastWarning) > kWarningThrottleNs) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2036 ns2ms(delta), mNumDelayedWrites, this);
2037 lastWarning = now;
2038 }
2039 if (mStandby) {
2040 longStandbyExit = true;
2041 }
2042 }
2043 mStandby = false;
2044 } else {
2045 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002046 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 usleep(sleepTime);
2048 }
2049
2050 // finally let go of all our tracks, without the lock held
2051 // since we can't guarantee the destructors won't acquire that
2052 // same lock.
2053 tracksToRemove.clear();
2054
2055 // Effect chains will be actually deleted here if they were removed from
2056 // mEffectChains list during mixing or effects processing
2057 effectChains.clear();
2058 }
2059
2060 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002061 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002062 }
2063
Eric Laurentfeb0db62011-07-22 09:04:31 -07002064 releaseWakeLock();
2065
Steve Block3856b092011-10-20 11:56:00 +01002066 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 return false;
2068}
2069
2070// prepareTracks_l() must be called with ThreadBase::mLock held
2071uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2072{
2073
2074 uint32_t mixerStatus = MIXER_IDLE;
2075 // find out which tracks need to be processed
2076 size_t count = activeTracks.size();
2077 size_t mixedTracks = 0;
2078 size_t tracksWithEffect = 0;
2079
2080 float masterVolume = mMasterVolume;
2081 bool masterMute = mMasterMute;
2082
Eric Laurent571d49c2010-08-11 05:20:11 -07002083 if (masterMute) {
2084 masterVolume = 0;
2085 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002086 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002087 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002088 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002089 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002090 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 masterVolume = (float)((v + (1 << 23)) >> 24);
2092 chain.clear();
2093 }
2094
2095 for (size_t i=0 ; i<count ; i++) {
2096 sp<Track> t = activeTracks[i].promote();
2097 if (t == 0) continue;
2098
2099 Track* const track = t.get();
2100 audio_track_cblk_t* cblk = track->cblk();
2101
2102 // The first time a track is added we wait
2103 // for all its buffers to be filled before processing it
2104 mAudioMixer->setActiveTrack(track->name());
Eric Laurenta47b69c2011-11-08 18:10:16 -08002105 // make sure that we have enough frames to mix one full buffer.
2106 // enforce this condition only once to enable draining the buffer in case the client
2107 // app does not call stop() and relies on underrun to stop:
2108 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2109 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002110 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002111 if (!track->isStopped() && !track->isPausing() &&
2112 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002113 if (t->sampleRate() == (int)mSampleRate) {
2114 minFrames = mFrameCount;
2115 } else {
2116 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2117 }
2118 }
2119 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 !track->isPaused() && !track->isTerminated())
2121 {
Steve Block3856b092011-10-20 11:56:00 +01002122 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002123
2124 mixedTracks++;
2125
2126 // track->mainBuffer() != mMixBuffer means there is an effect chain
2127 // connected to the track
2128 chain.clear();
2129 if (track->mainBuffer() != mMixBuffer) {
2130 chain = getEffectChain_l(track->sessionId());
2131 // Delegate volume control to effect in track effect chain if needed
2132 if (chain != 0) {
2133 tracksWithEffect++;
2134 } else {
2135 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2136 track->name(), track->sessionId());
2137 }
2138 }
2139
2140
2141 int param = AudioMixer::VOLUME;
2142 if (track->mFillingUpStatus == Track::FS_FILLED) {
2143 // no ramp for the first volume setting
2144 track->mFillingUpStatus = Track::FS_ACTIVE;
2145 if (track->mState == TrackBase::RESUMING) {
2146 track->mState = TrackBase::ACTIVE;
2147 param = AudioMixer::RAMP_VOLUME;
2148 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002149 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 } else if (cblk->server != 0) {
2151 // If the track is stopped before the first frame was mixed,
2152 // do not apply ramp
2153 param = AudioMixer::RAMP_VOLUME;
2154 }
2155
2156 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002157 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002158 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002159 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002160 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002161 if (track->isPausing()) {
2162 track->setPaused();
2163 }
2164 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002165
Mathias Agopian65ab4712010-07-14 17:59:35 -07002166 // read original volumes with volume control
2167 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002168 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002169 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2170 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002171
Eric Laurente0aed6d2010-09-10 17:44:44 -07002172 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002174 // Delegate volume control to effect in track effect chain if needed
2175 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2176 // Do not ramp volume if volume is controlled by effect
2177 param = AudioMixer::VOLUME;
2178 track->mHasVolumeController = true;
2179 } else {
2180 // force no volume ramp when volume controller was just disabled or removed
2181 // from effect chain to avoid volume spike
2182 if (track->mHasVolumeController) {
2183 param = AudioMixer::VOLUME;
2184 }
2185 track->mHasVolumeController = false;
2186 }
2187
2188 // Convert volumes from 8.24 to 4.12 format
2189 int16_t left, right, aux;
2190 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2191 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2192 left = int16_t(v_clamped);
2193 v_clamped = (vr + (1 << 11)) >> 12;
2194 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2195 right = int16_t(v_clamped);
2196
2197 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2198 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199
Mathias Agopian65ab4712010-07-14 17:59:35 -07002200 // XXX: these things DON'T need to be done each time
2201 mAudioMixer->setBufferProvider(track);
2202 mAudioMixer->enable(AudioMixer::MIXING);
2203
2204 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2205 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2206 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2207 mAudioMixer->setParameter(
2208 AudioMixer::TRACK,
2209 AudioMixer::FORMAT, (void *)track->format());
2210 mAudioMixer->setParameter(
2211 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002212 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213 mAudioMixer->setParameter(
2214 AudioMixer::RESAMPLE,
2215 AudioMixer::SAMPLE_RATE,
2216 (void *)(cblk->sampleRate));
2217 mAudioMixer->setParameter(
2218 AudioMixer::TRACK,
2219 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2220 mAudioMixer->setParameter(
2221 AudioMixer::TRACK,
2222 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2223
2224 // reset retry count
2225 track->mRetryCount = kMaxTrackRetries;
2226 mixerStatus = MIXER_TRACKS_READY;
2227 } else {
Steve Block3856b092011-10-20 11:56:00 +01002228 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229 if (track->isStopped()) {
2230 track->reset();
2231 }
2232 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2233 // We have consumed all the buffers of this track.
2234 // Remove it from the list of active tracks.
2235 tracksToRemove->add(track);
2236 } else {
2237 // No buffers for this track. Give it a few chances to
2238 // fill a buffer, then remove it from active list.
2239 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002240 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002241 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002242 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002243 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 } else if (mixerStatus != MIXER_TRACKS_READY) {
2245 mixerStatus = MIXER_TRACKS_ENABLED;
2246 }
2247 }
2248 mAudioMixer->disable(AudioMixer::MIXING);
2249 }
2250 }
2251
2252 // remove all the tracks that need to be...
2253 count = tracksToRemove->size();
2254 if (UNLIKELY(count)) {
2255 for (size_t i=0 ; i<count ; i++) {
2256 const sp<Track>& track = tracksToRemove->itemAt(i);
2257 mActiveTracks.remove(track);
2258 if (track->mainBuffer() != mMixBuffer) {
2259 chain = getEffectChain_l(track->sessionId());
2260 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002261 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002262 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 }
2264 }
2265 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002266 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002267 }
2268 }
2269 }
2270
2271 // mix buffer must be cleared if all tracks are connected to an
2272 // effect chain as in this case the mixer will not write to
2273 // mix buffer and track effects will accumulate into it
2274 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2275 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2276 }
2277
2278 return mixerStatus;
2279}
2280
2281void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2282{
Steve Block3856b092011-10-20 11:56:00 +01002283 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002284 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002285 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002286
Mathias Agopian65ab4712010-07-14 17:59:35 -07002287 size_t size = mTracks.size();
2288 for (size_t i = 0; i < size; i++) {
2289 sp<Track> t = mTracks[i];
2290 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002291 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 }
2294 }
2295}
2296
Eric Laurent9f6530f2011-08-30 10:18:54 -07002297void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2298{
Steve Block3856b092011-10-20 11:56:00 +01002299 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002300 this, streamType, valid);
2301 Mutex::Autolock _l(mLock);
2302
2303 mStreamTypes[streamType].valid = valid;
2304}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002305
2306// getTrackName_l() must be called with ThreadBase::mLock held
2307int AudioFlinger::MixerThread::getTrackName_l()
2308{
2309 return mAudioMixer->getTrackName();
2310}
2311
2312// deleteTrackName_l() must be called with ThreadBase::mLock held
2313void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2314{
Steve Block3856b092011-10-20 11:56:00 +01002315 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316 mAudioMixer->deleteTrackName(name);
2317}
2318
2319// checkForNewParameters_l() must be called with ThreadBase::mLock held
2320bool AudioFlinger::MixerThread::checkForNewParameters_l()
2321{
2322 bool reconfig = false;
2323
2324 while (!mNewParameters.isEmpty()) {
2325 status_t status = NO_ERROR;
2326 String8 keyValuePair = mNewParameters[0];
2327 AudioParameter param = AudioParameter(keyValuePair);
2328 int value;
2329
2330 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2331 reconfig = true;
2332 }
2333 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002334 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335 status = BAD_VALUE;
2336 } else {
2337 reconfig = true;
2338 }
2339 }
2340 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002341 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002342 status = BAD_VALUE;
2343 } else {
2344 reconfig = true;
2345 }
2346 }
2347 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2348 // do not accept frame count changes if tracks are open as the track buffer
2349 // size depends on frame count and correct behavior would not be garantied
2350 // if frame count is changed after track creation
2351 if (!mTracks.isEmpty()) {
2352 status = INVALID_OPERATION;
2353 } else {
2354 reconfig = true;
2355 }
2356 }
2357 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002358 // when changing the audio output device, call addBatteryData to notify
2359 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002360 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002361 uint32_t params = 0;
2362 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002363 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002364 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2365 }
2366
2367 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002368 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002369 // check if any other device (except speaker) is on
2370 if (value & deviceWithoutSpeaker ) {
2371 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2372 }
2373
2374 if (params != 0) {
2375 addBatteryData(params);
2376 }
2377 }
2378
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 // forward device change to effects that have requested to be
2380 // aware of attached audio device.
2381 mDevice = (uint32_t)value;
2382 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002383 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002384 }
2385 }
2386
2387 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002388 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002389 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002391 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002392 mStandby = true;
2393 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002394 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002395 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002396 }
2397 if (status == NO_ERROR && reconfig) {
2398 delete mAudioMixer;
2399 readOutputParameters();
2400 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2401 for (size_t i = 0; i < mTracks.size() ; i++) {
2402 int name = getTrackName_l();
2403 if (name < 0) break;
2404 mTracks[i]->mName = name;
2405 // limit track sample rate to 2 x new output sample rate
2406 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2407 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2408 }
2409 }
2410 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2411 }
2412 }
2413
2414 mNewParameters.removeAt(0);
2415
2416 mParamStatus = status;
2417 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002418 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2419 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002420 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 }
2422 return reconfig;
2423}
2424
2425status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2426{
2427 const size_t SIZE = 256;
2428 char buffer[SIZE];
2429 String8 result;
2430
2431 PlaybackThread::dumpInternals(fd, args);
2432
2433 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2434 result.append(buffer);
2435 write(fd, result.string(), result.size());
2436 return NO_ERROR;
2437}
2438
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2440{
Eric Laurent60e18242010-07-29 06:50:24 -07002441 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002442}
2443
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002444uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2445{
2446 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2447}
2448
Mathias Agopian65ab4712010-07-14 17:59:35 -07002449// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002450AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 : PlaybackThread(audioFlinger, output, id, device)
2452{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002453 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002454}
2455
2456AudioFlinger::DirectOutputThread::~DirectOutputThread()
2457{
2458}
2459
2460
2461static inline int16_t clamp16(int32_t sample)
2462{
2463 if ((sample>>15) ^ (sample>>31))
2464 sample = 0x7FFF ^ (sample>>31);
2465 return sample;
2466}
2467
2468static inline
2469int32_t mul(int16_t in, int16_t v)
2470{
2471#if defined(__arm__) && !defined(__thumb__)
2472 int32_t out;
2473 asm( "smulbb %[out], %[in], %[v] \n"
2474 : [out]"=r"(out)
2475 : [in]"%r"(in), [v]"r"(v)
2476 : );
2477 return out;
2478#else
2479 return in * int32_t(v);
2480#endif
2481}
2482
2483void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2484{
2485 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002486 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002487 return;
2488 }
2489
2490 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002491 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002492 size_t count = mFrameCount * mChannelCount;
2493 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2494 int16_t *dst = mMixBuffer + count-1;
2495 while(count--) {
2496 *dst-- = (int16_t)(*src--^0x80) << 8;
2497 }
2498 }
2499
2500 size_t frameCount = mFrameCount;
2501 int16_t *out = mMixBuffer;
2502 if (ramp) {
2503 if (mChannelCount == 1) {
2504 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2505 int32_t vlInc = d / (int32_t)frameCount;
2506 int32_t vl = ((int32_t)mLeftVolShort << 16);
2507 do {
2508 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2509 out++;
2510 vl += vlInc;
2511 } while (--frameCount);
2512
2513 } else {
2514 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2515 int32_t vlInc = d / (int32_t)frameCount;
2516 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2517 int32_t vrInc = d / (int32_t)frameCount;
2518 int32_t vl = ((int32_t)mLeftVolShort << 16);
2519 int32_t vr = ((int32_t)mRightVolShort << 16);
2520 do {
2521 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2522 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2523 out += 2;
2524 vl += vlInc;
2525 vr += vrInc;
2526 } while (--frameCount);
2527 }
2528 } else {
2529 if (mChannelCount == 1) {
2530 do {
2531 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2532 out++;
2533 } while (--frameCount);
2534 } else {
2535 do {
2536 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2537 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2538 out += 2;
2539 } while (--frameCount);
2540 }
2541 }
2542
2543 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002544 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002545 size_t count = mFrameCount * mChannelCount;
2546 int16_t *src = mMixBuffer;
2547 uint8_t *dst = (uint8_t *)mMixBuffer;
2548 while(count--) {
2549 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2550 }
2551 }
2552
2553 mLeftVolShort = leftVol;
2554 mRightVolShort = rightVol;
2555}
2556
2557bool AudioFlinger::DirectOutputThread::threadLoop()
2558{
2559 uint32_t mixerStatus = MIXER_IDLE;
2560 sp<Track> trackToRemove;
2561 sp<Track> activeTrack;
2562 nsecs_t standbyTime = systemTime();
2563 int8_t *curBuf;
2564 size_t mixBufferSize = mFrameCount*mFrameSize;
2565 uint32_t activeSleepTime = activeSleepTimeUs();
2566 uint32_t idleSleepTime = idleSleepTimeUs();
2567 uint32_t sleepTime = idleSleepTime;
2568 // use shorter standby delay as on normal output to release
2569 // hardware resources as soon as possible
2570 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2571
Eric Laurentfeb0db62011-07-22 09:04:31 -07002572 acquireWakeLock();
2573
Mathias Agopian65ab4712010-07-14 17:59:35 -07002574 while (!exitPending())
2575 {
2576 bool rampVolume;
2577 uint16_t leftVol;
2578 uint16_t rightVol;
2579 Vector< sp<EffectChain> > effectChains;
2580
2581 processConfigEvents();
2582
2583 mixerStatus = MIXER_IDLE;
2584
2585 { // scope for the mLock
2586
2587 Mutex::Autolock _l(mLock);
2588
2589 if (checkForNewParameters_l()) {
2590 mixBufferSize = mFrameCount*mFrameSize;
2591 activeSleepTime = activeSleepTimeUs();
2592 idleSleepTime = idleSleepTimeUs();
2593 standbyDelay = microseconds(activeSleepTime*2);
2594 }
2595
2596 // put audio hardware into standby after short delay
2597 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2598 mSuspended) {
2599 // wait until we have something to do...
2600 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002601 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002602 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002603 mStandby = true;
2604 mBytesWritten = 0;
2605 }
2606
2607 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2608 // we're about to wait, flush the binder command buffer
2609 IPCThreadState::self()->flushCommands();
2610
2611 if (exitPending()) break;
2612
Eric Laurentfeb0db62011-07-22 09:04:31 -07002613 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002614 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002615 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002616 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002617 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618
2619 if (mMasterMute == false) {
2620 char value[PROPERTY_VALUE_MAX];
2621 property_get("ro.audio.silent", value, "0");
2622 if (atoi(value)) {
2623 LOGD("Silence is golden");
2624 setMasterMute(true);
2625 }
2626 }
2627
2628 standbyTime = systemTime() + standbyDelay;
2629 sleepTime = idleSleepTime;
2630 continue;
2631 }
2632 }
2633
2634 effectChains = mEffectChains;
2635
2636 // find out which tracks need to be processed
2637 if (mActiveTracks.size() != 0) {
2638 sp<Track> t = mActiveTracks[0].promote();
2639 if (t == 0) continue;
2640
2641 Track* const track = t.get();
2642 audio_track_cblk_t* cblk = track->cblk();
2643
2644 // The first time a track is added we wait
2645 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002646 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002647 !track->isPaused() && !track->isTerminated())
2648 {
Steve Block3856b092011-10-20 11:56:00 +01002649 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650
2651 if (track->mFillingUpStatus == Track::FS_FILLED) {
2652 track->mFillingUpStatus = Track::FS_ACTIVE;
2653 mLeftVolFloat = mRightVolFloat = 0;
2654 mLeftVolShort = mRightVolShort = 0;
2655 if (track->mState == TrackBase::RESUMING) {
2656 track->mState = TrackBase::ACTIVE;
2657 rampVolume = true;
2658 }
2659 } else if (cblk->server != 0) {
2660 // If the track is stopped before the first frame was mixed,
2661 // do not apply ramp
2662 rampVolume = true;
2663 }
2664 // compute volume for this track
2665 float left, right;
2666 if (track->isMuted() || mMasterMute || track->isPausing() ||
2667 mStreamTypes[track->type()].mute) {
2668 left = right = 0;
2669 if (track->isPausing()) {
2670 track->setPaused();
2671 }
2672 } else {
2673 float typeVolume = mStreamTypes[track->type()].volume;
2674 float v = mMasterVolume * typeVolume;
2675 float v_clamped = v * cblk->volume[0];
2676 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2677 left = v_clamped/MAX_GAIN;
2678 v_clamped = v * cblk->volume[1];
2679 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2680 right = v_clamped/MAX_GAIN;
2681 }
2682
2683 if (left != mLeftVolFloat || right != mRightVolFloat) {
2684 mLeftVolFloat = left;
2685 mRightVolFloat = right;
2686
2687 // If audio HAL implements volume control,
2688 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002689 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002690 left = 1.0f;
2691 right = 1.0f;
2692 }
2693
2694 // Convert volumes from float to 8.24
2695 uint32_t vl = (uint32_t)(left * (1 << 24));
2696 uint32_t vr = (uint32_t)(right * (1 << 24));
2697
2698 // Delegate volume control to effect in track effect chain if needed
2699 // only one effect chain can be present on DirectOutputThread, so if
2700 // there is one, the track is connected to it
2701 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002702 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002703 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 rampVolume = false;
2705 }
2706 }
2707
2708 // Convert volumes from 8.24 to 4.12 format
2709 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2710 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2711 leftVol = (uint16_t)v_clamped;
2712 v_clamped = (vr + (1 << 11)) >> 12;
2713 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2714 rightVol = (uint16_t)v_clamped;
2715 } else {
2716 leftVol = mLeftVolShort;
2717 rightVol = mRightVolShort;
2718 rampVolume = false;
2719 }
2720
2721 // reset retry count
2722 track->mRetryCount = kMaxTrackRetriesDirect;
2723 activeTrack = t;
2724 mixerStatus = MIXER_TRACKS_READY;
2725 } else {
Steve Block3856b092011-10-20 11:56:00 +01002726 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 if (track->isStopped()) {
2728 track->reset();
2729 }
2730 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2731 // We have consumed all the buffers of this track.
2732 // Remove it from the list of active tracks.
2733 trackToRemove = track;
2734 } else {
2735 // No buffers for this track. Give it a few chances to
2736 // fill a buffer, then remove it from active list.
2737 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002738 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 trackToRemove = track;
2740 } else {
2741 mixerStatus = MIXER_TRACKS_ENABLED;
2742 }
2743 }
2744 }
2745 }
2746
2747 // remove all the tracks that need to be...
2748 if (UNLIKELY(trackToRemove != 0)) {
2749 mActiveTracks.remove(trackToRemove);
2750 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002751 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002752 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002753 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002754 }
2755 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002756 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 }
2758 }
2759
Eric Laurentde070132010-07-13 04:45:46 -07002760 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 }
2762
2763 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2764 AudioBufferProvider::Buffer buffer;
2765 size_t frameCount = mFrameCount;
2766 curBuf = (int8_t *)mMixBuffer;
2767 // output audio to hardware
2768 while (frameCount) {
2769 buffer.frameCount = frameCount;
2770 activeTrack->getNextBuffer(&buffer);
2771 if (UNLIKELY(buffer.raw == 0)) {
2772 memset(curBuf, 0, frameCount * mFrameSize);
2773 break;
2774 }
2775 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2776 frameCount -= buffer.frameCount;
2777 curBuf += buffer.frameCount * mFrameSize;
2778 activeTrack->releaseBuffer(&buffer);
2779 }
2780 sleepTime = 0;
2781 standbyTime = systemTime() + standbyDelay;
2782 } else {
2783 if (sleepTime == 0) {
2784 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2785 sleepTime = activeSleepTime;
2786 } else {
2787 sleepTime = idleSleepTime;
2788 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002789 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002790 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2791 sleepTime = 0;
2792 }
2793 }
2794
2795 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002796 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 }
2798 // sleepTime == 0 means we must write to audio hardware
2799 if (sleepTime == 0) {
2800 if (mixerStatus == MIXER_TRACKS_READY) {
2801 applyVolume(leftVol, rightVol, rampVolume);
2802 }
2803 for (size_t i = 0; i < effectChains.size(); i ++) {
2804 effectChains[i]->process_l();
2805 }
Eric Laurentde070132010-07-13 04:45:46 -07002806 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807
2808 mLastWriteTime = systemTime();
2809 mInWrite = true;
2810 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002811 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2813 mNumWrites++;
2814 mInWrite = false;
2815 mStandby = false;
2816 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002817 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 usleep(sleepTime);
2819 }
2820
2821 // finally let go of removed track, without the lock held
2822 // since we can't guarantee the destructors won't acquire that
2823 // same lock.
2824 trackToRemove.clear();
2825 activeTrack.clear();
2826
2827 // Effect chains will be actually deleted here if they were removed from
2828 // mEffectChains list during mixing or effects processing
2829 effectChains.clear();
2830 }
2831
2832 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002833 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 }
2835
Eric Laurentfeb0db62011-07-22 09:04:31 -07002836 releaseWakeLock();
2837
Steve Block3856b092011-10-20 11:56:00 +01002838 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002839 return false;
2840}
2841
2842// getTrackName_l() must be called with ThreadBase::mLock held
2843int AudioFlinger::DirectOutputThread::getTrackName_l()
2844{
2845 return 0;
2846}
2847
2848// deleteTrackName_l() must be called with ThreadBase::mLock held
2849void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2850{
2851}
2852
2853// checkForNewParameters_l() must be called with ThreadBase::mLock held
2854bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2855{
2856 bool reconfig = false;
2857
2858 while (!mNewParameters.isEmpty()) {
2859 status_t status = NO_ERROR;
2860 String8 keyValuePair = mNewParameters[0];
2861 AudioParameter param = AudioParameter(keyValuePair);
2862 int value;
2863
2864 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2865 // do not accept frame count changes if tracks are open as the track buffer
2866 // size depends on frame count and correct behavior would not be garantied
2867 // if frame count is changed after track creation
2868 if (!mTracks.isEmpty()) {
2869 status = INVALID_OPERATION;
2870 } else {
2871 reconfig = true;
2872 }
2873 }
2874 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002875 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002876 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002878 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002879 mStandby = true;
2880 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002881 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002882 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 }
2884 if (status == NO_ERROR && reconfig) {
2885 readOutputParameters();
2886 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2887 }
2888 }
2889
2890 mNewParameters.removeAt(0);
2891
2892 mParamStatus = status;
2893 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002894 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2895 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002896 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002897 }
2898 return reconfig;
2899}
2900
2901uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2902{
2903 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002904 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002905 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002906 } else {
2907 time = 10000;
2908 }
2909 return time;
2910}
2911
2912uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2913{
2914 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002915 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002916 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 } else {
2918 time = 10000;
2919 }
2920 return time;
2921}
2922
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002923uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2924{
2925 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002926 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002927 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2928 } else {
2929 time = 10000;
2930 }
2931 return time;
2932}
2933
2934
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935// ----------------------------------------------------------------------------
2936
2937AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2938 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2939{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002940 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941 addOutputTrack(mainThread);
2942}
2943
2944AudioFlinger::DuplicatingThread::~DuplicatingThread()
2945{
2946 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2947 mOutputTracks[i]->destroy();
2948 }
2949 mOutputTracks.clear();
2950}
2951
2952bool AudioFlinger::DuplicatingThread::threadLoop()
2953{
2954 Vector< sp<Track> > tracksToRemove;
2955 uint32_t mixerStatus = MIXER_IDLE;
2956 nsecs_t standbyTime = systemTime();
2957 size_t mixBufferSize = mFrameCount*mFrameSize;
2958 SortedVector< sp<OutputTrack> > outputTracks;
2959 uint32_t writeFrames = 0;
2960 uint32_t activeSleepTime = activeSleepTimeUs();
2961 uint32_t idleSleepTime = idleSleepTimeUs();
2962 uint32_t sleepTime = idleSleepTime;
2963 Vector< sp<EffectChain> > effectChains;
2964
Eric Laurentfeb0db62011-07-22 09:04:31 -07002965 acquireWakeLock();
2966
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 while (!exitPending())
2968 {
2969 processConfigEvents();
2970
2971 mixerStatus = MIXER_IDLE;
2972 { // scope for the mLock
2973
2974 Mutex::Autolock _l(mLock);
2975
2976 if (checkForNewParameters_l()) {
2977 mixBufferSize = mFrameCount*mFrameSize;
2978 updateWaitTime();
2979 activeSleepTime = activeSleepTimeUs();
2980 idleSleepTime = idleSleepTimeUs();
2981 }
2982
2983 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2984
2985 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2986 outputTracks.add(mOutputTracks[i]);
2987 }
2988
2989 // put audio hardware into standby after short delay
2990 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2991 mSuspended) {
2992 if (!mStandby) {
2993 for (size_t i = 0; i < outputTracks.size(); i++) {
2994 outputTracks[i]->stop();
2995 }
2996 mStandby = true;
2997 mBytesWritten = 0;
2998 }
2999
3000 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3001 // we're about to wait, flush the binder command buffer
3002 IPCThreadState::self()->flushCommands();
3003 outputTracks.clear();
3004
3005 if (exitPending()) break;
3006
Eric Laurentfeb0db62011-07-22 09:04:31 -07003007 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003008 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003009 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003010 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003011 acquireWakeLock_l();
3012
Mathias Agopian65ab4712010-07-14 17:59:35 -07003013 if (mMasterMute == false) {
3014 char value[PROPERTY_VALUE_MAX];
3015 property_get("ro.audio.silent", value, "0");
3016 if (atoi(value)) {
3017 LOGD("Silence is golden");
3018 setMasterMute(true);
3019 }
3020 }
3021
3022 standbyTime = systemTime() + kStandbyTimeInNsecs;
3023 sleepTime = idleSleepTime;
3024 continue;
3025 }
3026 }
3027
3028 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3029
3030 // prevent any changes in effect chain list and in each effect chain
3031 // during mixing and effect process as the audio buffers could be deleted
3032 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003033 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003034 }
3035
3036 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3037 // mix buffers...
3038 if (outputsReady(outputTracks)) {
3039 mAudioMixer->process();
3040 } else {
3041 memset(mMixBuffer, 0, mixBufferSize);
3042 }
3043 sleepTime = 0;
3044 writeFrames = mFrameCount;
3045 } else {
3046 if (sleepTime == 0) {
3047 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3048 sleepTime = activeSleepTime;
3049 } else {
3050 sleepTime = idleSleepTime;
3051 }
3052 } else if (mBytesWritten != 0) {
3053 // flush remaining overflow buffers in output tracks
3054 for (size_t i = 0; i < outputTracks.size(); i++) {
3055 if (outputTracks[i]->isActive()) {
3056 sleepTime = 0;
3057 writeFrames = 0;
3058 memset(mMixBuffer, 0, mixBufferSize);
3059 break;
3060 }
3061 }
3062 }
3063 }
3064
3065 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003066 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003067 }
3068 // sleepTime == 0 means we must write to audio hardware
3069 if (sleepTime == 0) {
3070 for (size_t i = 0; i < effectChains.size(); i ++) {
3071 effectChains[i]->process_l();
3072 }
3073 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003074 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003075
3076 standbyTime = systemTime() + kStandbyTimeInNsecs;
3077 for (size_t i = 0; i < outputTracks.size(); i++) {
3078 outputTracks[i]->write(mMixBuffer, writeFrames);
3079 }
3080 mStandby = false;
3081 mBytesWritten += mixBufferSize;
3082 } else {
3083 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003084 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003085 usleep(sleepTime);
3086 }
3087
3088 // finally let go of all our tracks, without the lock held
3089 // since we can't guarantee the destructors won't acquire that
3090 // same lock.
3091 tracksToRemove.clear();
3092 outputTracks.clear();
3093
3094 // Effect chains will be actually deleted here if they were removed from
3095 // mEffectChains list during mixing or effects processing
3096 effectChains.clear();
3097 }
3098
Eric Laurentfeb0db62011-07-22 09:04:31 -07003099 releaseWakeLock();
3100
Mathias Agopian65ab4712010-07-14 17:59:35 -07003101 return false;
3102}
3103
3104void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3105{
3106 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3107 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3108 this,
3109 mSampleRate,
3110 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003111 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003112 frameCount);
3113 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003114 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003116 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 updateWaitTime();
3118 }
3119}
3120
3121void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3122{
3123 Mutex::Autolock _l(mLock);
3124 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3125 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3126 mOutputTracks[i]->destroy();
3127 mOutputTracks.removeAt(i);
3128 updateWaitTime();
3129 return;
3130 }
3131 }
Steve Block3856b092011-10-20 11:56:00 +01003132 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003133}
3134
3135void AudioFlinger::DuplicatingThread::updateWaitTime()
3136{
3137 mWaitTimeMs = UINT_MAX;
3138 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3139 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3140 if (strong != NULL) {
3141 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3142 if (waitTimeMs < mWaitTimeMs) {
3143 mWaitTimeMs = waitTimeMs;
3144 }
3145 }
3146 }
3147}
3148
3149
3150bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3151{
3152 for (size_t i = 0; i < outputTracks.size(); i++) {
3153 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3154 if (thread == 0) {
3155 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3156 return false;
3157 }
3158 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3159 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003160 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003161 return false;
3162 }
3163 }
3164 return true;
3165}
3166
3167uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3168{
3169 return (mWaitTimeMs * 1000) / 2;
3170}
3171
3172// ----------------------------------------------------------------------------
3173
3174// TrackBase constructor must be called with AudioFlinger::mLock held
3175AudioFlinger::ThreadBase::TrackBase::TrackBase(
3176 const wp<ThreadBase>& thread,
3177 const sp<Client>& client,
3178 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003179 uint32_t format,
3180 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 int frameCount,
3182 uint32_t flags,
3183 const sp<IMemory>& sharedBuffer,
3184 int sessionId)
3185 : RefBase(),
3186 mThread(thread),
3187 mClient(client),
3188 mCblk(0),
3189 mFrameCount(0),
3190 mState(IDLE),
3191 mClientTid(-1),
3192 mFormat(format),
3193 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3194 mSessionId(sessionId)
3195{
Steve Block3856b092011-10-20 11:56:00 +01003196 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003197
3198 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3199 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003200 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003201 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3202 if (sharedBuffer == 0) {
3203 size += bufferSize;
3204 }
3205
3206 if (client != NULL) {
3207 mCblkMemory = client->heap()->allocate(size);
3208 if (mCblkMemory != 0) {
3209 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3210 if (mCblk) { // construct the shared structure in-place.
3211 new(mCblk) audio_track_cblk_t();
3212 // clear all buffers
3213 mCblk->frameCount = frameCount;
3214 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003215 mChannelCount = channelCount;
3216 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 if (sharedBuffer == 0) {
3218 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3219 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3220 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003221 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003222 mCblk->flags = CBLK_UNDERRUN_ON;
3223 } else {
3224 mBuffer = sharedBuffer->pointer();
3225 }
3226 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3227 }
3228 } else {
3229 LOGE("not enough memory for AudioTrack size=%u", size);
3230 client->heap()->dump("AudioTrack");
3231 return;
3232 }
3233 } else {
3234 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3235 if (mCblk) { // construct the shared structure in-place.
3236 new(mCblk) audio_track_cblk_t();
3237 // clear all buffers
3238 mCblk->frameCount = frameCount;
3239 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003240 mChannelCount = channelCount;
3241 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3243 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3244 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003245 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003246 mCblk->flags = CBLK_UNDERRUN_ON;
3247 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3248 }
3249 }
3250}
3251
3252AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3253{
3254 if (mCblk) {
3255 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3256 if (mClient == NULL) {
3257 delete mCblk;
3258 }
3259 }
3260 mCblkMemory.clear(); // and free the shared memory
3261 if (mClient != NULL) {
3262 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3263 mClient.clear();
3264 }
3265}
3266
3267void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3268{
3269 buffer->raw = 0;
3270 mFrameCount = buffer->frameCount;
3271 step();
3272 buffer->frameCount = 0;
3273}
3274
3275bool AudioFlinger::ThreadBase::TrackBase::step() {
3276 bool result;
3277 audio_track_cblk_t* cblk = this->cblk();
3278
3279 result = cblk->stepServer(mFrameCount);
3280 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003281 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282 mFlags |= STEPSERVER_FAILED;
3283 }
3284 return result;
3285}
3286
3287void AudioFlinger::ThreadBase::TrackBase::reset() {
3288 audio_track_cblk_t* cblk = this->cblk();
3289
3290 cblk->user = 0;
3291 cblk->server = 0;
3292 cblk->userBase = 0;
3293 cblk->serverBase = 0;
3294 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003295 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296}
3297
3298sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3299{
3300 return mCblkMemory;
3301}
3302
3303int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3304 return (int)mCblk->sampleRate;
3305}
3306
3307int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003308 return (const int)mChannelCount;
3309}
3310
3311uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3312 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313}
3314
3315void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3316 audio_track_cblk_t* cblk = this->cblk();
3317 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3318 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3319
3320 // Check validity of returned pointer in case the track control block would have been corrupted.
3321 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3322 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3323 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 -07003324 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003325 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003326 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 return 0;
3328 }
3329
3330 return bufferStart;
3331}
3332
3333// ----------------------------------------------------------------------------
3334
3335// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3336AudioFlinger::PlaybackThread::Track::Track(
3337 const wp<ThreadBase>& thread,
3338 const sp<Client>& client,
3339 int streamType,
3340 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003341 uint32_t format,
3342 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003343 int frameCount,
3344 const sp<IMemory>& sharedBuffer,
3345 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003346 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003347 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3348 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349{
3350 if (mCblk != NULL) {
3351 sp<ThreadBase> baseThread = thread.promote();
3352 if (baseThread != 0) {
3353 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3354 mName = playbackThread->getTrackName_l();
3355 mMainBuffer = playbackThread->mixBuffer();
3356 }
Steve Block3856b092011-10-20 11:56:00 +01003357 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003358 if (mName < 0) {
3359 LOGE("no more track names available");
3360 }
3361 mVolume[0] = 1.0f;
3362 mVolume[1] = 1.0f;
3363 mStreamType = streamType;
3364 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3365 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003366 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003367 }
3368}
3369
3370AudioFlinger::PlaybackThread::Track::~Track()
3371{
Steve Block3856b092011-10-20 11:56:00 +01003372 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003373 sp<ThreadBase> thread = mThread.promote();
3374 if (thread != 0) {
3375 Mutex::Autolock _l(thread->mLock);
3376 mState = TERMINATED;
3377 }
3378}
3379
3380void AudioFlinger::PlaybackThread::Track::destroy()
3381{
3382 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3383 // by removing it from mTracks vector, so there is a risk that this Tracks's
3384 // desctructor is called. As the destructor needs to lock mLock,
3385 // we must acquire a strong reference on this Track before locking mLock
3386 // here so that the destructor is called only when exiting this function.
3387 // On the other hand, as long as Track::destroy() is only called by
3388 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3389 // this Track with its member mTrack.
3390 sp<Track> keep(this);
3391 { // scope for mLock
3392 sp<ThreadBase> thread = mThread.promote();
3393 if (thread != 0) {
3394 if (!isOutputTrack()) {
3395 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003396 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003397 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003398 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003399
3400 // to track the speaker usage
3401 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003402 }
3403 AudioSystem::releaseOutput(thread->id());
3404 }
3405 Mutex::Autolock _l(thread->mLock);
3406 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3407 playbackThread->destroyTrack_l(this);
3408 }
3409 }
3410}
3411
3412void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3413{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003414 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 -07003415 mName - AudioMixer::TRACK0,
3416 (mClient == NULL) ? getpid() : mClient->pid(),
3417 mStreamType,
3418 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003419 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003420 mSessionId,
3421 mFrameCount,
3422 mState,
3423 mMute,
3424 mFillingUpStatus,
3425 mCblk->sampleRate,
3426 mCblk->volume[0],
3427 mCblk->volume[1],
3428 mCblk->server,
3429 mCblk->user,
3430 (int)mMainBuffer,
3431 (int)mAuxBuffer);
3432}
3433
3434status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3435{
3436 audio_track_cblk_t* cblk = this->cblk();
3437 uint32_t framesReady;
3438 uint32_t framesReq = buffer->frameCount;
3439
3440 // Check if last stepServer failed, try to step now
3441 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3442 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003443 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003444 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3445 }
3446
3447 framesReady = cblk->framesReady();
3448
3449 if (LIKELY(framesReady)) {
3450 uint32_t s = cblk->server;
3451 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3452
3453 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3454 if (framesReq > framesReady) {
3455 framesReq = framesReady;
3456 }
3457 if (s + framesReq > bufferEnd) {
3458 framesReq = bufferEnd - s;
3459 }
3460
3461 buffer->raw = getBuffer(s, framesReq);
3462 if (buffer->raw == 0) goto getNextBuffer_exit;
3463
3464 buffer->frameCount = framesReq;
3465 return NO_ERROR;
3466 }
3467
3468getNextBuffer_exit:
3469 buffer->raw = 0;
3470 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003471 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472 return NOT_ENOUGH_DATA;
3473}
3474
3475bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003476 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477
3478 if (mCblk->framesReady() >= mCblk->frameCount ||
3479 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3480 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003481 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482 return true;
3483 }
3484 return false;
3485}
3486
3487status_t AudioFlinger::PlaybackThread::Track::start()
3488{
3489 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003490 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003491 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003492 sp<ThreadBase> thread = mThread.promote();
3493 if (thread != 0) {
3494 Mutex::Autolock _l(thread->mLock);
3495 int state = mState;
3496 // here the track could be either new, or restarted
3497 // in both cases "unstop" the track
3498 if (mState == PAUSED) {
3499 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003500 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003501 } else {
3502 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003503 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 }
3505
3506 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3507 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003508 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003509 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003510 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003511 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003512
3513 // to track the speaker usage
3514 if (status == NO_ERROR) {
3515 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3516 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003517 }
3518 if (status == NO_ERROR) {
3519 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3520 playbackThread->addTrack_l(this);
3521 } else {
3522 mState = state;
3523 }
3524 } else {
3525 status = BAD_VALUE;
3526 }
3527 return status;
3528}
3529
3530void AudioFlinger::PlaybackThread::Track::stop()
3531{
Steve Block3856b092011-10-20 11:56:00 +01003532 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 sp<ThreadBase> thread = mThread.promote();
3534 if (thread != 0) {
3535 Mutex::Autolock _l(thread->mLock);
3536 int state = mState;
3537 if (mState > STOPPED) {
3538 mState = STOPPED;
3539 // If the track is not active (PAUSED and buffers full), flush buffers
3540 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3541 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3542 reset();
3543 }
Steve Block3856b092011-10-20 11:56:00 +01003544 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003545 }
3546 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3547 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003548 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003549 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003550 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003551 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003552
3553 // to track the speaker usage
3554 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003555 }
3556 }
3557}
3558
3559void AudioFlinger::PlaybackThread::Track::pause()
3560{
Steve Block3856b092011-10-20 11:56:00 +01003561 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 sp<ThreadBase> thread = mThread.promote();
3563 if (thread != 0) {
3564 Mutex::Autolock _l(thread->mLock);
3565 if (mState == ACTIVE || mState == RESUMING) {
3566 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003567 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003568 if (!isOutputTrack()) {
3569 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003570 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003571 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003572 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003574
3575 // to track the speaker usage
3576 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003577 }
3578 }
3579 }
3580}
3581
3582void AudioFlinger::PlaybackThread::Track::flush()
3583{
Steve Block3856b092011-10-20 11:56:00 +01003584 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003585 sp<ThreadBase> thread = mThread.promote();
3586 if (thread != 0) {
3587 Mutex::Autolock _l(thread->mLock);
3588 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3589 return;
3590 }
3591 // No point remaining in PAUSED state after a flush => go to
3592 // STOPPED state
3593 mState = STOPPED;
3594
Eric Laurent38ccae22011-03-28 18:37:07 -07003595 // do not reset the track if it is still in the process of being stopped or paused.
3596 // this will be done by prepareTracks_l() when the track is stopped.
3597 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3598 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3599 reset();
3600 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 }
3602}
3603
3604void AudioFlinger::PlaybackThread::Track::reset()
3605{
3606 // Do not reset twice to avoid discarding data written just after a flush and before
3607 // the audioflinger thread detects the track is stopped.
3608 if (!mResetDone) {
3609 TrackBase::reset();
3610 // Force underrun condition to avoid false underrun callback until first data is
3611 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003612 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3613 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 mFillingUpStatus = FS_FILLING;
3615 mResetDone = true;
3616 }
3617}
3618
3619void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3620{
3621 mMute = muted;
3622}
3623
3624void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3625{
3626 mVolume[0] = left;
3627 mVolume[1] = right;
3628}
3629
3630status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3631{
3632 status_t status = DEAD_OBJECT;
3633 sp<ThreadBase> thread = mThread.promote();
3634 if (thread != 0) {
3635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3636 status = playbackThread->attachAuxEffect(this, EffectId);
3637 }
3638 return status;
3639}
3640
3641void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3642{
3643 mAuxEffectId = EffectId;
3644 mAuxBuffer = buffer;
3645}
3646
3647// ----------------------------------------------------------------------------
3648
3649// RecordTrack constructor must be called with AudioFlinger::mLock held
3650AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3651 const wp<ThreadBase>& thread,
3652 const sp<Client>& client,
3653 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003654 uint32_t format,
3655 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 int frameCount,
3657 uint32_t flags,
3658 int sessionId)
3659 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003660 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 mOverflow(false)
3662{
3663 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003664 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003665 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003666 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003667 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003668 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 } else {
3670 mCblk->frameSize = sizeof(int8_t);
3671 }
3672 }
3673}
3674
3675AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3676{
3677 sp<ThreadBase> thread = mThread.promote();
3678 if (thread != 0) {
3679 AudioSystem::releaseInput(thread->id());
3680 }
3681}
3682
3683status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3684{
3685 audio_track_cblk_t* cblk = this->cblk();
3686 uint32_t framesAvail;
3687 uint32_t framesReq = buffer->frameCount;
3688
3689 // Check if last stepServer failed, try to step now
3690 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3691 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003692 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003693 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3694 }
3695
3696 framesAvail = cblk->framesAvailable_l();
3697
3698 if (LIKELY(framesAvail)) {
3699 uint32_t s = cblk->server;
3700 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3701
3702 if (framesReq > framesAvail) {
3703 framesReq = framesAvail;
3704 }
3705 if (s + framesReq > bufferEnd) {
3706 framesReq = bufferEnd - s;
3707 }
3708
3709 buffer->raw = getBuffer(s, framesReq);
3710 if (buffer->raw == 0) goto getNextBuffer_exit;
3711
3712 buffer->frameCount = framesReq;
3713 return NO_ERROR;
3714 }
3715
3716getNextBuffer_exit:
3717 buffer->raw = 0;
3718 buffer->frameCount = 0;
3719 return NOT_ENOUGH_DATA;
3720}
3721
3722status_t AudioFlinger::RecordThread::RecordTrack::start()
3723{
3724 sp<ThreadBase> thread = mThread.promote();
3725 if (thread != 0) {
3726 RecordThread *recordThread = (RecordThread *)thread.get();
3727 return recordThread->start(this);
3728 } else {
3729 return BAD_VALUE;
3730 }
3731}
3732
3733void AudioFlinger::RecordThread::RecordTrack::stop()
3734{
3735 sp<ThreadBase> thread = mThread.promote();
3736 if (thread != 0) {
3737 RecordThread *recordThread = (RecordThread *)thread.get();
3738 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003739 TrackBase::reset();
3740 // Force overerrun condition to avoid false overrun callback until first data is
3741 // read from buffer
3742 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003743 }
3744}
3745
3746void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3747{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003748 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003749 (mClient == NULL) ? getpid() : mClient->pid(),
3750 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003751 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 mSessionId,
3753 mFrameCount,
3754 mState,
3755 mCblk->sampleRate,
3756 mCblk->server,
3757 mCblk->user);
3758}
3759
3760
3761// ----------------------------------------------------------------------------
3762
3763AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3764 const wp<ThreadBase>& thread,
3765 DuplicatingThread *sourceThread,
3766 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003767 uint32_t format,
3768 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003769 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003770 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003771 mActive(false), mSourceThread(sourceThread)
3772{
3773
3774 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3775 if (mCblk != NULL) {
3776 mCblk->flags |= CBLK_DIRECTION_OUT;
3777 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3778 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3779 mOutBuffer.frameCount = 0;
3780 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003781 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003782 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3783 mCblk, mBuffer, mCblk->buffers,
3784 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003785 } else {
3786 LOGW("Error creating output track on thread %p", playbackThread);
3787 }
3788}
3789
3790AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3791{
3792 clearBufferQueue();
3793}
3794
3795status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3796{
3797 status_t status = Track::start();
3798 if (status != NO_ERROR) {
3799 return status;
3800 }
3801
3802 mActive = true;
3803 mRetryCount = 127;
3804 return status;
3805}
3806
3807void AudioFlinger::PlaybackThread::OutputTrack::stop()
3808{
3809 Track::stop();
3810 clearBufferQueue();
3811 mOutBuffer.frameCount = 0;
3812 mActive = false;
3813}
3814
3815bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3816{
3817 Buffer *pInBuffer;
3818 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003819 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003820 bool outputBufferFull = false;
3821 inBuffer.frameCount = frames;
3822 inBuffer.i16 = data;
3823
3824 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3825
3826 if (!mActive && frames != 0) {
3827 start();
3828 sp<ThreadBase> thread = mThread.promote();
3829 if (thread != 0) {
3830 MixerThread *mixerThread = (MixerThread *)thread.get();
3831 if (mCblk->frameCount > frames){
3832 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3833 uint32_t startFrames = (mCblk->frameCount - frames);
3834 pInBuffer = new Buffer;
3835 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3836 pInBuffer->frameCount = startFrames;
3837 pInBuffer->i16 = pInBuffer->mBuffer;
3838 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3839 mBufferQueue.add(pInBuffer);
3840 } else {
3841 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3842 }
3843 }
3844 }
3845 }
3846
3847 while (waitTimeLeftMs) {
3848 // First write pending buffers, then new data
3849 if (mBufferQueue.size()) {
3850 pInBuffer = mBufferQueue.itemAt(0);
3851 } else {
3852 pInBuffer = &inBuffer;
3853 }
3854
3855 if (pInBuffer->frameCount == 0) {
3856 break;
3857 }
3858
3859 if (mOutBuffer.frameCount == 0) {
3860 mOutBuffer.frameCount = pInBuffer->frameCount;
3861 nsecs_t startTime = systemTime();
3862 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003863 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003864 outputBufferFull = true;
3865 break;
3866 }
3867 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3868 if (waitTimeLeftMs >= waitTimeMs) {
3869 waitTimeLeftMs -= waitTimeMs;
3870 } else {
3871 waitTimeLeftMs = 0;
3872 }
3873 }
3874
3875 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3876 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3877 mCblk->stepUser(outFrames);
3878 pInBuffer->frameCount -= outFrames;
3879 pInBuffer->i16 += outFrames * channelCount;
3880 mOutBuffer.frameCount -= outFrames;
3881 mOutBuffer.i16 += outFrames * channelCount;
3882
3883 if (pInBuffer->frameCount == 0) {
3884 if (mBufferQueue.size()) {
3885 mBufferQueue.removeAt(0);
3886 delete [] pInBuffer->mBuffer;
3887 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003888 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889 } else {
3890 break;
3891 }
3892 }
3893 }
3894
3895 // If we could not write all frames, allocate a buffer and queue it for next time.
3896 if (inBuffer.frameCount) {
3897 sp<ThreadBase> thread = mThread.promote();
3898 if (thread != 0 && !thread->standby()) {
3899 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3900 pInBuffer = new Buffer;
3901 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3902 pInBuffer->frameCount = inBuffer.frameCount;
3903 pInBuffer->i16 = pInBuffer->mBuffer;
3904 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3905 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003906 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003907 } else {
3908 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3909 }
3910 }
3911 }
3912
3913 // Calling write() with a 0 length buffer, means that no more data will be written:
3914 // If no more buffers are pending, fill output track buffer to make sure it is started
3915 // by output mixer.
3916 if (frames == 0 && mBufferQueue.size() == 0) {
3917 if (mCblk->user < mCblk->frameCount) {
3918 frames = mCblk->frameCount - mCblk->user;
3919 pInBuffer = new Buffer;
3920 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3921 pInBuffer->frameCount = frames;
3922 pInBuffer->i16 = pInBuffer->mBuffer;
3923 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3924 mBufferQueue.add(pInBuffer);
3925 } else if (mActive) {
3926 stop();
3927 }
3928 }
3929
3930 return outputBufferFull;
3931}
3932
3933status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3934{
3935 int active;
3936 status_t result;
3937 audio_track_cblk_t* cblk = mCblk;
3938 uint32_t framesReq = buffer->frameCount;
3939
Steve Block3856b092011-10-20 11:56:00 +01003940// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003941 buffer->frameCount = 0;
3942
3943 uint32_t framesAvail = cblk->framesAvailable();
3944
3945
3946 if (framesAvail == 0) {
3947 Mutex::Autolock _l(cblk->lock);
3948 goto start_loop_here;
3949 while (framesAvail == 0) {
3950 active = mActive;
3951 if (UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003952 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953 return AudioTrack::NO_MORE_BUFFERS;
3954 }
3955 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3956 if (result != NO_ERROR) {
3957 return AudioTrack::NO_MORE_BUFFERS;
3958 }
3959 // read the server count again
3960 start_loop_here:
3961 framesAvail = cblk->framesAvailable_l();
3962 }
3963 }
3964
3965// if (framesAvail < framesReq) {
3966// return AudioTrack::NO_MORE_BUFFERS;
3967// }
3968
3969 if (framesReq > framesAvail) {
3970 framesReq = framesAvail;
3971 }
3972
3973 uint32_t u = cblk->user;
3974 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3975
3976 if (u + framesReq > bufferEnd) {
3977 framesReq = bufferEnd - u;
3978 }
3979
3980 buffer->frameCount = framesReq;
3981 buffer->raw = (void *)cblk->buffer(u);
3982 return NO_ERROR;
3983}
3984
3985
3986void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3987{
3988 size_t size = mBufferQueue.size();
3989 Buffer *pBuffer;
3990
3991 for (size_t i = 0; i < size; i++) {
3992 pBuffer = mBufferQueue.itemAt(i);
3993 delete [] pBuffer->mBuffer;
3994 delete pBuffer;
3995 }
3996 mBufferQueue.clear();
3997}
3998
3999// ----------------------------------------------------------------------------
4000
4001AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4002 : RefBase(),
4003 mAudioFlinger(audioFlinger),
4004 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4005 mPid(pid)
4006{
4007 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4008}
4009
4010// Client destructor must be called with AudioFlinger::mLock held
4011AudioFlinger::Client::~Client()
4012{
4013 mAudioFlinger->removeClient_l(mPid);
4014}
4015
4016const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4017{
4018 return mMemoryDealer;
4019}
4020
4021// ----------------------------------------------------------------------------
4022
4023AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4024 const sp<IAudioFlingerClient>& client,
4025 pid_t pid)
4026 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4027{
4028}
4029
4030AudioFlinger::NotificationClient::~NotificationClient()
4031{
4032 mClient.clear();
4033}
4034
4035void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4036{
4037 sp<NotificationClient> keep(this);
4038 {
4039 mAudioFlinger->removeNotificationClient(mPid);
4040 }
4041}
4042
4043// ----------------------------------------------------------------------------
4044
4045AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4046 : BnAudioTrack(),
4047 mTrack(track)
4048{
4049}
4050
4051AudioFlinger::TrackHandle::~TrackHandle() {
4052 // just stop the track on deletion, associated resources
4053 // will be freed from the main thread once all pending buffers have
4054 // been played. Unless it's not in the active track list, in which
4055 // case we free everything now...
4056 mTrack->destroy();
4057}
4058
4059status_t AudioFlinger::TrackHandle::start() {
4060 return mTrack->start();
4061}
4062
4063void AudioFlinger::TrackHandle::stop() {
4064 mTrack->stop();
4065}
4066
4067void AudioFlinger::TrackHandle::flush() {
4068 mTrack->flush();
4069}
4070
4071void AudioFlinger::TrackHandle::mute(bool e) {
4072 mTrack->mute(e);
4073}
4074
4075void AudioFlinger::TrackHandle::pause() {
4076 mTrack->pause();
4077}
4078
4079void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4080 mTrack->setVolume(left, right);
4081}
4082
4083sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4084 return mTrack->getCblk();
4085}
4086
4087status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4088{
4089 return mTrack->attachAuxEffect(EffectId);
4090}
4091
4092status_t AudioFlinger::TrackHandle::onTransact(
4093 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4094{
4095 return BnAudioTrack::onTransact(code, data, reply, flags);
4096}
4097
4098// ----------------------------------------------------------------------------
4099
4100sp<IAudioRecord> AudioFlinger::openRecord(
4101 pid_t pid,
4102 int input,
4103 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004104 uint32_t format,
4105 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106 int frameCount,
4107 uint32_t flags,
4108 int *sessionId,
4109 status_t *status)
4110{
4111 sp<RecordThread::RecordTrack> recordTrack;
4112 sp<RecordHandle> recordHandle;
4113 sp<Client> client;
4114 wp<Client> wclient;
4115 status_t lStatus;
4116 RecordThread *thread;
4117 size_t inFrameCount;
4118 int lSessionId;
4119
4120 // check calling permissions
4121 if (!recordingAllowed()) {
4122 lStatus = PERMISSION_DENIED;
4123 goto Exit;
4124 }
4125
4126 // add client to list
4127 { // scope for mLock
4128 Mutex::Autolock _l(mLock);
4129 thread = checkRecordThread_l(input);
4130 if (thread == NULL) {
4131 lStatus = BAD_VALUE;
4132 goto Exit;
4133 }
4134
4135 wclient = mClients.valueFor(pid);
4136 if (wclient != NULL) {
4137 client = wclient.promote();
4138 } else {
4139 client = new Client(this, pid);
4140 mClients.add(pid, client);
4141 }
4142
4143 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004144 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004145 lSessionId = *sessionId;
4146 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004147 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 if (sessionId != NULL) {
4149 *sessionId = lSessionId;
4150 }
4151 }
4152 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004153 recordTrack = thread->createRecordTrack_l(client,
4154 sampleRate,
4155 format,
4156 channelMask,
4157 frameCount,
4158 flags,
4159 lSessionId,
4160 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004162 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4164 // destructor is called by the TrackBase destructor with mLock held
4165 client.clear();
4166 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004167 goto Exit;
4168 }
4169
4170 // return to handle to client
4171 recordHandle = new RecordHandle(recordTrack);
4172 lStatus = NO_ERROR;
4173
4174Exit:
4175 if (status) {
4176 *status = lStatus;
4177 }
4178 return recordHandle;
4179}
4180
4181// ----------------------------------------------------------------------------
4182
4183AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4184 : BnAudioRecord(),
4185 mRecordTrack(recordTrack)
4186{
4187}
4188
4189AudioFlinger::RecordHandle::~RecordHandle() {
4190 stop();
4191}
4192
4193status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004194 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 return mRecordTrack->start();
4196}
4197
4198void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004199 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 mRecordTrack->stop();
4201}
4202
4203sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4204 return mRecordTrack->getCblk();
4205}
4206
4207status_t AudioFlinger::RecordHandle::onTransact(
4208 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4209{
4210 return BnAudioRecord::onTransact(code, data, reply, flags);
4211}
4212
4213// ----------------------------------------------------------------------------
4214
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004215AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4216 AudioStreamIn *input,
4217 uint32_t sampleRate,
4218 uint32_t channels,
4219 int id,
4220 uint32_t device) :
4221 ThreadBase(audioFlinger, id, device),
4222 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004223{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004224 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004225
4226 snprintf(mName, kNameLength, "AudioIn_%d", id);
4227
Dima Zavinfce7a472011-04-19 22:30:36 -07004228 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004229 mReqSampleRate = sampleRate;
4230 readInputParameters();
4231}
4232
4233
4234AudioFlinger::RecordThread::~RecordThread()
4235{
4236 delete[] mRsmpInBuffer;
4237 if (mResampler != 0) {
4238 delete mResampler;
4239 delete[] mRsmpOutBuffer;
4240 }
4241}
4242
4243void AudioFlinger::RecordThread::onFirstRef()
4244{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004245 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004246}
4247
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004248status_t AudioFlinger::RecordThread::readyToRun()
4249{
4250 status_t status = initCheck();
4251 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4252 return status;
4253}
4254
Mathias Agopian65ab4712010-07-14 17:59:35 -07004255bool AudioFlinger::RecordThread::threadLoop()
4256{
4257 AudioBufferProvider::Buffer buffer;
4258 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004259 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260
Eric Laurent44d98482010-09-30 16:12:31 -07004261 nsecs_t lastWarning = 0;
4262
Eric Laurentfeb0db62011-07-22 09:04:31 -07004263 acquireWakeLock();
4264
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265 // start recording
4266 while (!exitPending()) {
4267
4268 processConfigEvents();
4269
4270 { // scope for mLock
4271 Mutex::Autolock _l(mLock);
4272 checkForNewParameters_l();
4273 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4274 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004275 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276 mStandby = true;
4277 }
4278
4279 if (exitPending()) break;
4280
Eric Laurentfeb0db62011-07-22 09:04:31 -07004281 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004282 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 // go to sleep
4284 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004285 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004286 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004287 continue;
4288 }
4289 if (mActiveTrack != 0) {
4290 if (mActiveTrack->mState == TrackBase::PAUSING) {
4291 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004292 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004293 mStandby = true;
4294 }
4295 mActiveTrack.clear();
4296 mStartStopCond.broadcast();
4297 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4298 if (mReqChannelCount != mActiveTrack->channelCount()) {
4299 mActiveTrack.clear();
4300 mStartStopCond.broadcast();
4301 } else if (mBytesRead != 0) {
4302 // record start succeeds only if first read from audio input
4303 // succeeds
4304 if (mBytesRead > 0) {
4305 mActiveTrack->mState = TrackBase::ACTIVE;
4306 } else {
4307 mActiveTrack.clear();
4308 }
4309 mStartStopCond.broadcast();
4310 }
4311 mStandby = false;
4312 }
4313 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004314 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004315 }
4316
4317 if (mActiveTrack != 0) {
4318 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4319 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004320 unlockEffectChains(effectChains);
4321 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 continue;
4323 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004324 for (size_t i = 0; i < effectChains.size(); i ++) {
4325 effectChains[i]->process_l();
4326 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004327
Mathias Agopian65ab4712010-07-14 17:59:35 -07004328 buffer.frameCount = mFrameCount;
4329 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4330 size_t framesOut = buffer.frameCount;
4331 if (mResampler == 0) {
4332 // no resampling
4333 while (framesOut) {
4334 size_t framesIn = mFrameCount - mRsmpInIndex;
4335 if (framesIn) {
4336 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4337 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4338 if (framesIn > framesOut)
4339 framesIn = framesOut;
4340 mRsmpInIndex += framesIn;
4341 framesOut -= framesIn;
4342 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004343 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004344 memcpy(dst, src, framesIn * mFrameSize);
4345 } else {
4346 int16_t *src16 = (int16_t *)src;
4347 int16_t *dst16 = (int16_t *)dst;
4348 if (mChannelCount == 1) {
4349 while (framesIn--) {
4350 *dst16++ = *src16;
4351 *dst16++ = *src16++;
4352 }
4353 } else {
4354 while (framesIn--) {
4355 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4356 src16 += 2;
4357 }
4358 }
4359 }
4360 }
4361 if (framesOut && mFrameCount == mRsmpInIndex) {
4362 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004363 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004364 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004365 framesOut = 0;
4366 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004367 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 mRsmpInIndex = 0;
4369 }
4370 if (mBytesRead < 0) {
4371 LOGE("Error reading audio input");
4372 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4373 // Force input into standby so that it tries to
4374 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004375 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004376 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004377 }
4378 mRsmpInIndex = mFrameCount;
4379 framesOut = 0;
4380 buffer.frameCount = 0;
4381 }
4382 }
4383 }
4384 } else {
4385 // resampling
4386
4387 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4388 // alter output frame count as if we were expecting stereo samples
4389 if (mChannelCount == 1 && mReqChannelCount == 1) {
4390 framesOut >>= 1;
4391 }
4392 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4393 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4394 // are 32 bit aligned which should be always true.
4395 if (mChannelCount == 2 && mReqChannelCount == 1) {
4396 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4397 // the resampler always outputs stereo samples: do post stereo to mono conversion
4398 int16_t *src = (int16_t *)mRsmpOutBuffer;
4399 int16_t *dst = buffer.i16;
4400 while (framesOut--) {
4401 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4402 src += 2;
4403 }
4404 } else {
4405 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4406 }
4407
4408 }
4409 mActiveTrack->releaseBuffer(&buffer);
4410 mActiveTrack->overflow();
4411 }
4412 // client isn't retrieving buffers fast enough
4413 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004414 if (!mActiveTrack->setOverflow()) {
4415 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004416 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent44d98482010-09-30 16:12:31 -07004417 LOGW("RecordThread: buffer overflow");
4418 lastWarning = now;
4419 }
4420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 // Release the processor for a while before asking for a new buffer.
4422 // This will give the application more chance to read from the buffer and
4423 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004424 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425 }
4426 }
Eric Laurentec437d82011-07-26 20:54:46 -07004427 // enable changes in effect chain
4428 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004429 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 }
4431
4432 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004433 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004434 }
4435 mActiveTrack.clear();
4436
4437 mStartStopCond.broadcast();
4438
Eric Laurentfeb0db62011-07-22 09:04:31 -07004439 releaseWakeLock();
4440
Steve Block3856b092011-10-20 11:56:00 +01004441 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004442 return false;
4443}
4444
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004445
4446sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4447 const sp<AudioFlinger::Client>& client,
4448 uint32_t sampleRate,
4449 int format,
4450 int channelMask,
4451 int frameCount,
4452 uint32_t flags,
4453 int sessionId,
4454 status_t *status)
4455{
4456 sp<RecordTrack> track;
4457 status_t lStatus;
4458
4459 lStatus = initCheck();
4460 if (lStatus != NO_ERROR) {
4461 LOGE("Audio driver not initialized.");
4462 goto Exit;
4463 }
4464
4465 { // scope for mLock
4466 Mutex::Autolock _l(mLock);
4467
4468 track = new RecordTrack(this, client, sampleRate,
4469 format, channelMask, frameCount, flags, sessionId);
4470
4471 if (track->getCblk() == NULL) {
4472 lStatus = NO_MEMORY;
4473 goto Exit;
4474 }
4475
4476 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004477 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4478 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004479 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004480 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4481 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004482 }
4483 lStatus = NO_ERROR;
4484
4485Exit:
4486 if (status) {
4487 *status = lStatus;
4488 }
4489 return track;
4490}
4491
Mathias Agopian65ab4712010-07-14 17:59:35 -07004492status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4493{
Steve Block3856b092011-10-20 11:56:00 +01004494 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495 sp <ThreadBase> strongMe = this;
4496 status_t status = NO_ERROR;
4497 {
4498 AutoMutex lock(&mLock);
4499 if (mActiveTrack != 0) {
4500 if (recordTrack != mActiveTrack.get()) {
4501 status = -EBUSY;
4502 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4503 mActiveTrack->mState = TrackBase::ACTIVE;
4504 }
4505 return status;
4506 }
4507
4508 recordTrack->mState = TrackBase::IDLE;
4509 mActiveTrack = recordTrack;
4510 mLock.unlock();
4511 status_t status = AudioSystem::startInput(mId);
4512 mLock.lock();
4513 if (status != NO_ERROR) {
4514 mActiveTrack.clear();
4515 return status;
4516 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004517 mRsmpInIndex = mFrameCount;
4518 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004519 if (mResampler != NULL) {
4520 mResampler->reset();
4521 }
4522 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004524 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 mWaitWorkCV.signal();
4526 // do not wait for mStartStopCond if exiting
4527 if (mExiting) {
4528 mActiveTrack.clear();
4529 status = INVALID_OPERATION;
4530 goto startError;
4531 }
4532 mStartStopCond.wait(mLock);
4533 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004534 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 status = BAD_VALUE;
4536 goto startError;
4537 }
Steve Block3856b092011-10-20 11:56:00 +01004538 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539 return status;
4540 }
4541startError:
4542 AudioSystem::stopInput(mId);
4543 return status;
4544}
4545
4546void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004547 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 sp <ThreadBase> strongMe = this;
4549 {
4550 AutoMutex lock(&mLock);
4551 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4552 mActiveTrack->mState = TrackBase::PAUSING;
4553 // do not wait for mStartStopCond if exiting
4554 if (mExiting) {
4555 return;
4556 }
4557 mStartStopCond.wait(mLock);
4558 // if we have been restarted, recordTrack == mActiveTrack.get() here
4559 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4560 mLock.unlock();
4561 AudioSystem::stopInput(mId);
4562 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004563 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 }
4565 }
4566 }
4567}
4568
4569status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4570{
4571 const size_t SIZE = 256;
4572 char buffer[SIZE];
4573 String8 result;
4574 pid_t pid = 0;
4575
4576 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4577 result.append(buffer);
4578
4579 if (mActiveTrack != 0) {
4580 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004581 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582 mActiveTrack->dump(buffer, SIZE);
4583 result.append(buffer);
4584
4585 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4586 result.append(buffer);
4587 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4588 result.append(buffer);
4589 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4590 result.append(buffer);
4591 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4592 result.append(buffer);
4593 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4594 result.append(buffer);
4595
4596
4597 } else {
4598 result.append("No record client\n");
4599 }
4600 write(fd, result.string(), result.size());
4601
4602 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004603 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604
4605 return NO_ERROR;
4606}
4607
4608status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4609{
4610 size_t framesReq = buffer->frameCount;
4611 size_t framesReady = mFrameCount - mRsmpInIndex;
4612 int channelCount;
4613
4614 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004615 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004616 if (mBytesRead < 0) {
4617 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4618 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4619 // Force input into standby so that it tries to
4620 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004621 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004622 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004623 }
4624 buffer->raw = 0;
4625 buffer->frameCount = 0;
4626 return NOT_ENOUGH_DATA;
4627 }
4628 mRsmpInIndex = 0;
4629 framesReady = mFrameCount;
4630 }
4631
4632 if (framesReq > framesReady) {
4633 framesReq = framesReady;
4634 }
4635
4636 if (mChannelCount == 1 && mReqChannelCount == 2) {
4637 channelCount = 1;
4638 } else {
4639 channelCount = 2;
4640 }
4641 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4642 buffer->frameCount = framesReq;
4643 return NO_ERROR;
4644}
4645
4646void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4647{
4648 mRsmpInIndex += buffer->frameCount;
4649 buffer->frameCount = 0;
4650}
4651
4652bool AudioFlinger::RecordThread::checkForNewParameters_l()
4653{
4654 bool reconfig = false;
4655
4656 while (!mNewParameters.isEmpty()) {
4657 status_t status = NO_ERROR;
4658 String8 keyValuePair = mNewParameters[0];
4659 AudioParameter param = AudioParameter(keyValuePair);
4660 int value;
4661 int reqFormat = mFormat;
4662 int reqSamplingRate = mReqSampleRate;
4663 int reqChannelCount = mReqChannelCount;
4664
4665 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4666 reqSamplingRate = value;
4667 reconfig = true;
4668 }
4669 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4670 reqFormat = value;
4671 reconfig = true;
4672 }
4673 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004674 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004675 reconfig = true;
4676 }
4677 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4678 // do not accept frame count changes if tracks are open as the track buffer
4679 // size depends on frame count and correct behavior would not be garantied
4680 // if frame count is changed after track creation
4681 if (mActiveTrack != 0) {
4682 status = INVALID_OPERATION;
4683 } else {
4684 reconfig = true;
4685 }
4686 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004687 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4688 // forward device change to effects that have requested to be
4689 // aware of attached audio device.
4690 for (size_t i = 0; i < mEffectChains.size(); i++) {
4691 mEffectChains[i]->setDevice_l(value);
4692 }
4693 // store input device and output device but do not forward output device to audio HAL.
4694 // Note that status is ignored by the caller for output device
4695 // (see AudioFlinger::setParameters()
4696 if (value & AUDIO_DEVICE_OUT_ALL) {
4697 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4698 status = BAD_VALUE;
4699 } else {
4700 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004701 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4702 if (mTrack != NULL) {
4703 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004704 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004705 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4706 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4707 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004708 }
4709 mDevice |= (uint32_t)value;
4710 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004711 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004712 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004714 mInput->stream->common.standby(&mInput->stream->common);
4715 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 }
4717 if (reconfig) {
4718 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004719 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004720 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004721 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4722 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004723 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004724 status = NO_ERROR;
4725 }
4726 if (status == NO_ERROR) {
4727 readInputParameters();
4728 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4729 }
4730 }
4731 }
4732
4733 mNewParameters.removeAt(0);
4734
4735 mParamStatus = status;
4736 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004737 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4738 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004739 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740 }
4741 return reconfig;
4742}
4743
4744String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4745{
Dima Zavinfce7a472011-04-19 22:30:36 -07004746 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004747 String8 out_s8 = String8();
4748
4749 Mutex::Autolock _l(mLock);
4750 if (initCheck() != NO_ERROR) {
4751 return out_s8;
4752 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004753
Dima Zavin799a70e2011-04-18 16:57:27 -07004754 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004755 out_s8 = String8(s);
4756 free(s);
4757 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004758}
4759
4760void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4761 AudioSystem::OutputDescriptor desc;
4762 void *param2 = 0;
4763
4764 switch (event) {
4765 case AudioSystem::INPUT_OPENED:
4766 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004767 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004768 desc.samplingRate = mSampleRate;
4769 desc.format = mFormat;
4770 desc.frameCount = mFrameCount;
4771 desc.latency = 0;
4772 param2 = &desc;
4773 break;
4774
4775 case AudioSystem::INPUT_CLOSED:
4776 default:
4777 break;
4778 }
4779 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4780}
4781
4782void AudioFlinger::RecordThread::readInputParameters()
4783{
4784 if (mRsmpInBuffer) delete mRsmpInBuffer;
4785 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4786 if (mResampler) delete mResampler;
4787 mResampler = 0;
4788
Dima Zavin799a70e2011-04-18 16:57:27 -07004789 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004790 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4791 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004792 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4793 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4794 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004795 mFrameCount = mInputBytes / mFrameSize;
4796 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4797
4798 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4799 {
4800 int channelCount;
4801 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4802 // stereo to mono post process as the resampler always outputs stereo.
4803 if (mChannelCount == 1 && mReqChannelCount == 2) {
4804 channelCount = 1;
4805 } else {
4806 channelCount = 2;
4807 }
4808 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4809 mResampler->setSampleRate(mSampleRate);
4810 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4811 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4812
4813 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4814 if (mChannelCount == 1 && mReqChannelCount == 1) {
4815 mFrameCount >>= 1;
4816 }
4817
4818 }
4819 mRsmpInIndex = mFrameCount;
4820}
4821
4822unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4823{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004824 Mutex::Autolock _l(mLock);
4825 if (initCheck() != NO_ERROR) {
4826 return 0;
4827 }
4828
Dima Zavin799a70e2011-04-18 16:57:27 -07004829 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004830}
4831
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004832uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4833{
4834 Mutex::Autolock _l(mLock);
4835 uint32_t result = 0;
4836 if (getEffectChain_l(sessionId) != 0) {
4837 result = EFFECT_SESSION;
4838 }
4839
4840 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4841 result |= TRACK_SESSION;
4842 }
4843
4844 return result;
4845}
4846
Eric Laurent59bd0da2011-08-01 09:52:20 -07004847AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4848{
4849 Mutex::Autolock _l(mLock);
4850 return mTrack;
4851}
4852
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004853AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4854{
4855 Mutex::Autolock _l(mLock);
4856 return mInput;
4857}
4858
4859AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4860{
4861 Mutex::Autolock _l(mLock);
4862 AudioStreamIn *input = mInput;
4863 mInput = NULL;
4864 return input;
4865}
4866
4867// this method must always be called either with ThreadBase mLock held or inside the thread loop
4868audio_stream_t* AudioFlinger::RecordThread::stream()
4869{
4870 if (mInput == NULL) {
4871 return NULL;
4872 }
4873 return &mInput->stream->common;
4874}
4875
4876
Mathias Agopian65ab4712010-07-14 17:59:35 -07004877// ----------------------------------------------------------------------------
4878
4879int AudioFlinger::openOutput(uint32_t *pDevices,
4880 uint32_t *pSamplingRate,
4881 uint32_t *pFormat,
4882 uint32_t *pChannels,
4883 uint32_t *pLatencyMs,
4884 uint32_t flags)
4885{
4886 status_t status;
4887 PlaybackThread *thread = NULL;
4888 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4889 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4890 uint32_t format = pFormat ? *pFormat : 0;
4891 uint32_t channels = pChannels ? *pChannels : 0;
4892 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004893 audio_stream_out_t *outStream;
4894 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895
Steve Block3856b092011-10-20 11:56:00 +01004896 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004897 pDevices ? *pDevices : 0,
4898 samplingRate,
4899 format,
4900 channels,
4901 flags);
4902
4903 if (pDevices == NULL || *pDevices == 0) {
4904 return 0;
4905 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004906
Mathias Agopian65ab4712010-07-14 17:59:35 -07004907 Mutex::Autolock _l(mLock);
4908
Dima Zavin799a70e2011-04-18 16:57:27 -07004909 outHwDev = findSuitableHwDev_l(*pDevices);
4910 if (outHwDev == NULL)
4911 return 0;
4912
4913 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4914 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004915 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004916 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 samplingRate,
4918 format,
4919 channels,
4920 status);
4921
4922 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004923 if (outStream != NULL) {
4924 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004925 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004926
Dima Zavinfce7a472011-04-19 22:30:36 -07004927 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4928 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4929 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004930 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004931 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004932 } else {
4933 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004934 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 }
4936 mPlaybackThreads.add(id, thread);
4937
4938 if (pSamplingRate) *pSamplingRate = samplingRate;
4939 if (pFormat) *pFormat = format;
4940 if (pChannels) *pChannels = channels;
4941 if (pLatencyMs) *pLatencyMs = thread->latency();
4942
4943 // notify client processes of the new output creation
4944 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4945 return id;
4946 }
4947
4948 return 0;
4949}
4950
4951int AudioFlinger::openDuplicateOutput(int output1, int output2)
4952{
4953 Mutex::Autolock _l(mLock);
4954 MixerThread *thread1 = checkMixerThread_l(output1);
4955 MixerThread *thread2 = checkMixerThread_l(output2);
4956
4957 if (thread1 == NULL || thread2 == NULL) {
4958 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4959 return 0;
4960 }
4961
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004962 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004963 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4964 thread->addOutputTrack(thread2);
4965 mPlaybackThreads.add(id, thread);
4966 // notify client processes of the new output creation
4967 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4968 return id;
4969}
4970
4971status_t AudioFlinger::closeOutput(int output)
4972{
4973 // keep strong reference on the playback thread so that
4974 // it is not destroyed while exit() is executed
4975 sp <PlaybackThread> thread;
4976 {
4977 Mutex::Autolock _l(mLock);
4978 thread = checkPlaybackThread_l(output);
4979 if (thread == NULL) {
4980 return BAD_VALUE;
4981 }
4982
Steve Block3856b092011-10-20 11:56:00 +01004983 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004984
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004985 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004986 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004987 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004988 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4989 dupThread->removeOutputTrack((MixerThread *)thread.get());
4990 }
4991 }
4992 }
4993 void *param2 = 0;
4994 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4995 mPlaybackThreads.removeItem(output);
4996 }
4997 thread->exit();
4998
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004999 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005000 AudioStreamOut *out = thread->clearOutput();
5001 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005002 out->hwDev->close_output_stream(out->hwDev, out->stream);
5003 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004 }
5005 return NO_ERROR;
5006}
5007
5008status_t AudioFlinger::suspendOutput(int output)
5009{
5010 Mutex::Autolock _l(mLock);
5011 PlaybackThread *thread = checkPlaybackThread_l(output);
5012
5013 if (thread == NULL) {
5014 return BAD_VALUE;
5015 }
5016
Steve Block3856b092011-10-20 11:56:00 +01005017 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005018 thread->suspend();
5019
5020 return NO_ERROR;
5021}
5022
5023status_t AudioFlinger::restoreOutput(int output)
5024{
5025 Mutex::Autolock _l(mLock);
5026 PlaybackThread *thread = checkPlaybackThread_l(output);
5027
5028 if (thread == NULL) {
5029 return BAD_VALUE;
5030 }
5031
Steve Block3856b092011-10-20 11:56:00 +01005032 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005033
5034 thread->restore();
5035
5036 return NO_ERROR;
5037}
5038
5039int AudioFlinger::openInput(uint32_t *pDevices,
5040 uint32_t *pSamplingRate,
5041 uint32_t *pFormat,
5042 uint32_t *pChannels,
5043 uint32_t acoustics)
5044{
5045 status_t status;
5046 RecordThread *thread = NULL;
5047 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5048 uint32_t format = pFormat ? *pFormat : 0;
5049 uint32_t channels = pChannels ? *pChannels : 0;
5050 uint32_t reqSamplingRate = samplingRate;
5051 uint32_t reqFormat = format;
5052 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005053 audio_stream_in_t *inStream;
5054 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005055
5056 if (pDevices == NULL || *pDevices == 0) {
5057 return 0;
5058 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005059
Mathias Agopian65ab4712010-07-14 17:59:35 -07005060 Mutex::Autolock _l(mLock);
5061
Dima Zavin799a70e2011-04-18 16:57:27 -07005062 inHwDev = findSuitableHwDev_l(*pDevices);
5063 if (inHwDev == NULL)
5064 return 0;
5065
5066 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5067 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005068 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005069 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005070 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005071 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 samplingRate,
5073 format,
5074 channels,
5075 acoustics,
5076 status);
5077
5078 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5079 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5080 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005081 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005082 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005084 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005085 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005086 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5087 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005088 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 }
5091
Dima Zavin799a70e2011-04-18 16:57:27 -07005092 if (inStream != NULL) {
5093 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5094
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005095 int id = nextUniqueId();
5096 // Start record thread
5097 // RecorThread require both input and output device indication to forward to audio
5098 // pre processing modules
5099 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5100 thread = new RecordThread(this,
5101 input,
5102 reqSamplingRate,
5103 reqChannels,
5104 id,
5105 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005106 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005107 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005108 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5109 if (pFormat) *pFormat = format;
5110 if (pChannels) *pChannels = reqChannels;
5111
Dima Zavin799a70e2011-04-18 16:57:27 -07005112 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113
5114 // notify client processes of the new input creation
5115 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5116 return id;
5117 }
5118
5119 return 0;
5120}
5121
5122status_t AudioFlinger::closeInput(int input)
5123{
5124 // keep strong reference on the record thread so that
5125 // it is not destroyed while exit() is executed
5126 sp <RecordThread> thread;
5127 {
5128 Mutex::Autolock _l(mLock);
5129 thread = checkRecordThread_l(input);
5130 if (thread == NULL) {
5131 return BAD_VALUE;
5132 }
5133
Steve Block3856b092011-10-20 11:56:00 +01005134 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005135 void *param2 = 0;
5136 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5137 mRecordThreads.removeItem(input);
5138 }
5139 thread->exit();
5140
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005141 AudioStreamIn *in = thread->clearInput();
5142 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005143 in->hwDev->close_input_stream(in->hwDev, in->stream);
5144 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005145
5146 return NO_ERROR;
5147}
5148
5149status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5150{
5151 Mutex::Autolock _l(mLock);
5152 MixerThread *dstThread = checkMixerThread_l(output);
5153 if (dstThread == NULL) {
5154 LOGW("setStreamOutput() bad output id %d", output);
5155 return BAD_VALUE;
5156 }
5157
Steve Block3856b092011-10-20 11:56:00 +01005158 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005159 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5160
Eric Laurent9f6530f2011-08-30 10:18:54 -07005161 dstThread->setStreamValid(stream, true);
5162
Mathias Agopian65ab4712010-07-14 17:59:35 -07005163 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5164 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5165 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005166 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005167 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005168 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005169 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 }
Eric Laurentde070132010-07-13 04:45:46 -07005171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172
5173 return NO_ERROR;
5174}
5175
5176
5177int AudioFlinger::newAudioSessionId()
5178{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005179 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180}
5181
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005182void AudioFlinger::acquireAudioSessionId(int audioSession)
5183{
5184 Mutex::Autolock _l(mLock);
5185 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005186 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005187 int num = mAudioSessionRefs.size();
5188 for (int i = 0; i< num; i++) {
5189 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5190 if (ref->sessionid == audioSession && ref->pid == caller) {
5191 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005192 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005193 return;
5194 }
5195 }
5196 AudioSessionRef *ref = new AudioSessionRef();
5197 ref->sessionid = audioSession;
5198 ref->pid = caller;
5199 ref->cnt = 1;
5200 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005201 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005202}
5203
5204void AudioFlinger::releaseAudioSessionId(int audioSession)
5205{
5206 Mutex::Autolock _l(mLock);
5207 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005208 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005209 int num = mAudioSessionRefs.size();
5210 for (int i = 0; i< num; i++) {
5211 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5212 if (ref->sessionid == audioSession && ref->pid == caller) {
5213 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005214 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005215 if (ref->cnt == 0) {
5216 mAudioSessionRefs.removeAt(i);
5217 delete ref;
5218 purgeStaleEffects_l();
5219 }
5220 return;
5221 }
5222 }
5223 LOGW("session id %d not found for pid %d", audioSession, caller);
5224}
5225
5226void AudioFlinger::purgeStaleEffects_l() {
5227
Steve Block3856b092011-10-20 11:56:00 +01005228 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005229
5230 Vector< sp<EffectChain> > chains;
5231
5232 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5233 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5234 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5235 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005236 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5237 chains.push(ec);
5238 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005239 }
5240 }
5241 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5242 sp<RecordThread> t = mRecordThreads.valueAt(i);
5243 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5244 sp<EffectChain> ec = t->mEffectChains[j];
5245 chains.push(ec);
5246 }
5247 }
5248
5249 for (size_t i = 0; i < chains.size(); i++) {
5250 sp<EffectChain> ec = chains[i];
5251 int sessionid = ec->sessionId();
5252 sp<ThreadBase> t = ec->mThread.promote();
5253 if (t == 0) {
5254 continue;
5255 }
5256 size_t numsessionrefs = mAudioSessionRefs.size();
5257 bool found = false;
5258 for (size_t k = 0; k < numsessionrefs; k++) {
5259 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5260 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005261 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005262 sessionid, ref->pid, ref->cnt);
5263 found = true;
5264 break;
5265 }
5266 }
5267 if (!found) {
5268 // remove all effects from the chain
5269 while (ec->mEffects.size()) {
5270 sp<EffectModule> effect = ec->mEffects[0];
5271 effect->unPin();
5272 Mutex::Autolock _l (t->mLock);
5273 t->removeEffect_l(effect);
5274 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5275 sp<EffectHandle> handle = effect->mHandles[j].promote();
5276 if (handle != 0) {
5277 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005278 if (handle->mHasControl && handle->mEnabled) {
5279 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5280 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005281 }
5282 }
5283 AudioSystem::unregisterEffect(effect->id());
5284 }
5285 }
5286 }
5287 return;
5288}
5289
Mathias Agopian65ab4712010-07-14 17:59:35 -07005290// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5291AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5292{
5293 PlaybackThread *thread = NULL;
5294 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5295 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5296 }
5297 return thread;
5298}
5299
5300// checkMixerThread_l() must be called with AudioFlinger::mLock held
5301AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5302{
5303 PlaybackThread *thread = checkPlaybackThread_l(output);
5304 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005305 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306 thread = NULL;
5307 }
5308 }
5309 return (MixerThread *)thread;
5310}
5311
5312// checkRecordThread_l() must be called with AudioFlinger::mLock held
5313AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5314{
5315 RecordThread *thread = NULL;
5316 if (mRecordThreads.indexOfKey(input) >= 0) {
5317 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5318 }
5319 return thread;
5320}
5321
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005322uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005324 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005325}
5326
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005327AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5328{
5329 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5330 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005331 AudioStreamOut *output = thread->getOutput();
5332 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005333 return thread;
5334 }
5335 }
5336 return NULL;
5337}
5338
5339uint32_t AudioFlinger::primaryOutputDevice_l()
5340{
5341 PlaybackThread *thread = primaryPlaybackThread_l();
5342
5343 if (thread == NULL) {
5344 return 0;
5345 }
5346
5347 return thread->device();
5348}
5349
5350
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351// ----------------------------------------------------------------------------
5352// Effect management
5353// ----------------------------------------------------------------------------
5354
5355
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5357{
5358 Mutex::Autolock _l(mLock);
5359 return EffectQueryNumberEffects(numEffects);
5360}
5361
5362status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5363{
5364 Mutex::Autolock _l(mLock);
5365 return EffectQueryEffect(index, descriptor);
5366}
5367
5368status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5369{
5370 Mutex::Autolock _l(mLock);
5371 return EffectGetDescriptor(pUuid, descriptor);
5372}
5373
5374
Mathias Agopian65ab4712010-07-14 17:59:35 -07005375sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5376 effect_descriptor_t *pDesc,
5377 const sp<IEffectClient>& effectClient,
5378 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005379 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 int sessionId,
5381 status_t *status,
5382 int *id,
5383 int *enabled)
5384{
5385 status_t lStatus = NO_ERROR;
5386 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005387 effect_descriptor_t desc;
5388 sp<Client> client;
5389 wp<Client> wclient;
5390
Steve Block3856b092011-10-20 11:56:00 +01005391 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005392 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005393
5394 if (pDesc == NULL) {
5395 lStatus = BAD_VALUE;
5396 goto Exit;
5397 }
5398
Eric Laurent84e9a102010-09-23 16:10:16 -07005399 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005400 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005401 lStatus = PERMISSION_DENIED;
5402 goto Exit;
5403 }
5404
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005406 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005407 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005408 lStatus = PERMISSION_DENIED;
5409 goto Exit;
5410 }
5411
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005413 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005414 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005415 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005416 lStatus = BAD_VALUE;
5417 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005418 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005419 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005420 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005421 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005422 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005423 }
5424 }
5425
Mathias Agopian65ab4712010-07-14 17:59:35 -07005426 {
5427 Mutex::Autolock _l(mLock);
5428
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429
5430 if (!EffectIsNullUuid(&pDesc->uuid)) {
5431 // if uuid is specified, request effect descriptor
5432 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5433 if (lStatus < 0) {
5434 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5435 goto Exit;
5436 }
5437 } else {
5438 // if uuid is not specified, look for an available implementation
5439 // of the required type in effect factory
5440 if (EffectIsNullUuid(&pDesc->type)) {
5441 LOGW("createEffect() no effect type");
5442 lStatus = BAD_VALUE;
5443 goto Exit;
5444 }
5445 uint32_t numEffects = 0;
5446 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005447 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 bool found = false;
5449
5450 lStatus = EffectQueryNumberEffects(&numEffects);
5451 if (lStatus < 0) {
5452 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5453 goto Exit;
5454 }
5455 for (uint32_t i = 0; i < numEffects; i++) {
5456 lStatus = EffectQueryEffect(i, &desc);
5457 if (lStatus < 0) {
5458 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5459 continue;
5460 }
5461 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5462 // If matching type found save effect descriptor. If the session is
5463 // 0 and the effect is not auxiliary, continue enumeration in case
5464 // an auxiliary version of this effect type is available
5465 found = true;
5466 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005467 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005468 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5469 break;
5470 }
5471 }
5472 }
5473 if (!found) {
5474 lStatus = BAD_VALUE;
5475 LOGW("createEffect() effect not found");
5476 goto Exit;
5477 }
5478 // For same effect type, chose auxiliary version over insert version if
5479 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005481 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5482 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5483 }
5484 }
5485
5486 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005487 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005488 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5489 lStatus = INVALID_OPERATION;
5490 goto Exit;
5491 }
5492
Eric Laurent59255e42011-07-27 19:49:51 -07005493 // check recording permission for visualizer
5494 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5495 !recordingAllowed()) {
5496 lStatus = PERMISSION_DENIED;
5497 goto Exit;
5498 }
5499
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500 // return effect descriptor
5501 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5502
5503 // If output is not specified try to find a matching audio session ID in one of the
5504 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005505 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5506 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005507 // Note: io is never 0 when creating an effect on an input
5508 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005509 // look for the thread where the specified audio session is present
5510 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5511 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005512 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005513 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005514 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005515 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005516 if (io == 0) {
5517 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5518 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5519 io = mRecordThreads.keyAt(i);
5520 break;
5521 }
5522 }
5523 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005524 // If no output thread contains the requested session ID, default to
5525 // first output. The effect chain will be moved to the correct output
5526 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005527 if (io == 0 && mPlaybackThreads.size()) {
5528 io = mPlaybackThreads.keyAt(0);
5529 }
Steve Block3856b092011-10-20 11:56:00 +01005530 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005531 }
5532 ThreadBase *thread = checkRecordThread_l(io);
5533 if (thread == NULL) {
5534 thread = checkPlaybackThread_l(io);
5535 if (thread == NULL) {
5536 LOGE("createEffect() unknown output thread");
5537 lStatus = BAD_VALUE;
5538 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005539 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005540 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005541
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542 wclient = mClients.valueFor(pid);
5543
5544 if (wclient != NULL) {
5545 client = wclient.promote();
5546 } else {
5547 client = new Client(this, pid);
5548 mClients.add(pid, client);
5549 }
5550
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005551 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005552 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5553 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005554 if (handle != 0 && id != NULL) {
5555 *id = handle->id();
5556 }
5557 }
5558
5559Exit:
5560 if(status) {
5561 *status = lStatus;
5562 }
5563 return handle;
5564}
5565
Eric Laurent59255e42011-07-27 19:49:51 -07005566status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005567{
Steve Block3856b092011-10-20 11:56:00 +01005568 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005569 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005570 Mutex::Autolock _l(mLock);
5571 if (srcOutput == dstOutput) {
5572 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5573 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005574 }
Eric Laurentde070132010-07-13 04:45:46 -07005575 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5576 if (srcThread == NULL) {
5577 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5578 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 }
Eric Laurentde070132010-07-13 04:45:46 -07005580 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5581 if (dstThread == NULL) {
5582 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5583 return BAD_VALUE;
5584 }
5585
5586 Mutex::Autolock _dl(dstThread->mLock);
5587 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005588 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005589
Mathias Agopian65ab4712010-07-14 17:59:35 -07005590 return NO_ERROR;
5591}
5592
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005593// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005594status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005595 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005596 AudioFlinger::PlaybackThread *dstThread,
5597 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005598{
Steve Block3856b092011-10-20 11:56:00 +01005599 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005600 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005601
Eric Laurent59255e42011-07-27 19:49:51 -07005602 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005603 if (chain == 0) {
5604 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005605 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005606 return INVALID_OPERATION;
5607 }
5608
Eric Laurent39e94f82010-07-28 01:32:47 -07005609 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005610 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005611 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005612 // removed.
5613 srcThread->removeEffectChain_l(chain);
5614
5615 // transfer all effects one by one so that new effect chain is created on new thread with
5616 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005617 int dstOutput = dstThread->id();
5618 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005619 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005620 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5621 while (effect != 0) {
5622 srcThread->removeEffect_l(effect);
5623 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005624 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5625 if (effect->state() == EffectModule::ACTIVE ||
5626 effect->state() == EffectModule::STOPPING) {
5627 effect->start();
5628 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005629 // if the move request is not received from audio policy manager, the effect must be
5630 // re-registered with the new strategy and output
5631 if (dstChain == 0) {
5632 dstChain = effect->chain().promote();
5633 if (dstChain == 0) {
5634 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5635 srcThread->addEffect_l(effect);
5636 return NO_INIT;
5637 }
5638 strategy = dstChain->strategy();
5639 }
5640 if (reRegister) {
5641 AudioSystem::unregisterEffect(effect->id());
5642 AudioSystem::registerEffect(&effect->desc(),
5643 dstOutput,
5644 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005645 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005646 effect->id());
5647 }
Eric Laurentde070132010-07-13 04:45:46 -07005648 effect = chain->getEffectFromId_l(0);
5649 }
5650
5651 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652}
5653
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005654
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005656sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 const sp<AudioFlinger::Client>& client,
5658 const sp<IEffectClient>& effectClient,
5659 int32_t priority,
5660 int sessionId,
5661 effect_descriptor_t *desc,
5662 int *enabled,
5663 status_t *status
5664 )
5665{
5666 sp<EffectModule> effect;
5667 sp<EffectHandle> handle;
5668 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005670 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671 bool effectCreated = false;
5672 bool effectRegistered = false;
5673
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005674 lStatus = initCheck();
5675 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 goto Exit;
5678 }
5679
5680 // Do not allow effects with session ID 0 on direct output or duplicating threads
5681 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005682 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005683 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5684 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 lStatus = BAD_VALUE;
5686 goto Exit;
5687 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005688 // Only Pre processor effects are allowed on input threads and only on input threads
5689 if ((mType == RECORD &&
5690 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5691 (mType != RECORD &&
5692 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5693 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5694 desc->name, desc->flags, mType);
5695 lStatus = BAD_VALUE;
5696 goto Exit;
5697 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005698
Steve Block3856b092011-10-20 11:56:00 +01005699 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005700
5701 { // scope for mLock
5702 Mutex::Autolock _l(mLock);
5703
5704 // check for existing effect chain with the requested audio session
5705 chain = getEffectChain_l(sessionId);
5706 if (chain == 0) {
5707 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005708 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709 chain = new EffectChain(this, sessionId);
5710 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005711 chain->setStrategy(getStrategyForSession_l(sessionId));
5712 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005714 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 }
5716
Steve Block3856b092011-10-20 11:56:00 +01005717 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718
5719 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005720 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005722 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 if (lStatus != NO_ERROR) {
5724 goto Exit;
5725 }
5726 effectRegistered = true;
5727 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005728 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 lStatus = effect->status();
5730 if (lStatus != NO_ERROR) {
5731 goto Exit;
5732 }
Eric Laurentcab11242010-07-15 12:50:15 -07005733 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 if (lStatus != NO_ERROR) {
5735 goto Exit;
5736 }
5737 effectCreated = true;
5738
5739 effect->setDevice(mDevice);
5740 effect->setMode(mAudioFlinger->getMode());
5741 }
5742 // create effect handle and connect it to effect module
5743 handle = new EffectHandle(effect, client, effectClient, priority);
5744 lStatus = effect->addHandle(handle);
5745 if (enabled) {
5746 *enabled = (int)effect->isEnabled();
5747 }
5748 }
5749
5750Exit:
5751 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005752 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005753 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005754 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005755 }
5756 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005757 AudioSystem::unregisterEffect(effect->id());
5758 }
5759 if (chainCreated) {
5760 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 }
5762 handle.clear();
5763 }
5764
5765 if(status) {
5766 *status = lStatus;
5767 }
5768 return handle;
5769}
5770
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005771sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5772{
5773 sp<EffectModule> effect;
5774
5775 sp<EffectChain> chain = getEffectChain_l(sessionId);
5776 if (chain != 0) {
5777 effect = chain->getEffectFromId_l(effectId);
5778 }
5779 return effect;
5780}
5781
Eric Laurentde070132010-07-13 04:45:46 -07005782// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5783// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005784status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005785{
5786 // check for existing effect chain with the requested audio session
5787 int sessionId = effect->sessionId();
5788 sp<EffectChain> chain = getEffectChain_l(sessionId);
5789 bool chainCreated = false;
5790
5791 if (chain == 0) {
5792 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005793 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005794 chain = new EffectChain(this, sessionId);
5795 addEffectChain_l(chain);
5796 chain->setStrategy(getStrategyForSession_l(sessionId));
5797 chainCreated = true;
5798 }
Steve Block3856b092011-10-20 11:56:00 +01005799 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005800
5801 if (chain->getEffectFromId_l(effect->id()) != 0) {
5802 LOGW("addEffect_l() %p effect %s already present in chain %p",
5803 this, effect->desc().name, chain.get());
5804 return BAD_VALUE;
5805 }
5806
5807 status_t status = chain->addEffect_l(effect);
5808 if (status != NO_ERROR) {
5809 if (chainCreated) {
5810 removeEffectChain_l(chain);
5811 }
5812 return status;
5813 }
5814
5815 effect->setDevice(mDevice);
5816 effect->setMode(mAudioFlinger->getMode());
5817 return NO_ERROR;
5818}
5819
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005820void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005821
Steve Block3856b092011-10-20 11:56:00 +01005822 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005824 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5825 detachAuxEffect_l(effect->id());
5826 }
5827
5828 sp<EffectChain> chain = effect->chain().promote();
5829 if (chain != 0) {
5830 // remove effect chain if removing last effect
5831 if (chain->removeEffect_l(effect) == 0) {
5832 removeEffectChain_l(chain);
5833 }
5834 } else {
5835 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5836 }
5837}
5838
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005839void AudioFlinger::ThreadBase::lockEffectChains_l(
5840 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5841{
5842 effectChains = mEffectChains;
5843 for (size_t i = 0; i < mEffectChains.size(); i++) {
5844 mEffectChains[i]->lock();
5845 }
5846}
5847
5848void AudioFlinger::ThreadBase::unlockEffectChains(
5849 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5850{
5851 for (size_t i = 0; i < effectChains.size(); i++) {
5852 effectChains[i]->unlock();
5853 }
5854}
5855
5856sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5857{
5858 Mutex::Autolock _l(mLock);
5859 return getEffectChain_l(sessionId);
5860}
5861
5862sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5863{
5864 sp<EffectChain> chain;
5865
5866 size_t size = mEffectChains.size();
5867 for (size_t i = 0; i < size; i++) {
5868 if (mEffectChains[i]->sessionId() == sessionId) {
5869 chain = mEffectChains[i];
5870 break;
5871 }
5872 }
5873 return chain;
5874}
5875
5876void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5877{
5878 Mutex::Autolock _l(mLock);
5879 size_t size = mEffectChains.size();
5880 for (size_t i = 0; i < size; i++) {
5881 mEffectChains[i]->setMode_l(mode);
5882 }
5883}
5884
5885void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005886 const wp<EffectHandle>& handle,
5887 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005888
Mathias Agopian65ab4712010-07-14 17:59:35 -07005889 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005890 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005891 // delete the effect module if removing last handle on it
5892 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005893 if (!effect->isPinned() || unpiniflast) {
5894 removeEffect_l(effect);
5895 AudioSystem::unregisterEffect(effect->id());
5896 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005897 }
5898}
5899
5900status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5901{
5902 int session = chain->sessionId();
5903 int16_t *buffer = mMixBuffer;
5904 bool ownsBuffer = false;
5905
Steve Block3856b092011-10-20 11:56:00 +01005906 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005907 if (session > 0) {
5908 // Only one effect chain can be present in direct output thread and it uses
5909 // the mix buffer as input
5910 if (mType != DIRECT) {
5911 size_t numSamples = mFrameCount * mChannelCount;
5912 buffer = new int16_t[numSamples];
5913 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005914 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005915 ownsBuffer = true;
5916 }
5917
5918 // Attach all tracks with same session ID to this chain.
5919 for (size_t i = 0; i < mTracks.size(); ++i) {
5920 sp<Track> track = mTracks[i];
5921 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005922 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005923 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005924 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 }
5926 }
5927
5928 // indicate all active tracks in the chain
5929 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5930 sp<Track> track = mActiveTracks[i].promote();
5931 if (track == 0) continue;
5932 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005933 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005934 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005935 }
5936 }
5937 }
5938
5939 chain->setInBuffer(buffer, ownsBuffer);
5940 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005941 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005942 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005943 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5944 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005946 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5947 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005948 // Effect chain for other sessions are inserted at beginning of effect
5949 // chains list to be processed before output mix effects. Relative order between other
5950 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951 size_t size = mEffectChains.size();
5952 size_t i = 0;
5953 for (i = 0; i < size; i++) {
5954 if (mEffectChains[i]->sessionId() < session) break;
5955 }
5956 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005957 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958
5959 return NO_ERROR;
5960}
5961
5962size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5963{
5964 int session = chain->sessionId();
5965
Steve Block3856b092011-10-20 11:56:00 +01005966 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967
5968 for (size_t i = 0; i < mEffectChains.size(); i++) {
5969 if (chain == mEffectChains[i]) {
5970 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005971 // detach all active tracks from the chain
5972 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5973 sp<Track> track = mActiveTracks[i].promote();
5974 if (track == 0) continue;
5975 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005976 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005977 chain.get(), session);
5978 chain->decActiveTrackCnt();
5979 }
5980 }
5981
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 // detach all tracks with same session ID from this chain
5983 for (size_t i = 0; i < mTracks.size(); ++i) {
5984 sp<Track> track = mTracks[i];
5985 if (session == track->sessionId()) {
5986 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005987 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005988 }
5989 }
Eric Laurentde070132010-07-13 04:45:46 -07005990 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 }
5992 }
5993 return mEffectChains.size();
5994}
5995
Eric Laurentde070132010-07-13 04:45:46 -07005996status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5997 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998{
5999 Mutex::Autolock _l(mLock);
6000 return attachAuxEffect_l(track, EffectId);
6001}
6002
Eric Laurentde070132010-07-13 04:45:46 -07006003status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6004 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006005{
6006 status_t status = NO_ERROR;
6007
6008 if (EffectId == 0) {
6009 track->setAuxBuffer(0, NULL);
6010 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006011 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6012 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006013 if (effect != 0) {
6014 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6015 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6016 } else {
6017 status = INVALID_OPERATION;
6018 }
6019 } else {
6020 status = BAD_VALUE;
6021 }
6022 }
6023 return status;
6024}
6025
6026void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6027{
6028 for (size_t i = 0; i < mTracks.size(); ++i) {
6029 sp<Track> track = mTracks[i];
6030 if (track->auxEffectId() == effectId) {
6031 attachAuxEffect_l(track, 0);
6032 }
6033 }
6034}
6035
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006036status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6037{
6038 // only one chain per input thread
6039 if (mEffectChains.size() != 0) {
6040 return INVALID_OPERATION;
6041 }
Steve Block3856b092011-10-20 11:56:00 +01006042 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006043
6044 chain->setInBuffer(NULL);
6045 chain->setOutBuffer(NULL);
6046
Eric Laurent59255e42011-07-27 19:49:51 -07006047 checkSuspendOnAddEffectChain_l(chain);
6048
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006049 mEffectChains.add(chain);
6050
6051 return NO_ERROR;
6052}
6053
6054size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6055{
Steve Block3856b092011-10-20 11:56:00 +01006056 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 LOGW_IF(mEffectChains.size() != 1,
6058 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6059 chain.get(), mEffectChains.size(), this);
6060 if (mEffectChains.size() == 1) {
6061 mEffectChains.removeAt(0);
6062 }
6063 return 0;
6064}
6065
Mathias Agopian65ab4712010-07-14 17:59:35 -07006066// ----------------------------------------------------------------------------
6067// EffectModule implementation
6068// ----------------------------------------------------------------------------
6069
6070#undef LOG_TAG
6071#define LOG_TAG "AudioFlinger::EffectModule"
6072
6073AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6074 const wp<AudioFlinger::EffectChain>& chain,
6075 effect_descriptor_t *desc,
6076 int id,
6077 int sessionId)
6078 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006079 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080{
Steve Block3856b092011-10-20 11:56:00 +01006081 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006082 int lStatus;
6083 sp<ThreadBase> thread = mThread.promote();
6084 if (thread == 0) {
6085 return;
6086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087
6088 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6089
6090 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006091 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092
6093 if (mStatus != NO_ERROR) {
6094 return;
6095 }
6096 lStatus = init();
6097 if (lStatus < 0) {
6098 mStatus = lStatus;
6099 goto Error;
6100 }
6101
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006102 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6103 mPinned = true;
6104 }
Steve Block3856b092011-10-20 11:56:00 +01006105 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106 return;
6107Error:
6108 EffectRelease(mEffectInterface);
6109 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006110 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111}
6112
6113AudioFlinger::EffectModule::~EffectModule()
6114{
Steve Block3856b092011-10-20 11:56:00 +01006115 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006117 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6118 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6119 sp<ThreadBase> thread = mThread.promote();
6120 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006121 audio_stream_t *stream = thread->stream();
6122 if (stream != NULL) {
6123 stream->remove_audio_effect(stream, mEffectInterface);
6124 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006125 }
6126 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 // release effect engine
6128 EffectRelease(mEffectInterface);
6129 }
6130}
6131
6132status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6133{
6134 status_t status;
6135
6136 Mutex::Autolock _l(mLock);
6137 // First handle in mHandles has highest priority and controls the effect module
6138 int priority = handle->priority();
6139 size_t size = mHandles.size();
6140 sp<EffectHandle> h;
6141 size_t i;
6142 for (i = 0; i < size; i++) {
6143 h = mHandles[i].promote();
6144 if (h == 0) continue;
6145 if (h->priority() <= priority) break;
6146 }
6147 // if inserted in first place, move effect control from previous owner to this handle
6148 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006149 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006151 enabled = h->enabled();
6152 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 }
Eric Laurent59255e42011-07-27 19:49:51 -07006154 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 status = NO_ERROR;
6156 } else {
6157 status = ALREADY_EXISTS;
6158 }
Steve Block3856b092011-10-20 11:56:00 +01006159 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 mHandles.insertAt(handle, i);
6161 return status;
6162}
6163
6164size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6165{
6166 Mutex::Autolock _l(mLock);
6167 size_t size = mHandles.size();
6168 size_t i;
6169 for (i = 0; i < size; i++) {
6170 if (mHandles[i] == handle) break;
6171 }
6172 if (i == size) {
6173 return size;
6174 }
Steve Block3856b092011-10-20 11:56:00 +01006175 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006176
6177 bool enabled = false;
6178 EffectHandle *hdl = handle.unsafe_get();
6179 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006180 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006181 enabled = hdl->enabled();
6182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 mHandles.removeAt(i);
6184 size = mHandles.size();
6185 // if removed from first place, move effect control from this handle to next in line
6186 if (i == 0 && size != 0) {
6187 sp<EffectHandle> h = mHandles[0].promote();
6188 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006189 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006190 }
6191 }
6192
Eric Laurentec437d82011-07-26 20:54:46 -07006193 // Prevent calls to process() and other functions on effect interface from now on.
6194 // The effect engine will be released by the destructor when the last strong reference on
6195 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006196 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006197 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006198 }
6199
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 return size;
6201}
6202
Eric Laurent59255e42011-07-27 19:49:51 -07006203sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6204{
6205 Mutex::Autolock _l(mLock);
6206 sp<EffectHandle> handle;
6207 if (mHandles.size() != 0) {
6208 handle = mHandles[0].promote();
6209 }
6210 return handle;
6211}
6212
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006213void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214{
Steve Block3856b092011-10-20 11:56:00 +01006215 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 // keep a strong reference on this EffectModule to avoid calling the
6217 // destructor before we exit
6218 sp<EffectModule> keep(this);
6219 {
6220 sp<ThreadBase> thread = mThread.promote();
6221 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006222 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006223 }
6224 }
6225}
6226
6227void AudioFlinger::EffectModule::updateState() {
6228 Mutex::Autolock _l(mLock);
6229
6230 switch (mState) {
6231 case RESTART:
6232 reset_l();
6233 // FALL THROUGH
6234
6235 case STARTING:
6236 // clear auxiliary effect input buffer for next accumulation
6237 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6238 memset(mConfig.inputCfg.buffer.raw,
6239 0,
6240 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6241 }
6242 start_l();
6243 mState = ACTIVE;
6244 break;
6245 case STOPPING:
6246 stop_l();
6247 mDisableWaitCnt = mMaxDisableWaitCnt;
6248 mState = STOPPED;
6249 break;
6250 case STOPPED:
6251 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6252 // turn off sequence.
6253 if (--mDisableWaitCnt == 0) {
6254 reset_l();
6255 mState = IDLE;
6256 }
6257 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006258 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006259 break;
6260 }
6261}
6262
6263void AudioFlinger::EffectModule::process()
6264{
6265 Mutex::Autolock _l(mLock);
6266
Eric Laurentec437d82011-07-26 20:54:46 -07006267 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006268 mConfig.inputCfg.buffer.raw == NULL ||
6269 mConfig.outputCfg.buffer.raw == NULL) {
6270 return;
6271 }
6272
Eric Laurent8f45bd72010-08-31 13:50:07 -07006273 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6275 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6276 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6277 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006278 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 }
6280
6281 // do the actual processing in the effect engine
6282 int ret = (*mEffectInterface)->process(mEffectInterface,
6283 &mConfig.inputCfg.buffer,
6284 &mConfig.outputCfg.buffer);
6285
6286 // force transition to IDLE state when engine is ready
6287 if (mState == STOPPED && ret == -ENODATA) {
6288 mDisableWaitCnt = 1;
6289 }
6290
6291 // clear auxiliary effect input buffer for next accumulation
6292 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006293 memset(mConfig.inputCfg.buffer.raw, 0,
6294 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006295 }
6296 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006297 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6298 // If an insert effect is idle and input buffer is different from output buffer,
6299 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006301 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006302 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6303 int16_t *in = mConfig.inputCfg.buffer.s16;
6304 int16_t *out = mConfig.outputCfg.buffer.s16;
6305 for (size_t i = 0; i < frameCnt; i++) {
6306 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006308 }
6309 }
6310}
6311
6312void AudioFlinger::EffectModule::reset_l()
6313{
6314 if (mEffectInterface == NULL) {
6315 return;
6316 }
6317 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6318}
6319
6320status_t AudioFlinger::EffectModule::configure()
6321{
6322 uint32_t channels;
6323 if (mEffectInterface == NULL) {
6324 return NO_INIT;
6325 }
6326
6327 sp<ThreadBase> thread = mThread.promote();
6328 if (thread == 0) {
6329 return DEAD_OBJECT;
6330 }
6331
6332 // TODO: handle configuration of effects replacing track process
6333 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006334 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006335 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006336 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006337 }
6338
6339 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006340 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006341 } else {
6342 mConfig.inputCfg.channels = channels;
6343 }
6344 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006345 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6346 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347 mConfig.inputCfg.samplingRate = thread->sampleRate();
6348 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6349 mConfig.inputCfg.bufferProvider.cookie = NULL;
6350 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6351 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6352 mConfig.outputCfg.bufferProvider.cookie = NULL;
6353 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6354 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6355 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6356 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006357 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006358 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006359 // - in other sessions:
6360 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6361 // other effect: overwrites output buffer: input buffer == output buffer
6362 // Auxiliary effect:
6363 // accumulates in output buffer: input buffer != output buffer
6364 // Therefore: accumulate <=> input buffer != output buffer
6365 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6366 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6367 } else {
6368 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6369 }
6370 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6371 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6372 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6373 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6374
Steve Block3856b092011-10-20 11:56:00 +01006375 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006376 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6377
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006379 uint32_t size = sizeof(int);
6380 status_t status = (*mEffectInterface)->command(mEffectInterface,
6381 EFFECT_CMD_CONFIGURE,
6382 sizeof(effect_config_t),
6383 &mConfig,
6384 &size,
6385 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 if (status == 0) {
6387 status = cmdStatus;
6388 }
6389
6390 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6391 (1000 * mConfig.outputCfg.buffer.frameCount);
6392
6393 return status;
6394}
6395
6396status_t AudioFlinger::EffectModule::init()
6397{
6398 Mutex::Autolock _l(mLock);
6399 if (mEffectInterface == NULL) {
6400 return NO_INIT;
6401 }
6402 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006403 uint32_t size = sizeof(status_t);
6404 status_t status = (*mEffectInterface)->command(mEffectInterface,
6405 EFFECT_CMD_INIT,
6406 0,
6407 NULL,
6408 &size,
6409 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410 if (status == 0) {
6411 status = cmdStatus;
6412 }
6413 return status;
6414}
6415
Eric Laurentec35a142011-10-05 17:42:25 -07006416status_t AudioFlinger::EffectModule::start()
6417{
6418 Mutex::Autolock _l(mLock);
6419 return start_l();
6420}
6421
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422status_t AudioFlinger::EffectModule::start_l()
6423{
6424 if (mEffectInterface == NULL) {
6425 return NO_INIT;
6426 }
6427 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006428 uint32_t size = sizeof(status_t);
6429 status_t status = (*mEffectInterface)->command(mEffectInterface,
6430 EFFECT_CMD_ENABLE,
6431 0,
6432 NULL,
6433 &size,
6434 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435 if (status == 0) {
6436 status = cmdStatus;
6437 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006438 if (status == 0 &&
6439 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6440 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6441 sp<ThreadBase> thread = mThread.promote();
6442 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006443 audio_stream_t *stream = thread->stream();
6444 if (stream != NULL) {
6445 stream->add_audio_effect(stream, mEffectInterface);
6446 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006447 }
6448 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449 return status;
6450}
6451
Eric Laurentec437d82011-07-26 20:54:46 -07006452status_t AudioFlinger::EffectModule::stop()
6453{
6454 Mutex::Autolock _l(mLock);
6455 return stop_l();
6456}
6457
Mathias Agopian65ab4712010-07-14 17:59:35 -07006458status_t AudioFlinger::EffectModule::stop_l()
6459{
6460 if (mEffectInterface == NULL) {
6461 return NO_INIT;
6462 }
6463 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006464 uint32_t size = sizeof(status_t);
6465 status_t status = (*mEffectInterface)->command(mEffectInterface,
6466 EFFECT_CMD_DISABLE,
6467 0,
6468 NULL,
6469 &size,
6470 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006471 if (status == 0) {
6472 status = cmdStatus;
6473 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006474 if (status == 0 &&
6475 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6476 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6477 sp<ThreadBase> thread = mThread.promote();
6478 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006479 audio_stream_t *stream = thread->stream();
6480 if (stream != NULL) {
6481 stream->remove_audio_effect(stream, mEffectInterface);
6482 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006483 }
6484 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485 return status;
6486}
6487
Eric Laurent25f43952010-07-28 05:40:18 -07006488status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6489 uint32_t cmdSize,
6490 void *pCmdData,
6491 uint32_t *replySize,
6492 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006493{
6494 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006495// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496
Eric Laurentec437d82011-07-26 20:54:46 -07006497 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498 return NO_INIT;
6499 }
Eric Laurent25f43952010-07-28 05:40:18 -07006500 status_t status = (*mEffectInterface)->command(mEffectInterface,
6501 cmdCode,
6502 cmdSize,
6503 pCmdData,
6504 replySize,
6505 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006507 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006508 for (size_t i = 1; i < mHandles.size(); i++) {
6509 sp<EffectHandle> h = mHandles[i].promote();
6510 if (h != 0) {
6511 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6512 }
6513 }
6514 }
6515 return status;
6516}
6517
6518status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6519{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006520
Mathias Agopian65ab4712010-07-14 17:59:35 -07006521 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006522 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006523
6524 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006525 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6526 if (enabled && status != NO_ERROR) {
6527 return status;
6528 }
6529
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 switch (mState) {
6531 // going from disabled to enabled
6532 case IDLE:
6533 mState = STARTING;
6534 break;
6535 case STOPPED:
6536 mState = RESTART;
6537 break;
6538 case STOPPING:
6539 mState = ACTIVE;
6540 break;
6541
6542 // going from enabled to disabled
6543 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006544 mState = STOPPED;
6545 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006546 case STARTING:
6547 mState = IDLE;
6548 break;
6549 case ACTIVE:
6550 mState = STOPPING;
6551 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006552 case DESTROYED:
6553 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006554 }
6555 for (size_t i = 1; i < mHandles.size(); i++) {
6556 sp<EffectHandle> h = mHandles[i].promote();
6557 if (h != 0) {
6558 h->setEnabled(enabled);
6559 }
6560 }
6561 }
6562 return NO_ERROR;
6563}
6564
6565bool AudioFlinger::EffectModule::isEnabled()
6566{
6567 switch (mState) {
6568 case RESTART:
6569 case STARTING:
6570 case ACTIVE:
6571 return true;
6572 case IDLE:
6573 case STOPPING:
6574 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006575 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576 default:
6577 return false;
6578 }
6579}
6580
Eric Laurent8f45bd72010-08-31 13:50:07 -07006581bool AudioFlinger::EffectModule::isProcessEnabled()
6582{
6583 switch (mState) {
6584 case RESTART:
6585 case ACTIVE:
6586 case STOPPING:
6587 case STOPPED:
6588 return true;
6589 case IDLE:
6590 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006591 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006592 default:
6593 return false;
6594 }
6595}
6596
Mathias Agopian65ab4712010-07-14 17:59:35 -07006597status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6598{
6599 Mutex::Autolock _l(mLock);
6600 status_t status = NO_ERROR;
6601
6602 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6603 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006604 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006605 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6606 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006607 status_t cmdStatus;
6608 uint32_t volume[2];
6609 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006610 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 volume[0] = *left;
6612 volume[1] = *right;
6613 if (controller) {
6614 pVolume = volume;
6615 }
Eric Laurent25f43952010-07-28 05:40:18 -07006616 status = (*mEffectInterface)->command(mEffectInterface,
6617 EFFECT_CMD_SET_VOLUME,
6618 size,
6619 volume,
6620 &size,
6621 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006622 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6623 *left = volume[0];
6624 *right = volume[1];
6625 }
6626 }
6627 return status;
6628}
6629
6630status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6631{
6632 Mutex::Autolock _l(mLock);
6633 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006634 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6635 // audio pre processing modules on RecordThread can receive both output and
6636 // input device indication in the same call
6637 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6638 if (dev) {
6639 status_t cmdStatus;
6640 uint32_t size = sizeof(status_t);
6641
6642 status = (*mEffectInterface)->command(mEffectInterface,
6643 EFFECT_CMD_SET_DEVICE,
6644 sizeof(uint32_t),
6645 &dev,
6646 &size,
6647 &cmdStatus);
6648 if (status == NO_ERROR) {
6649 status = cmdStatus;
6650 }
6651 }
6652 dev = device & AUDIO_DEVICE_IN_ALL;
6653 if (dev) {
6654 status_t cmdStatus;
6655 uint32_t size = sizeof(status_t);
6656
6657 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6658 EFFECT_CMD_SET_INPUT_DEVICE,
6659 sizeof(uint32_t),
6660 &dev,
6661 &size,
6662 &cmdStatus);
6663 if (status2 == NO_ERROR) {
6664 status2 = cmdStatus;
6665 }
6666 if (status == NO_ERROR) {
6667 status = status2;
6668 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 }
6670 }
6671 return status;
6672}
6673
6674status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6675{
6676 Mutex::Autolock _l(mLock);
6677 status_t status = NO_ERROR;
6678 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006680 uint32_t size = sizeof(status_t);
6681 status = (*mEffectInterface)->command(mEffectInterface,
6682 EFFECT_CMD_SET_AUDIO_MODE,
6683 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006684 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006685 &size,
6686 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006687 if (status == NO_ERROR) {
6688 status = cmdStatus;
6689 }
6690 }
6691 return status;
6692}
6693
Eric Laurent59255e42011-07-27 19:49:51 -07006694void AudioFlinger::EffectModule::setSuspended(bool suspended)
6695{
6696 Mutex::Autolock _l(mLock);
6697 mSuspended = suspended;
6698}
6699bool AudioFlinger::EffectModule::suspended()
6700{
6701 Mutex::Autolock _l(mLock);
6702 return mSuspended;
6703}
6704
Mathias Agopian65ab4712010-07-14 17:59:35 -07006705status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6706{
6707 const size_t SIZE = 256;
6708 char buffer[SIZE];
6709 String8 result;
6710
6711 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6712 result.append(buffer);
6713
6714 bool locked = tryLock(mLock);
6715 // failed to lock - AudioFlinger is probably deadlocked
6716 if (!locked) {
6717 result.append("\t\tCould not lock Fx mutex:\n");
6718 }
6719
6720 result.append("\t\tSession Status State Engine:\n");
6721 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6722 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6723 result.append(buffer);
6724
6725 result.append("\t\tDescriptor:\n");
6726 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6727 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6728 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6729 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6730 result.append(buffer);
6731 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6732 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6733 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6734 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6735 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006736 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006737 mDescriptor.apiVersion,
6738 mDescriptor.flags);
6739 result.append(buffer);
6740 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6741 mDescriptor.name);
6742 result.append(buffer);
6743 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6744 mDescriptor.implementor);
6745 result.append(buffer);
6746
6747 result.append("\t\t- Input configuration:\n");
6748 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6749 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6750 (uint32_t)mConfig.inputCfg.buffer.raw,
6751 mConfig.inputCfg.buffer.frameCount,
6752 mConfig.inputCfg.samplingRate,
6753 mConfig.inputCfg.channels,
6754 mConfig.inputCfg.format);
6755 result.append(buffer);
6756
6757 result.append("\t\t- Output configuration:\n");
6758 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6759 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6760 (uint32_t)mConfig.outputCfg.buffer.raw,
6761 mConfig.outputCfg.buffer.frameCount,
6762 mConfig.outputCfg.samplingRate,
6763 mConfig.outputCfg.channels,
6764 mConfig.outputCfg.format);
6765 result.append(buffer);
6766
6767 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6768 result.append(buffer);
6769 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6770 for (size_t i = 0; i < mHandles.size(); ++i) {
6771 sp<EffectHandle> handle = mHandles[i].promote();
6772 if (handle != 0) {
6773 handle->dump(buffer, SIZE);
6774 result.append(buffer);
6775 }
6776 }
6777
6778 result.append("\n");
6779
6780 write(fd, result.string(), result.length());
6781
6782 if (locked) {
6783 mLock.unlock();
6784 }
6785
6786 return NO_ERROR;
6787}
6788
6789// ----------------------------------------------------------------------------
6790// EffectHandle implementation
6791// ----------------------------------------------------------------------------
6792
6793#undef LOG_TAG
6794#define LOG_TAG "AudioFlinger::EffectHandle"
6795
6796AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6797 const sp<AudioFlinger::Client>& client,
6798 const sp<IEffectClient>& effectClient,
6799 int32_t priority)
6800 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006801 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006802 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006803{
Steve Block3856b092011-10-20 11:56:00 +01006804 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006805
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006806 if (client == 0) {
6807 return;
6808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6810 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6811 if (mCblkMemory != 0) {
6812 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6813
6814 if (mCblk) {
6815 new(mCblk) effect_param_cblk_t();
6816 mBuffer = (uint8_t *)mCblk + bufOffset;
6817 }
6818 } else {
6819 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6820 return;
6821 }
6822}
6823
6824AudioFlinger::EffectHandle::~EffectHandle()
6825{
Steve Block3856b092011-10-20 11:56:00 +01006826 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006827 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006828 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829}
6830
6831status_t AudioFlinger::EffectHandle::enable()
6832{
Steve Block3856b092011-10-20 11:56:00 +01006833 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834 if (!mHasControl) return INVALID_OPERATION;
6835 if (mEffect == 0) return DEAD_OBJECT;
6836
Eric Laurentdb7c0792011-08-10 10:37:50 -07006837 if (mEnabled) {
6838 return NO_ERROR;
6839 }
6840
Eric Laurent59255e42011-07-27 19:49:51 -07006841 mEnabled = true;
6842
6843 sp<ThreadBase> thread = mEffect->thread().promote();
6844 if (thread != 0) {
6845 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6846 }
6847
6848 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6849 if (mEffect->suspended()) {
6850 return NO_ERROR;
6851 }
6852
Eric Laurentdb7c0792011-08-10 10:37:50 -07006853 status_t status = mEffect->setEnabled(true);
6854 if (status != NO_ERROR) {
6855 if (thread != 0) {
6856 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6857 }
6858 mEnabled = false;
6859 }
6860 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861}
6862
6863status_t AudioFlinger::EffectHandle::disable()
6864{
Steve Block3856b092011-10-20 11:56:00 +01006865 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006867 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006868
Eric Laurentdb7c0792011-08-10 10:37:50 -07006869 if (!mEnabled) {
6870 return NO_ERROR;
6871 }
Eric Laurent59255e42011-07-27 19:49:51 -07006872 mEnabled = false;
6873
6874 if (mEffect->suspended()) {
6875 return NO_ERROR;
6876 }
6877
6878 status_t status = mEffect->setEnabled(false);
6879
6880 sp<ThreadBase> thread = mEffect->thread().promote();
6881 if (thread != 0) {
6882 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6883 }
6884
6885 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006886}
6887
6888void AudioFlinger::EffectHandle::disconnect()
6889{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006890 disconnect(true);
6891}
6892
6893void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6894{
Steve Block3856b092011-10-20 11:56:00 +01006895 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006896 if (mEffect == 0) {
6897 return;
6898 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006899 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006900
Eric Laurenta85a74a2011-10-19 11:44:54 -07006901 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006902 sp<ThreadBase> thread = mEffect->thread().promote();
6903 if (thread != 0) {
6904 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6905 }
Eric Laurent59255e42011-07-27 19:49:51 -07006906 }
6907
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908 // release sp on module => module destructor can be called now
6909 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006910 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006911 if (mCblk) {
6912 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6913 }
6914 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6916 mClient.clear();
6917 }
6918}
6919
Eric Laurent25f43952010-07-28 05:40:18 -07006920status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6921 uint32_t cmdSize,
6922 void *pCmdData,
6923 uint32_t *replySize,
6924 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006925{
Steve Block3856b092011-10-20 11:56:00 +01006926// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006927// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928
6929 // only get parameter command is permitted for applications not controlling the effect
6930 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6931 return INVALID_OPERATION;
6932 }
6933 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006934 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006935
6936 // handle commands that are not forwarded transparently to effect engine
6937 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6938 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6939 // no risk to block the whole media server process or mixer threads is we are stuck here
6940 Mutex::Autolock _l(mCblk->lock);
6941 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6942 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6943 mCblk->serverIndex = 0;
6944 mCblk->clientIndex = 0;
6945 return BAD_VALUE;
6946 }
6947 status_t status = NO_ERROR;
6948 while (mCblk->serverIndex < mCblk->clientIndex) {
6949 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006950 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 int *p = (int *)(mBuffer + mCblk->serverIndex);
6952 int size = *p++;
6953 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6954 LOGW("command(): invalid parameter block size");
6955 break;
6956 }
6957 effect_param_t *param = (effect_param_t *)p;
6958 if (param->psize == 0 || param->vsize == 0) {
6959 LOGW("command(): null parameter or value size");
6960 mCblk->serverIndex += size;
6961 continue;
6962 }
Eric Laurent25f43952010-07-28 05:40:18 -07006963 uint32_t psize = sizeof(effect_param_t) +
6964 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6965 param->vsize;
6966 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6967 psize,
6968 p,
6969 &rsize,
6970 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006971 // stop at first error encountered
6972 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006973 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006974 *(int *)pReplyData = reply;
6975 break;
6976 } else if (reply != NO_ERROR) {
6977 *(int *)pReplyData = reply;
6978 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 }
6980 mCblk->serverIndex += size;
6981 }
6982 mCblk->serverIndex = 0;
6983 mCblk->clientIndex = 0;
6984 return status;
6985 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006986 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006987 return enable();
6988 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006989 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990 return disable();
6991 }
6992
6993 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6994}
6995
6996sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6997 return mCblkMemory;
6998}
6999
Eric Laurent59255e42011-07-27 19:49:51 -07007000void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007001{
Steve Block3856b092011-10-20 11:56:00 +01007002 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003
7004 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007005 mEnabled = enabled;
7006
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 if (signal && mEffectClient != 0) {
7008 mEffectClient->controlStatusChanged(hasControl);
7009 }
7010}
7011
Eric Laurent25f43952010-07-28 05:40:18 -07007012void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7013 uint32_t cmdSize,
7014 void *pCmdData,
7015 uint32_t replySize,
7016 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007017{
7018 if (mEffectClient != 0) {
7019 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7020 }
7021}
7022
7023
7024
7025void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7026{
7027 if (mEffectClient != 0) {
7028 mEffectClient->enableStatusChanged(enabled);
7029 }
7030}
7031
7032status_t AudioFlinger::EffectHandle::onTransact(
7033 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7034{
7035 return BnEffect::onTransact(code, data, reply, flags);
7036}
7037
7038
7039void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7040{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007041 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042
7043 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7044 (mClient == NULL) ? getpid() : mClient->pid(),
7045 mPriority,
7046 mHasControl,
7047 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007048 mCblk ? mCblk->clientIndex : 0,
7049 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007050 );
7051
7052 if (locked) {
7053 mCblk->lock.unlock();
7054 }
7055}
7056
7057#undef LOG_TAG
7058#define LOG_TAG "AudioFlinger::EffectChain"
7059
7060AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7061 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007062 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007063 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7064 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007065{
Dima Zavinfce7a472011-04-19 22:30:36 -07007066 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007067 sp<ThreadBase> thread = mThread.promote();
7068 if (thread == 0) {
7069 return;
7070 }
7071 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7072 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007073}
7074
7075AudioFlinger::EffectChain::~EffectChain()
7076{
7077 if (mOwnInBuffer) {
7078 delete mInBuffer;
7079 }
7080
7081}
7082
Eric Laurent59255e42011-07-27 19:49:51 -07007083// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007084sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007085{
7086 sp<EffectModule> effect;
7087 size_t size = mEffects.size();
7088
7089 for (size_t i = 0; i < size; i++) {
7090 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7091 effect = mEffects[i];
7092 break;
7093 }
7094 }
7095 return effect;
7096}
7097
Eric Laurent59255e42011-07-27 19:49:51 -07007098// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007099sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007100{
7101 sp<EffectModule> effect;
7102 size_t size = mEffects.size();
7103
7104 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007105 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7106 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007107 effect = mEffects[i];
7108 break;
7109 }
7110 }
7111 return effect;
7112}
7113
Eric Laurent59255e42011-07-27 19:49:51 -07007114// getEffectFromType_l() must be called with ThreadBase::mLock held
7115sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7116 const effect_uuid_t *type)
7117{
7118 sp<EffectModule> effect;
7119 size_t size = mEffects.size();
7120
7121 for (size_t i = 0; i < size; i++) {
7122 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7123 effect = mEffects[i];
7124 break;
7125 }
7126 }
7127 return effect;
7128}
7129
Mathias Agopian65ab4712010-07-14 17:59:35 -07007130// Must be called with EffectChain::mLock locked
7131void AudioFlinger::EffectChain::process_l()
7132{
Eric Laurentdac69112010-09-28 14:09:57 -07007133 sp<ThreadBase> thread = mThread.promote();
7134 if (thread == 0) {
7135 LOGW("process_l(): cannot promote mixer thread");
7136 return;
7137 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007138 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7139 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007140 // always process effects unless no more tracks are on the session and the effect tail
7141 // has been rendered
7142 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007143 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007144 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007145
Eric Laurent544fe9b2011-11-11 15:42:52 -08007146 if (!tracksOnSession && mTailBufferCount == 0) {
7147 doProcess = false;
7148 }
7149
7150 if (activeTrackCnt() == 0) {
7151 // if no track is active and the effect tail has not been rendered,
7152 // the input buffer must be cleared here as the mixer process will not do it
7153 if (tracksOnSession || mTailBufferCount > 0) {
7154 size_t numSamples = thread->frameCount() * thread->channelCount();
7155 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7156 if (mTailBufferCount > 0) {
7157 mTailBufferCount--;
7158 }
7159 }
7160 }
Eric Laurentdac69112010-09-28 14:09:57 -07007161 }
7162
Mathias Agopian65ab4712010-07-14 17:59:35 -07007163 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007164 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007165 for (size_t i = 0; i < size; i++) {
7166 mEffects[i]->process();
7167 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 }
7169 for (size_t i = 0; i < size; i++) {
7170 mEffects[i]->updateState();
7171 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}
7173
Eric Laurentcab11242010-07-15 12:50:15 -07007174// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007175status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007176{
7177 effect_descriptor_t desc = effect->desc();
7178 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7179
7180 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007181 effect->setChain(this);
7182 sp<ThreadBase> thread = mThread.promote();
7183 if (thread == 0) {
7184 return NO_INIT;
7185 }
7186 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007187
7188 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7189 // Auxiliary effects are inserted at the beginning of mEffects vector as
7190 // they are processed first and accumulated in chain input buffer
7191 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007192
Mathias Agopian65ab4712010-07-14 17:59:35 -07007193 // the input buffer for auxiliary effect contains mono samples in
7194 // 32 bit format. This is to avoid saturation in AudoMixer
7195 // accumulation stage. Saturation is done in EffectModule::process() before
7196 // calling the process in effect engine
7197 size_t numSamples = thread->frameCount();
7198 int32_t *buffer = new int32_t[numSamples];
7199 memset(buffer, 0, numSamples * sizeof(int32_t));
7200 effect->setInBuffer((int16_t *)buffer);
7201 // auxiliary effects output samples to chain input buffer for further processing
7202 // by insert effects
7203 effect->setOutBuffer(mInBuffer);
7204 } else {
7205 // Insert effects are inserted at the end of mEffects vector as they are processed
7206 // after track and auxiliary effects.
7207 // Insert effect order as a function of indicated preference:
7208 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7209 // another effect is present
7210 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7211 // last effect claiming first position
7212 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7213 // first effect claiming last position
7214 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7215 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7216 // already present
7217
7218 int size = (int)mEffects.size();
7219 int idx_insert = size;
7220 int idx_insert_first = -1;
7221 int idx_insert_last = -1;
7222
7223 for (int i = 0; i < size; i++) {
7224 effect_descriptor_t d = mEffects[i]->desc();
7225 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7226 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7227 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7228 // check invalid effect chaining combinations
7229 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7230 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007231 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007232 return INVALID_OPERATION;
7233 }
7234 // remember position of first insert effect and by default
7235 // select this as insert position for new effect
7236 if (idx_insert == size) {
7237 idx_insert = i;
7238 }
7239 // remember position of last insert effect claiming
7240 // first position
7241 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7242 idx_insert_first = i;
7243 }
7244 // remember position of first insert effect claiming
7245 // last position
7246 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7247 idx_insert_last == -1) {
7248 idx_insert_last = i;
7249 }
7250 }
7251 }
7252
7253 // modify idx_insert from first position if needed
7254 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7255 if (idx_insert_last != -1) {
7256 idx_insert = idx_insert_last;
7257 } else {
7258 idx_insert = size;
7259 }
7260 } else {
7261 if (idx_insert_first != -1) {
7262 idx_insert = idx_insert_first + 1;
7263 }
7264 }
7265
7266 // always read samples from chain input buffer
7267 effect->setInBuffer(mInBuffer);
7268
7269 // if last effect in the chain, output samples to chain
7270 // output buffer, otherwise to chain input buffer
7271 if (idx_insert == size) {
7272 if (idx_insert != 0) {
7273 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7274 mEffects[idx_insert-1]->configure();
7275 }
7276 effect->setOutBuffer(mOutBuffer);
7277 } else {
7278 effect->setOutBuffer(mInBuffer);
7279 }
7280 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007281
Steve Block3856b092011-10-20 11:56:00 +01007282 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007283 }
7284 effect->configure();
7285 return NO_ERROR;
7286}
7287
Eric Laurentcab11242010-07-15 12:50:15 -07007288// removeEffect_l() must be called with PlaybackThread::mLock held
7289size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007290{
7291 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007292 int size = (int)mEffects.size();
7293 int i;
7294 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7295
7296 for (i = 0; i < size; i++) {
7297 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007298 // calling stop here will remove pre-processing effect from the audio HAL.
7299 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7300 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007301 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7302 mEffects[i]->state() == EffectModule::STOPPING) {
7303 mEffects[i]->stop();
7304 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007305 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7306 delete[] effect->inBuffer();
7307 } else {
7308 if (i == size - 1 && i != 0) {
7309 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7310 mEffects[i - 1]->configure();
7311 }
7312 }
7313 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007314 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007315 break;
7316 }
7317 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318
7319 return mEffects.size();
7320}
7321
Eric Laurentcab11242010-07-15 12:50:15 -07007322// setDevice_l() must be called with PlaybackThread::mLock held
7323void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007324{
7325 size_t size = mEffects.size();
7326 for (size_t i = 0; i < size; i++) {
7327 mEffects[i]->setDevice(device);
7328 }
7329}
7330
Eric Laurentcab11242010-07-15 12:50:15 -07007331// setMode_l() must be called with PlaybackThread::mLock held
7332void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007333{
7334 size_t size = mEffects.size();
7335 for (size_t i = 0; i < size; i++) {
7336 mEffects[i]->setMode(mode);
7337 }
7338}
7339
Eric Laurentcab11242010-07-15 12:50:15 -07007340// setVolume_l() must be called with PlaybackThread::mLock held
7341bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007342{
7343 uint32_t newLeft = *left;
7344 uint32_t newRight = *right;
7345 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007346 int ctrlIdx = -1;
7347 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007348
Eric Laurentcab11242010-07-15 12:50:15 -07007349 // first update volume controller
7350 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007351 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007352 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7353 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007354 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007355 break;
7356 }
7357 }
7358
7359 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007360 if (hasControl) {
7361 *left = mNewLeftVolume;
7362 *right = mNewRightVolume;
7363 }
7364 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007365 }
7366
7367 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007368 mLeftVolume = newLeft;
7369 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007370
7371 // second get volume update from volume controller
7372 if (ctrlIdx >= 0) {
7373 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007374 mNewLeftVolume = newLeft;
7375 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007376 }
7377 // then indicate volume to all other effects in chain.
7378 // Pass altered volume to effects before volume controller
7379 // and requested volume to effects after controller
7380 uint32_t lVol = newLeft;
7381 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007382
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007384 if ((int)i == ctrlIdx) continue;
7385 // this also works for ctrlIdx == -1 when there is no volume controller
7386 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387 lVol = *left;
7388 rVol = *right;
7389 }
7390 mEffects[i]->setVolume(&lVol, &rVol, false);
7391 }
7392 *left = newLeft;
7393 *right = newRight;
7394
7395 return hasControl;
7396}
7397
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7399{
7400 const size_t SIZE = 256;
7401 char buffer[SIZE];
7402 String8 result;
7403
7404 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7405 result.append(buffer);
7406
7407 bool locked = tryLock(mLock);
7408 // failed to lock - AudioFlinger is probably deadlocked
7409 if (!locked) {
7410 result.append("\tCould not lock mutex:\n");
7411 }
7412
Eric Laurentcab11242010-07-15 12:50:15 -07007413 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7414 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007415 mEffects.size(),
7416 (uint32_t)mInBuffer,
7417 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 mActiveTrackCnt);
7419 result.append(buffer);
7420 write(fd, result.string(), result.size());
7421
7422 for (size_t i = 0; i < mEffects.size(); ++i) {
7423 sp<EffectModule> effect = mEffects[i];
7424 if (effect != 0) {
7425 effect->dump(fd, args);
7426 }
7427 }
7428
7429 if (locked) {
7430 mLock.unlock();
7431 }
7432
7433 return NO_ERROR;
7434}
7435
Eric Laurent59255e42011-07-27 19:49:51 -07007436// must be called with ThreadBase::mLock held
7437void AudioFlinger::EffectChain::setEffectSuspended_l(
7438 const effect_uuid_t *type, bool suspend)
7439{
7440 sp<SuspendedEffectDesc> desc;
7441 // use effect type UUID timelow as key as there is no real risk of identical
7442 // timeLow fields among effect type UUIDs.
7443 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7444 if (suspend) {
7445 if (index >= 0) {
7446 desc = mSuspendedEffects.valueAt(index);
7447 } else {
7448 desc = new SuspendedEffectDesc();
7449 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7450 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007451 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007452 }
7453 if (desc->mRefCount++ == 0) {
7454 sp<EffectModule> effect = getEffectIfEnabled(type);
7455 if (effect != 0) {
7456 desc->mEffect = effect;
7457 effect->setSuspended(true);
7458 effect->setEnabled(false);
7459 }
7460 }
7461 } else {
7462 if (index < 0) {
7463 return;
7464 }
7465 desc = mSuspendedEffects.valueAt(index);
7466 if (desc->mRefCount <= 0) {
7467 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7468 desc->mRefCount = 1;
7469 }
7470 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007471 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007472 if (desc->mEffect != 0) {
7473 sp<EffectModule> effect = desc->mEffect.promote();
7474 if (effect != 0) {
7475 effect->setSuspended(false);
7476 sp<EffectHandle> handle = effect->controlHandle();
7477 if (handle != 0) {
7478 effect->setEnabled(handle->enabled());
7479 }
7480 }
7481 desc->mEffect.clear();
7482 }
7483 mSuspendedEffects.removeItemsAt(index);
7484 }
7485 }
7486}
7487
7488// must be called with ThreadBase::mLock held
7489void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7490{
7491 sp<SuspendedEffectDesc> desc;
7492
7493 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7494 if (suspend) {
7495 if (index >= 0) {
7496 desc = mSuspendedEffects.valueAt(index);
7497 } else {
7498 desc = new SuspendedEffectDesc();
7499 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007500 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007501 }
7502 if (desc->mRefCount++ == 0) {
7503 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7504 for (size_t i = 0; i < effects.size(); i++) {
7505 setEffectSuspended_l(&effects[i]->desc().type, true);
7506 }
7507 }
7508 } else {
7509 if (index < 0) {
7510 return;
7511 }
7512 desc = mSuspendedEffects.valueAt(index);
7513 if (desc->mRefCount <= 0) {
7514 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7515 desc->mRefCount = 1;
7516 }
7517 if (--desc->mRefCount == 0) {
7518 Vector<const effect_uuid_t *> types;
7519 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7520 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7521 continue;
7522 }
7523 types.add(&mSuspendedEffects.valueAt(i)->mType);
7524 }
7525 for (size_t i = 0; i < types.size(); i++) {
7526 setEffectSuspended_l(types[i], false);
7527 }
Steve Block3856b092011-10-20 11:56:00 +01007528 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007529 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7530 }
7531 }
7532}
7533
Eric Laurent6bffdb82011-09-23 08:40:41 -07007534
7535// The volume effect is used for automated tests only
7536#ifndef OPENSL_ES_H_
7537static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7538 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7539const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7540#endif //OPENSL_ES_H_
7541
Eric Laurentdb7c0792011-08-10 10:37:50 -07007542bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7543{
7544 // auxiliary effects and visualizer are never suspended on output mix
7545 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7546 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007547 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7548 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007549 return false;
7550 }
7551 return true;
7552}
7553
Eric Laurent59255e42011-07-27 19:49:51 -07007554Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7555{
7556 Vector< sp<EffectModule> > effects;
7557 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007558 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007559 continue;
7560 }
7561 effects.add(mEffects[i]);
7562 }
7563 return effects;
7564}
7565
7566sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7567 const effect_uuid_t *type)
7568{
7569 sp<EffectModule> effect;
7570 effect = getEffectFromType_l(type);
7571 if (effect != 0 && !effect->isEnabled()) {
7572 effect.clear();
7573 }
7574 return effect;
7575}
7576
7577void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7578 bool enabled)
7579{
7580 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7581 if (enabled) {
7582 if (index < 0) {
7583 // if the effect is not suspend check if all effects are suspended
7584 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7585 if (index < 0) {
7586 return;
7587 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007588 if (!isEffectEligibleForSuspend(effect->desc())) {
7589 return;
7590 }
Eric Laurent59255e42011-07-27 19:49:51 -07007591 setEffectSuspended_l(&effect->desc().type, enabled);
7592 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007593 if (index < 0) {
7594 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7595 return;
7596 }
Eric Laurent59255e42011-07-27 19:49:51 -07007597 }
Steve Block3856b092011-10-20 11:56:00 +01007598 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007599 effect->desc().type.timeLow);
7600 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7601 // if effect is requested to suspended but was not yet enabled, supend it now.
7602 if (desc->mEffect == 0) {
7603 desc->mEffect = effect;
7604 effect->setEnabled(false);
7605 effect->setSuspended(true);
7606 }
7607 } else {
7608 if (index < 0) {
7609 return;
7610 }
Steve Block3856b092011-10-20 11:56:00 +01007611 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007612 effect->desc().type.timeLow);
7613 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7614 desc->mEffect.clear();
7615 effect->setSuspended(false);
7616 }
7617}
7618
Mathias Agopian65ab4712010-07-14 17:59:35 -07007619#undef LOG_TAG
7620#define LOG_TAG "AudioFlinger"
7621
7622// ----------------------------------------------------------------------------
7623
7624status_t AudioFlinger::onTransact(
7625 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7626{
7627 return BnAudioFlinger::onTransact(code, data, reply, flags);
7628}
7629
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630}; // namespace android