blob: e494d05c4b17a92f8b2c19a0ead46720a111115f [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
46#include <hardware/audio.h>
47#include <hardware/audio_hal.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>
53#include <media/EffectVisualizerApi.h>
54
55// ----------------------------------------------------------------------------
56// the sim build doesn't have gettid
57
58#ifndef HAVE_GETTID
59# define gettid getpid
60#endif
61
62// ----------------------------------------------------------------------------
63
Eric Laurentde070132010-07-13 04:45:46 -070064extern const char * const gEffectLibPath;
65
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
68static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
69static const char* kHardwareLockedString = "Hardware lock is taken\n";
70
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
73static const float MAX_GAIN_INT = 0x1000;
74
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
85static const int kDumpLockSleep = 20000;
86
87static const nsecs_t kWarningThrottle = seconds(5);
88
89
90#define AUDIOFLINGER_SECURITY_ENABLED 1
91
92// ----------------------------------------------------------------------------
93
94static bool recordingAllowed() {
95#ifndef HAVE_ANDROID_OS
96 return true;
97#endif
98#if AUDIOFLINGER_SECURITY_ENABLED
99 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
100 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
101 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
102 return ok;
103#else
104 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
105 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
106 return true;
107#endif
108}
109
110static bool settingsAllowed() {
111#ifndef HAVE_ANDROID_OS
112 return true;
113#endif
114#if AUDIOFLINGER_SECURITY_ENABLED
115 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
116 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
117 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
118 return ok;
119#else
120 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
121 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
122 return true;
123#endif
124}
125
Gloria Wang9ee159b2011-02-24 14:51:45 -0800126// To collect the amplifier usage
127static void addBatteryData(uint32_t params) {
128 sp<IBinder> binder =
129 defaultServiceManager()->getService(String16("media.player"));
130 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
131 if (service.get() == NULL) {
132 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
133 return;
134 }
135
136 service->addBatteryData(params);
137}
138
Dima Zavin799a70e2011-04-18 16:57:27 -0700139static int load_audio_interface(const char *if_name, const hw_module_t **mod,
140 audio_hw_device_t **dev)
141{
142 int rc;
143
144 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
145 if (rc)
146 goto out;
147
148 rc = audio_hw_device_open(*mod, dev);
149 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
150 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
151 if (rc)
152 goto out;
153
154 return 0;
155
156out:
157 *mod = NULL;
158 *dev = NULL;
159 return rc;
160}
161
162static const char *audio_interfaces[] = {
163 "primary",
164 "a2dp",
165 "usb",
166};
167#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
168
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169// ----------------------------------------------------------------------------
170
171AudioFlinger::AudioFlinger()
172 : BnAudioFlinger(),
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700174{
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700176
Eric Laurent93575202011-01-18 18:39:02 -0800177 Mutex::Autolock _l(mLock);
178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700180 mHardwareStatus = AUDIO_HW_IDLE;
181
Dima Zavin799a70e2011-04-18 16:57:27 -0700182 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
183 const hw_module_t *mod;
184 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700185
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
187 if (rc)
188 continue;
189
190 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
191 mod->name, mod->id);
192 mAudioHwDevs.push(dev);
193
194 if (!mPrimaryHardwareDev) {
195 mPrimaryHardwareDev = dev;
196 LOGI("Using '%s' (%s.%s) as the primary audio interface",
197 AUDIO_HARDWARE_INTERFACE, mod->name, mod->id,
198 audio_interfaces[i]);
199 }
200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700201
202 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700203
Dima Zavin799a70e2011-04-18 16:57:27 -0700204 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
205 LOGE("Primary audio interface not found");
206 return;
207 }
208
209 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
210 audio_hw_device_t *dev = mAudioHwDevs[i];
211
212 mHardwareStatus = AUDIO_HW_INIT;
213 rc = dev->init_check(dev);
214 if (rc == 0) {
215 AutoMutex lock(mHardwareLock);
216
217 mMode = AUDIO_MODE_NORMAL;
218 mHardwareStatus = AUDIO_HW_SET_MODE;
219 dev->set_mode(dev, mMode);
220 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
221 dev->set_master_volume(dev, 1.0f);
222 mHardwareStatus = AUDIO_HW_IDLE;
223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700224 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700225}
226
227AudioFlinger::~AudioFlinger()
228{
Dima Zavin799a70e2011-04-18 16:57:27 -0700229 int num_devs = mAudioHwDevs.size();
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231 while (!mRecordThreads.isEmpty()) {
232 // closeInput() will remove first entry from mRecordThreads
233 closeInput(mRecordThreads.keyAt(0));
234 }
235 while (!mPlaybackThreads.isEmpty()) {
236 // closeOutput() will remove first entry from mPlaybackThreads
237 closeOutput(mPlaybackThreads.keyAt(0));
238 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700239
240 for (int i = 0; i < num_devs; i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700243 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700244 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245}
246
Dima Zavin799a70e2011-04-18 16:57:27 -0700247audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
248{
249 /* first matching HW device is returned */
250 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
251 audio_hw_device_t *dev = mAudioHwDevs[i];
252 if ((dev->get_supported_devices(dev) & devices) == devices)
253 return dev;
254 }
255 return NULL;
256}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700257
258status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
259{
260 const size_t SIZE = 256;
261 char buffer[SIZE];
262 String8 result;
263
264 result.append("Clients:\n");
265 for (size_t i = 0; i < mClients.size(); ++i) {
266 wp<Client> wClient = mClients.valueAt(i);
267 if (wClient != 0) {
268 sp<Client> client = wClient.promote();
269 if (client != 0) {
270 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
271 result.append(buffer);
272 }
273 }
274 }
275 write(fd, result.string(), result.size());
276 return NO_ERROR;
277}
278
279
280status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
281{
282 const size_t SIZE = 256;
283 char buffer[SIZE];
284 String8 result;
285 int hardwareStatus = mHardwareStatus;
286
287 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
288 result.append(buffer);
289 write(fd, result.string(), result.size());
290 return NO_ERROR;
291}
292
293status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
294{
295 const size_t SIZE = 256;
296 char buffer[SIZE];
297 String8 result;
298 snprintf(buffer, SIZE, "Permission Denial: "
299 "can't dump AudioFlinger from pid=%d, uid=%d\n",
300 IPCThreadState::self()->getCallingPid(),
301 IPCThreadState::self()->getCallingUid());
302 result.append(buffer);
303 write(fd, result.string(), result.size());
304 return NO_ERROR;
305}
306
307static bool tryLock(Mutex& mutex)
308{
309 bool locked = false;
310 for (int i = 0; i < kDumpLockRetries; ++i) {
311 if (mutex.tryLock() == NO_ERROR) {
312 locked = true;
313 break;
314 }
315 usleep(kDumpLockSleep);
316 }
317 return locked;
318}
319
320status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
321{
322 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
323 dumpPermissionDenial(fd, args);
324 } else {
325 // get state of hardware lock
326 bool hardwareLocked = tryLock(mHardwareLock);
327 if (!hardwareLocked) {
328 String8 result(kHardwareLockedString);
329 write(fd, result.string(), result.size());
330 } else {
331 mHardwareLock.unlock();
332 }
333
334 bool locked = tryLock(mLock);
335
336 // failed to lock - AudioFlinger is probably deadlocked
337 if (!locked) {
338 String8 result(kDeadlockedString);
339 write(fd, result.string(), result.size());
340 }
341
342 dumpClients(fd, args);
343 dumpInternals(fd, args);
344
345 // dump playback threads
346 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
347 mPlaybackThreads.valueAt(i)->dump(fd, args);
348 }
349
350 // dump record threads
351 for (size_t i = 0; i < mRecordThreads.size(); i++) {
352 mRecordThreads.valueAt(i)->dump(fd, args);
353 }
354
Dima Zavin799a70e2011-04-18 16:57:27 -0700355 // dump all hardware devs
356 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
357 audio_hw_device_t *dev = mAudioHwDevs[i];
358 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700359 }
360 if (locked) mLock.unlock();
361 }
362 return NO_ERROR;
363}
364
365
366// IAudioFlinger interface
367
368
369sp<IAudioTrack> AudioFlinger::createTrack(
370 pid_t pid,
371 int streamType,
372 uint32_t sampleRate,
373 int format,
374 int channelCount,
375 int frameCount,
376 uint32_t flags,
377 const sp<IMemory>& sharedBuffer,
378 int output,
379 int *sessionId,
380 status_t *status)
381{
382 sp<PlaybackThread::Track> track;
383 sp<TrackHandle> trackHandle;
384 sp<Client> client;
385 wp<Client> wclient;
386 status_t lStatus;
387 int lSessionId;
388
Dima Zavinfce7a472011-04-19 22:30:36 -0700389 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700390 LOGE("invalid stream type");
391 lStatus = BAD_VALUE;
392 goto Exit;
393 }
394
395 {
396 Mutex::Autolock _l(mLock);
397 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700398 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700399 if (thread == NULL) {
400 LOGE("unknown output thread");
401 lStatus = BAD_VALUE;
402 goto Exit;
403 }
404
405 wclient = mClients.valueFor(pid);
406
407 if (wclient != NULL) {
408 client = wclient.promote();
409 } else {
410 client = new Client(this, pid);
411 mClients.add(pid, client);
412 }
413
Mathias Agopian65ab4712010-07-14 17:59:35 -0700414 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700415 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700416 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700417 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
418 if (mPlaybackThreads.keyAt(i) != output) {
419 // prevent same audio session on different output threads
420 uint32_t sessions = t->hasAudioSession(*sessionId);
421 if (sessions & PlaybackThread::TRACK_SESSION) {
422 lStatus = BAD_VALUE;
423 goto Exit;
424 }
425 // check if an effect with same session ID is waiting for a track to be created
426 if (sessions & PlaybackThread::EFFECT_SESSION) {
427 effectThread = t.get();
428 }
Eric Laurentde070132010-07-13 04:45:46 -0700429 }
430 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700431 lSessionId = *sessionId;
432 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700433 // if no audio session id is provided, create one here
Eric Laurentf5aafb22010-11-18 08:40:16 -0800434 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 if (sessionId != NULL) {
436 *sessionId = lSessionId;
437 }
438 }
439 LOGV("createTrack() lSessionId: %d", lSessionId);
440
441 track = thread->createTrack_l(client, streamType, sampleRate, format,
442 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700443
444 // move effect chain to this output thread if an effect on same session was waiting
445 // for a track to be created
446 if (lStatus == NO_ERROR && effectThread != NULL) {
447 Mutex::Autolock _dl(thread->mLock);
448 Mutex::Autolock _sl(effectThread->mLock);
449 moveEffectChain_l(lSessionId, effectThread, thread, true);
450 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700451 }
452 if (lStatus == NO_ERROR) {
453 trackHandle = new TrackHandle(track);
454 } else {
455 // remove local strong reference to Client before deleting the Track so that the Client
456 // destructor is called by the TrackBase destructor with mLock held
457 client.clear();
458 track.clear();
459 }
460
461Exit:
462 if(status) {
463 *status = lStatus;
464 }
465 return trackHandle;
466}
467
468uint32_t AudioFlinger::sampleRate(int output) const
469{
470 Mutex::Autolock _l(mLock);
471 PlaybackThread *thread = checkPlaybackThread_l(output);
472 if (thread == NULL) {
473 LOGW("sampleRate() unknown thread %d", output);
474 return 0;
475 }
476 return thread->sampleRate();
477}
478
479int AudioFlinger::channelCount(int output) const
480{
481 Mutex::Autolock _l(mLock);
482 PlaybackThread *thread = checkPlaybackThread_l(output);
483 if (thread == NULL) {
484 LOGW("channelCount() unknown thread %d", output);
485 return 0;
486 }
487 return thread->channelCount();
488}
489
490int AudioFlinger::format(int output) const
491{
492 Mutex::Autolock _l(mLock);
493 PlaybackThread *thread = checkPlaybackThread_l(output);
494 if (thread == NULL) {
495 LOGW("format() unknown thread %d", output);
496 return 0;
497 }
498 return thread->format();
499}
500
501size_t AudioFlinger::frameCount(int output) const
502{
503 Mutex::Autolock _l(mLock);
504 PlaybackThread *thread = checkPlaybackThread_l(output);
505 if (thread == NULL) {
506 LOGW("frameCount() unknown thread %d", output);
507 return 0;
508 }
509 return thread->frameCount();
510}
511
512uint32_t AudioFlinger::latency(int output) const
513{
514 Mutex::Autolock _l(mLock);
515 PlaybackThread *thread = checkPlaybackThread_l(output);
516 if (thread == NULL) {
517 LOGW("latency() unknown thread %d", output);
518 return 0;
519 }
520 return thread->latency();
521}
522
523status_t AudioFlinger::setMasterVolume(float value)
524{
525 // check calling permissions
526 if (!settingsAllowed()) {
527 return PERMISSION_DENIED;
528 }
529
530 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800531 { // scope for the lock
532 AutoMutex lock(mHardwareLock);
533 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700534 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800535 value = 1.0f;
536 }
537 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700538 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700539
Eric Laurent93575202011-01-18 18:39:02 -0800540 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700541 mMasterVolume = value;
542 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
543 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
544
545 return NO_ERROR;
546}
547
548status_t AudioFlinger::setMode(int mode)
549{
550 status_t ret;
551
552 // check calling permissions
553 if (!settingsAllowed()) {
554 return PERMISSION_DENIED;
555 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700556 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 LOGW("Illegal value: setMode(%d)", mode);
558 return BAD_VALUE;
559 }
560
561 { // scope for the lock
562 AutoMutex lock(mHardwareLock);
563 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700564 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700565 mHardwareStatus = AUDIO_HW_IDLE;
566 }
567
568 if (NO_ERROR == ret) {
569 Mutex::Autolock _l(mLock);
570 mMode = mode;
571 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
572 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 }
574
575 return ret;
576}
577
578status_t AudioFlinger::setMicMute(bool state)
579{
580 // check calling permissions
581 if (!settingsAllowed()) {
582 return PERMISSION_DENIED;
583 }
584
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700587 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700588 mHardwareStatus = AUDIO_HW_IDLE;
589 return ret;
590}
591
592bool AudioFlinger::getMicMute() const
593{
Dima Zavinfce7a472011-04-19 22:30:36 -0700594 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700596 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 mHardwareStatus = AUDIO_HW_IDLE;
598 return state;
599}
600
601status_t AudioFlinger::setMasterMute(bool muted)
602{
603 // check calling permissions
604 if (!settingsAllowed()) {
605 return PERMISSION_DENIED;
606 }
607
Eric Laurent93575202011-01-18 18:39:02 -0800608 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700609 mMasterMute = muted;
610 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
611 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
612
613 return NO_ERROR;
614}
615
616float AudioFlinger::masterVolume() const
617{
618 return mMasterVolume;
619}
620
621bool AudioFlinger::masterMute() const
622{
623 return mMasterMute;
624}
625
626status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
627{
628 // check calling permissions
629 if (!settingsAllowed()) {
630 return PERMISSION_DENIED;
631 }
632
Dima Zavinfce7a472011-04-19 22:30:36 -0700633 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700634 return BAD_VALUE;
635 }
636
637 AutoMutex lock(mLock);
638 PlaybackThread *thread = NULL;
639 if (output) {
640 thread = checkPlaybackThread_l(output);
641 if (thread == NULL) {
642 return BAD_VALUE;
643 }
644 }
645
646 mStreamTypes[stream].volume = value;
647
648 if (thread == NULL) {
649 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
650 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
651 }
652 } else {
653 thread->setStreamVolume(stream, value);
654 }
655
656 return NO_ERROR;
657}
658
659status_t AudioFlinger::setStreamMute(int stream, bool muted)
660{
661 // check calling permissions
662 if (!settingsAllowed()) {
663 return PERMISSION_DENIED;
664 }
665
Dima Zavinfce7a472011-04-19 22:30:36 -0700666 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
667 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700668 return BAD_VALUE;
669 }
670
Eric Laurent93575202011-01-18 18:39:02 -0800671 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 mStreamTypes[stream].mute = muted;
673 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
674 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
675
676 return NO_ERROR;
677}
678
679float AudioFlinger::streamVolume(int stream, int output) const
680{
Dima Zavinfce7a472011-04-19 22:30:36 -0700681 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700682 return 0.0f;
683 }
684
685 AutoMutex lock(mLock);
686 float volume;
687 if (output) {
688 PlaybackThread *thread = checkPlaybackThread_l(output);
689 if (thread == NULL) {
690 return 0.0f;
691 }
692 volume = thread->streamVolume(stream);
693 } else {
694 volume = mStreamTypes[stream].volume;
695 }
696
697 return volume;
698}
699
700bool AudioFlinger::streamMute(int stream) const
701{
Dima Zavinfce7a472011-04-19 22:30:36 -0700702 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 return true;
704 }
705
706 return mStreamTypes[stream].mute;
707}
708
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
710{
711 status_t result;
712
713 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
714 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
715 // check calling permissions
716 if (!settingsAllowed()) {
717 return PERMISSION_DENIED;
718 }
719
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720 // ioHandle == 0 means the parameters are global to the audio hardware interface
721 if (ioHandle == 0) {
722 AutoMutex lock(mHardwareLock);
723 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700724 status_t final_result = NO_ERROR;
725 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
726 audio_hw_device_t *dev = mAudioHwDevs[i];
727 result = dev->set_parameters(dev, keyValuePairs.string());
728 final_result = result ?: final_result;
729 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700730 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700731 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700732 }
733
734 // hold a strong ref on thread in case closeOutput() or closeInput() is called
735 // and the thread is exited once the lock is released
736 sp<ThreadBase> thread;
737 {
738 Mutex::Autolock _l(mLock);
739 thread = checkPlaybackThread_l(ioHandle);
740 if (thread == NULL) {
741 thread = checkRecordThread_l(ioHandle);
742 }
743 }
744 if (thread != NULL) {
745 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700746 return result;
747 }
748 return BAD_VALUE;
749}
750
751String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
752{
753// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
754// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
755
756 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700757 String8 out_s8;
758
Dima Zavin799a70e2011-04-18 16:57:27 -0700759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 char *s = dev->get_parameters(dev, keys.string());
762 out_s8 += String8(s);
763 free(s);
764 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700765 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700766 }
767
768 Mutex::Autolock _l(mLock);
769
770 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
771 if (playbackThread != NULL) {
772 return playbackThread->getParameters(keys);
773 }
774 RecordThread *recordThread = checkRecordThread_l(ioHandle);
775 if (recordThread != NULL) {
776 return recordThread->getParameters(keys);
777 }
778 return String8("");
779}
780
781size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
782{
Dima Zavin799a70e2011-04-18 16:57:27 -0700783 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784}
785
786unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
787{
788 if (ioHandle == 0) {
789 return 0;
790 }
791
792 Mutex::Autolock _l(mLock);
793
794 RecordThread *recordThread = checkRecordThread_l(ioHandle);
795 if (recordThread != NULL) {
796 return recordThread->getInputFramesLost();
797 }
798 return 0;
799}
800
801status_t AudioFlinger::setVoiceVolume(float value)
802{
803 // check calling permissions
804 if (!settingsAllowed()) {
805 return PERMISSION_DENIED;
806 }
807
808 AutoMutex lock(mHardwareLock);
809 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700810 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811 mHardwareStatus = AUDIO_HW_IDLE;
812
813 return ret;
814}
815
816status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
817{
818 status_t status;
819
820 Mutex::Autolock _l(mLock);
821
822 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
823 if (playbackThread != NULL) {
824 return playbackThread->getRenderPosition(halFrames, dspFrames);
825 }
826
827 return BAD_VALUE;
828}
829
830void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
831{
832
833 Mutex::Autolock _l(mLock);
834
835 int pid = IPCThreadState::self()->getCallingPid();
836 if (mNotificationClients.indexOfKey(pid) < 0) {
837 sp<NotificationClient> notificationClient = new NotificationClient(this,
838 client,
839 pid);
840 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
841
842 mNotificationClients.add(pid, notificationClient);
843
844 sp<IBinder> binder = client->asBinder();
845 binder->linkToDeath(notificationClient);
846
847 // the config change is always sent from playback or record threads to avoid deadlock
848 // with AudioSystem::gLock
849 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
850 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
851 }
852
853 for (size_t i = 0; i < mRecordThreads.size(); i++) {
854 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
855 }
856 }
857}
858
859void AudioFlinger::removeNotificationClient(pid_t pid)
860{
861 Mutex::Autolock _l(mLock);
862
863 int index = mNotificationClients.indexOfKey(pid);
864 if (index >= 0) {
865 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
866 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700867 mNotificationClients.removeItem(pid);
868 }
869}
870
871// audioConfigChanged_l() must be called with AudioFlinger::mLock held
872void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
873{
874 size_t size = mNotificationClients.size();
875 for (size_t i = 0; i < size; i++) {
876 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
877 }
878}
879
880// removeClient_l() must be called with AudioFlinger::mLock held
881void AudioFlinger::removeClient_l(pid_t pid)
882{
883 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
884 mClients.removeItem(pid);
885}
886
887
888// ----------------------------------------------------------------------------
889
890AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
891 : Thread(false),
892 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
893 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
894{
895}
896
897AudioFlinger::ThreadBase::~ThreadBase()
898{
899 mParamCond.broadcast();
900 mNewParameters.clear();
901}
902
903void AudioFlinger::ThreadBase::exit()
904{
905 // keep a strong ref on ourself so that we wont get
906 // destroyed in the middle of requestExitAndWait()
907 sp <ThreadBase> strongMe = this;
908
909 LOGV("ThreadBase::exit");
910 {
911 AutoMutex lock(&mLock);
912 mExiting = true;
913 requestExit();
914 mWaitWorkCV.signal();
915 }
916 requestExitAndWait();
917}
918
919uint32_t AudioFlinger::ThreadBase::sampleRate() const
920{
921 return mSampleRate;
922}
923
924int AudioFlinger::ThreadBase::channelCount() const
925{
926 return (int)mChannelCount;
927}
928
929int AudioFlinger::ThreadBase::format() const
930{
931 return mFormat;
932}
933
934size_t AudioFlinger::ThreadBase::frameCount() const
935{
936 return mFrameCount;
937}
938
939status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
940{
941 status_t status;
942
943 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
944 Mutex::Autolock _l(mLock);
945
946 mNewParameters.add(keyValuePairs);
947 mWaitWorkCV.signal();
948 // wait condition with timeout in case the thread loop has exited
949 // before the request could be processed
950 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
951 status = mParamStatus;
952 mWaitWorkCV.signal();
953 } else {
954 status = TIMED_OUT;
955 }
956 return status;
957}
958
959void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
960{
961 Mutex::Autolock _l(mLock);
962 sendConfigEvent_l(event, param);
963}
964
965// sendConfigEvent_l() must be called with ThreadBase::mLock held
966void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
967{
968 ConfigEvent *configEvent = new ConfigEvent();
969 configEvent->mEvent = event;
970 configEvent->mParam = param;
971 mConfigEvents.add(configEvent);
972 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
973 mWaitWorkCV.signal();
974}
975
976void AudioFlinger::ThreadBase::processConfigEvents()
977{
978 mLock.lock();
979 while(!mConfigEvents.isEmpty()) {
980 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
981 ConfigEvent *configEvent = mConfigEvents[0];
982 mConfigEvents.removeAt(0);
983 // release mLock before locking AudioFlinger mLock: lock order is always
984 // AudioFlinger then ThreadBase to avoid cross deadlock
985 mLock.unlock();
986 mAudioFlinger->mLock.lock();
987 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
988 mAudioFlinger->mLock.unlock();
989 delete configEvent;
990 mLock.lock();
991 }
992 mLock.unlock();
993}
994
995status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
996{
997 const size_t SIZE = 256;
998 char buffer[SIZE];
999 String8 result;
1000
1001 bool locked = tryLock(mLock);
1002 if (!locked) {
1003 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1004 write(fd, buffer, strlen(buffer));
1005 }
1006
1007 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1008 result.append(buffer);
1009 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1010 result.append(buffer);
1011 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1012 result.append(buffer);
1013 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1014 result.append(buffer);
1015 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1016 result.append(buffer);
1017 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1018 result.append(buffer);
1019
1020 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1021 result.append(buffer);
1022 result.append(" Index Command");
1023 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1024 snprintf(buffer, SIZE, "\n %02d ", i);
1025 result.append(buffer);
1026 result.append(mNewParameters[i]);
1027 }
1028
1029 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1030 result.append(buffer);
1031 snprintf(buffer, SIZE, " Index event param\n");
1032 result.append(buffer);
1033 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1034 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1035 result.append(buffer);
1036 }
1037 result.append("\n");
1038
1039 write(fd, result.string(), result.size());
1040
1041 if (locked) {
1042 mLock.unlock();
1043 }
1044 return NO_ERROR;
1045}
1046
1047
1048// ----------------------------------------------------------------------------
1049
Dima Zavin799a70e2011-04-18 16:57:27 -07001050AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001051 : ThreadBase(audioFlinger, id),
1052 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
1053 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1054 mDevice(device)
1055{
1056 readOutputParameters();
1057
1058 mMasterVolume = mAudioFlinger->masterVolume();
1059 mMasterMute = mAudioFlinger->masterMute();
1060
Dima Zavinfce7a472011-04-19 22:30:36 -07001061 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1063 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1064 }
1065}
1066
1067AudioFlinger::PlaybackThread::~PlaybackThread()
1068{
1069 delete [] mMixBuffer;
1070}
1071
1072status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1073{
1074 dumpInternals(fd, args);
1075 dumpTracks(fd, args);
1076 dumpEffectChains(fd, args);
1077 return NO_ERROR;
1078}
1079
1080status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1081{
1082 const size_t SIZE = 256;
1083 char buffer[SIZE];
1084 String8 result;
1085
1086 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1087 result.append(buffer);
1088 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
1089 for (size_t i = 0; i < mTracks.size(); ++i) {
1090 sp<Track> track = mTracks[i];
1091 if (track != 0) {
1092 track->dump(buffer, SIZE);
1093 result.append(buffer);
1094 }
1095 }
1096
1097 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1098 result.append(buffer);
1099 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
1100 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1101 wp<Track> wTrack = mActiveTracks[i];
1102 if (wTrack != 0) {
1103 sp<Track> track = wTrack.promote();
1104 if (track != 0) {
1105 track->dump(buffer, SIZE);
1106 result.append(buffer);
1107 }
1108 }
1109 }
1110 write(fd, result.string(), result.size());
1111 return NO_ERROR;
1112}
1113
1114status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1115{
1116 const size_t SIZE = 256;
1117 char buffer[SIZE];
1118 String8 result;
1119
1120 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1121 write(fd, buffer, strlen(buffer));
1122
1123 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1124 sp<EffectChain> chain = mEffectChains[i];
1125 if (chain != 0) {
1126 chain->dump(fd, args);
1127 }
1128 }
1129 return NO_ERROR;
1130}
1131
1132status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1133{
1134 const size_t SIZE = 256;
1135 char buffer[SIZE];
1136 String8 result;
1137
1138 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1139 result.append(buffer);
1140 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1141 result.append(buffer);
1142 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1143 result.append(buffer);
1144 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1145 result.append(buffer);
1146 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1147 result.append(buffer);
1148 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1149 result.append(buffer);
1150 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1151 result.append(buffer);
1152 write(fd, result.string(), result.size());
1153
1154 dumpBase(fd, args);
1155
1156 return NO_ERROR;
1157}
1158
1159// Thread virtuals
1160status_t AudioFlinger::PlaybackThread::readyToRun()
1161{
1162 if (mSampleRate == 0) {
1163 LOGE("No working audio driver found.");
1164 return NO_INIT;
1165 }
1166 LOGI("AudioFlinger's thread %p ready to run", this);
1167 return NO_ERROR;
1168}
1169
1170void AudioFlinger::PlaybackThread::onFirstRef()
1171{
1172 const size_t SIZE = 256;
1173 char buffer[SIZE];
1174
1175 snprintf(buffer, SIZE, "Playback Thread %p", this);
1176
1177 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1178}
1179
1180// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1181sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1182 const sp<AudioFlinger::Client>& client,
1183 int streamType,
1184 uint32_t sampleRate,
1185 int format,
1186 int channelCount,
1187 int frameCount,
1188 const sp<IMemory>& sharedBuffer,
1189 int sessionId,
1190 status_t *status)
1191{
1192 sp<Track> track;
1193 status_t lStatus;
1194
1195 if (mType == DIRECT) {
1196 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
1197 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1198 sampleRate, format, channelCount, mOutput);
1199 lStatus = BAD_VALUE;
1200 goto Exit;
1201 }
1202 } else {
1203 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1204 if (sampleRate > mSampleRate*2) {
1205 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1206 lStatus = BAD_VALUE;
1207 goto Exit;
1208 }
1209 }
1210
1211 if (mOutput == 0) {
1212 LOGE("Audio driver not initialized.");
1213 lStatus = NO_INIT;
1214 goto Exit;
1215 }
1216
1217 { // scope for mLock
1218 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001219
1220 // all tracks in same audio session must share the same routing strategy otherwise
1221 // conflicts will happen when tracks are moved from one output to another by audio policy
1222 // manager
1223 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001224 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001225 for (size_t i = 0; i < mTracks.size(); ++i) {
1226 sp<Track> t = mTracks[i];
1227 if (t != 0) {
1228 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001229 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001230 lStatus = BAD_VALUE;
1231 goto Exit;
1232 }
1233 }
1234 }
1235
Mathias Agopian65ab4712010-07-14 17:59:35 -07001236 track = new Track(this, client, streamType, sampleRate, format,
1237 channelCount, frameCount, sharedBuffer, sessionId);
1238 if (track->getCblk() == NULL || track->name() < 0) {
1239 lStatus = NO_MEMORY;
1240 goto Exit;
1241 }
1242 mTracks.add(track);
1243
1244 sp<EffectChain> chain = getEffectChain_l(sessionId);
1245 if (chain != 0) {
1246 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1247 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001248 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 }
1250 }
1251 lStatus = NO_ERROR;
1252
1253Exit:
1254 if(status) {
1255 *status = lStatus;
1256 }
1257 return track;
1258}
1259
1260uint32_t AudioFlinger::PlaybackThread::latency() const
1261{
1262 if (mOutput) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001263 return mOutput->stream->get_latency(mOutput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001264 }
1265 else {
1266 return 0;
1267 }
1268}
1269
1270status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1271{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001272 mMasterVolume = value;
1273 return NO_ERROR;
1274}
1275
1276status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1277{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001278 mMasterMute = muted;
1279 return NO_ERROR;
1280}
1281
1282float AudioFlinger::PlaybackThread::masterVolume() const
1283{
1284 return mMasterVolume;
1285}
1286
1287bool AudioFlinger::PlaybackThread::masterMute() const
1288{
1289 return mMasterMute;
1290}
1291
1292status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1293{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001294 mStreamTypes[stream].volume = value;
1295 return NO_ERROR;
1296}
1297
1298status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1299{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001300 mStreamTypes[stream].mute = muted;
1301 return NO_ERROR;
1302}
1303
1304float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1305{
1306 return mStreamTypes[stream].volume;
1307}
1308
1309bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1310{
1311 return mStreamTypes[stream].mute;
1312}
1313
Mathias Agopian65ab4712010-07-14 17:59:35 -07001314// addTrack_l() must be called with ThreadBase::mLock held
1315status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1316{
1317 status_t status = ALREADY_EXISTS;
1318
1319 // set retry count for buffer fill
1320 track->mRetryCount = kMaxTrackStartupRetries;
1321 if (mActiveTracks.indexOf(track) < 0) {
1322 // the track is newly added, make sure it fills up all its
1323 // buffers before playing. This is to ensure the client will
1324 // effectively get the latency it requested.
1325 track->mFillingUpStatus = Track::FS_FILLING;
1326 track->mResetDone = false;
1327 mActiveTracks.add(track);
1328 if (track->mainBuffer() != mMixBuffer) {
1329 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1330 if (chain != 0) {
1331 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1332 chain->startTrack();
1333 }
1334 }
1335
1336 status = NO_ERROR;
1337 }
1338
1339 LOGV("mWaitWorkCV.broadcast");
1340 mWaitWorkCV.broadcast();
1341
1342 return status;
1343}
1344
1345// destroyTrack_l() must be called with ThreadBase::mLock held
1346void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1347{
1348 track->mState = TrackBase::TERMINATED;
1349 if (mActiveTracks.indexOf(track) < 0) {
1350 mTracks.remove(track);
1351 deleteTrackName_l(track->name());
1352 }
1353}
1354
1355String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1356{
Dima Zavinfce7a472011-04-19 22:30:36 -07001357 String8 out_s8;
1358 char *s;
1359
Dima Zavin799a70e2011-04-18 16:57:27 -07001360 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001361 out_s8 = String8(s);
1362 free(s);
1363 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364}
1365
1366// destroyTrack_l() must be called with AudioFlinger::mLock held
1367void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1368 AudioSystem::OutputDescriptor desc;
1369 void *param2 = 0;
1370
1371 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1372
1373 switch (event) {
1374 case AudioSystem::OUTPUT_OPENED:
1375 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1376 desc.channels = mChannels;
1377 desc.samplingRate = mSampleRate;
1378 desc.format = mFormat;
1379 desc.frameCount = mFrameCount;
1380 desc.latency = latency();
1381 param2 = &desc;
1382 break;
1383
1384 case AudioSystem::STREAM_CONFIG_CHANGED:
1385 param2 = &param;
1386 case AudioSystem::OUTPUT_CLOSED:
1387 default:
1388 break;
1389 }
1390 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1391}
1392
1393void AudioFlinger::PlaybackThread::readOutputParameters()
1394{
Dima Zavin799a70e2011-04-18 16:57:27 -07001395 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
1396 mChannels = mOutput->stream->common.get_channels(&mOutput->stream->common);
Dima Zavinfce7a472011-04-19 22:30:36 -07001397 mChannelCount = (uint16_t)popcount(mChannels);
Dima Zavin799a70e2011-04-18 16:57:27 -07001398 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1399 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1400 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001401
1402 // FIXME - Current mixer implementation only supports stereo output: Always
1403 // Allocate a stereo buffer even if HW output is mono.
1404 if (mMixBuffer != NULL) delete[] mMixBuffer;
1405 mMixBuffer = new int16_t[mFrameCount * 2];
1406 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1407
Eric Laurentde070132010-07-13 04:45:46 -07001408 // force reconfiguration of effect chains and engines to take new buffer size and audio
1409 // parameters into account
1410 // Note that mLock is not held when readOutputParameters() is called from the constructor
1411 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1412 // matter.
1413 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1414 Vector< sp<EffectChain> > effectChains = mEffectChains;
1415 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001416 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001417 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001418}
1419
1420status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1421{
1422 if (halFrames == 0 || dspFrames == 0) {
1423 return BAD_VALUE;
1424 }
1425 if (mOutput == 0) {
1426 return INVALID_OPERATION;
1427 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001428 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429
Dima Zavin799a70e2011-04-18 16:57:27 -07001430 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431}
1432
Eric Laurent39e94f82010-07-28 01:32:47 -07001433uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434{
1435 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001436 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001437 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001438 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 }
1440
1441 for (size_t i = 0; i < mTracks.size(); ++i) {
1442 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001443 if (sessionId == track->sessionId() &&
1444 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001445 result |= TRACK_SESSION;
1446 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001447 }
1448 }
1449
Eric Laurent39e94f82010-07-28 01:32:47 -07001450 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451}
1452
Eric Laurentde070132010-07-13 04:45:46 -07001453uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1454{
Dima Zavinfce7a472011-04-19 22:30:36 -07001455 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001456 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001457 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1458 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001459 }
1460 for (size_t i = 0; i < mTracks.size(); i++) {
1461 sp<Track> track = mTracks[i];
1462 if (sessionId == track->sessionId() &&
1463 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001464 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001465 }
1466 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001467 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001468}
1469
Mathias Agopian65ab4712010-07-14 17:59:35 -07001470sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1471{
1472 Mutex::Autolock _l(mLock);
1473 return getEffectChain_l(sessionId);
1474}
1475
1476sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1477{
1478 sp<EffectChain> chain;
1479
1480 size_t size = mEffectChains.size();
1481 for (size_t i = 0; i < size; i++) {
1482 if (mEffectChains[i]->sessionId() == sessionId) {
1483 chain = mEffectChains[i];
1484 break;
1485 }
1486 }
1487 return chain;
1488}
1489
1490void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1491{
1492 Mutex::Autolock _l(mLock);
1493 size_t size = mEffectChains.size();
1494 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001495 mEffectChains[i]->setMode_l(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001496 }
1497}
1498
1499// ----------------------------------------------------------------------------
1500
Dima Zavin799a70e2011-04-18 16:57:27 -07001501AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001502 : PlaybackThread(audioFlinger, output, id, device),
1503 mAudioMixer(0)
1504{
1505 mType = PlaybackThread::MIXER;
1506 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1507
1508 // FIXME - Current mixer implementation only supports stereo output
1509 if (mChannelCount == 1) {
1510 LOGE("Invalid audio hardware channel count");
1511 }
1512}
1513
1514AudioFlinger::MixerThread::~MixerThread()
1515{
1516 delete mAudioMixer;
1517}
1518
1519bool AudioFlinger::MixerThread::threadLoop()
1520{
1521 Vector< sp<Track> > tracksToRemove;
1522 uint32_t mixerStatus = MIXER_IDLE;
1523 nsecs_t standbyTime = systemTime();
1524 size_t mixBufferSize = mFrameCount * mFrameSize;
1525 // FIXME: Relaxed timing because of a certain device that can't meet latency
1526 // Should be reduced to 2x after the vendor fixes the driver issue
1527 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1528 nsecs_t lastWarning = 0;
1529 bool longStandbyExit = false;
1530 uint32_t activeSleepTime = activeSleepTimeUs();
1531 uint32_t idleSleepTime = idleSleepTimeUs();
1532 uint32_t sleepTime = idleSleepTime;
1533 Vector< sp<EffectChain> > effectChains;
1534
1535 while (!exitPending())
1536 {
1537 processConfigEvents();
1538
1539 mixerStatus = MIXER_IDLE;
1540 { // scope for mLock
1541
1542 Mutex::Autolock _l(mLock);
1543
1544 if (checkForNewParameters_l()) {
1545 mixBufferSize = mFrameCount * mFrameSize;
1546 // FIXME: Relaxed timing because of a certain device that can't meet latency
1547 // Should be reduced to 2x after the vendor fixes the driver issue
1548 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1549 activeSleepTime = activeSleepTimeUs();
1550 idleSleepTime = idleSleepTimeUs();
1551 }
1552
1553 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1554
1555 // put audio hardware into standby after short delay
1556 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1557 mSuspended) {
1558 if (!mStandby) {
1559 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001560 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001561 mStandby = true;
1562 mBytesWritten = 0;
1563 }
1564
1565 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1566 // we're about to wait, flush the binder command buffer
1567 IPCThreadState::self()->flushCommands();
1568
1569 if (exitPending()) break;
1570
1571 // wait until we have something to do...
1572 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1573 mWaitWorkCV.wait(mLock);
1574 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1575
1576 if (mMasterMute == false) {
1577 char value[PROPERTY_VALUE_MAX];
1578 property_get("ro.audio.silent", value, "0");
1579 if (atoi(value)) {
1580 LOGD("Silence is golden");
1581 setMasterMute(true);
1582 }
1583 }
1584
1585 standbyTime = systemTime() + kStandbyTimeInNsecs;
1586 sleepTime = idleSleepTime;
1587 continue;
1588 }
1589 }
1590
1591 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1592
1593 // prevent any changes in effect chain list and in each effect chain
1594 // during mixing and effect process as the audio buffers could be deleted
1595 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001596 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001597 }
1598
1599 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1600 // mix buffers...
1601 mAudioMixer->process();
1602 sleepTime = 0;
1603 standbyTime = systemTime() + kStandbyTimeInNsecs;
1604 //TODO: delay standby when effects have a tail
1605 } else {
1606 // If no tracks are ready, sleep once for the duration of an output
1607 // buffer size, then write 0s to the output
1608 if (sleepTime == 0) {
1609 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1610 sleepTime = activeSleepTime;
1611 } else {
1612 sleepTime = idleSleepTime;
1613 }
1614 } else if (mBytesWritten != 0 ||
1615 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1616 memset (mMixBuffer, 0, mixBufferSize);
1617 sleepTime = 0;
1618 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1619 }
1620 // TODO add standby time extension fct of effect tail
1621 }
1622
1623 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001624 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001625 }
1626 // sleepTime == 0 means we must write to audio hardware
1627 if (sleepTime == 0) {
1628 for (size_t i = 0; i < effectChains.size(); i ++) {
1629 effectChains[i]->process_l();
1630 }
1631 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001632 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001633 mLastWriteTime = systemTime();
1634 mInWrite = true;
1635 mBytesWritten += mixBufferSize;
1636
Dima Zavin799a70e2011-04-18 16:57:27 -07001637 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1639 mNumWrites++;
1640 mInWrite = false;
1641 nsecs_t now = systemTime();
1642 nsecs_t delta = now - mLastWriteTime;
1643 if (delta > maxPeriod) {
1644 mNumDelayedWrites++;
1645 if ((now - lastWarning) > kWarningThrottle) {
1646 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1647 ns2ms(delta), mNumDelayedWrites, this);
1648 lastWarning = now;
1649 }
1650 if (mStandby) {
1651 longStandbyExit = true;
1652 }
1653 }
1654 mStandby = false;
1655 } else {
1656 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001657 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 usleep(sleepTime);
1659 }
1660
1661 // finally let go of all our tracks, without the lock held
1662 // since we can't guarantee the destructors won't acquire that
1663 // same lock.
1664 tracksToRemove.clear();
1665
1666 // Effect chains will be actually deleted here if they were removed from
1667 // mEffectChains list during mixing or effects processing
1668 effectChains.clear();
1669 }
1670
1671 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001672 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001673 }
1674
1675 LOGV("MixerThread %p exiting", this);
1676 return false;
1677}
1678
1679// prepareTracks_l() must be called with ThreadBase::mLock held
1680uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1681{
1682
1683 uint32_t mixerStatus = MIXER_IDLE;
1684 // find out which tracks need to be processed
1685 size_t count = activeTracks.size();
1686 size_t mixedTracks = 0;
1687 size_t tracksWithEffect = 0;
1688
1689 float masterVolume = mMasterVolume;
1690 bool masterMute = mMasterMute;
1691
Eric Laurent571d49c2010-08-11 05:20:11 -07001692 if (masterMute) {
1693 masterVolume = 0;
1694 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07001696 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001697 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001698 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001699 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 masterVolume = (float)((v + (1 << 23)) >> 24);
1701 chain.clear();
1702 }
1703
1704 for (size_t i=0 ; i<count ; i++) {
1705 sp<Track> t = activeTracks[i].promote();
1706 if (t == 0) continue;
1707
1708 Track* const track = t.get();
1709 audio_track_cblk_t* cblk = track->cblk();
1710
1711 // The first time a track is added we wait
1712 // for all its buffers to be filled before processing it
1713 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001714 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001715 !track->isPaused() && !track->isTerminated())
1716 {
1717 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1718
1719 mixedTracks++;
1720
1721 // track->mainBuffer() != mMixBuffer means there is an effect chain
1722 // connected to the track
1723 chain.clear();
1724 if (track->mainBuffer() != mMixBuffer) {
1725 chain = getEffectChain_l(track->sessionId());
1726 // Delegate volume control to effect in track effect chain if needed
1727 if (chain != 0) {
1728 tracksWithEffect++;
1729 } else {
1730 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1731 track->name(), track->sessionId());
1732 }
1733 }
1734
1735
1736 int param = AudioMixer::VOLUME;
1737 if (track->mFillingUpStatus == Track::FS_FILLED) {
1738 // no ramp for the first volume setting
1739 track->mFillingUpStatus = Track::FS_ACTIVE;
1740 if (track->mState == TrackBase::RESUMING) {
1741 track->mState = TrackBase::ACTIVE;
1742 param = AudioMixer::RAMP_VOLUME;
1743 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001744 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001745 } else if (cblk->server != 0) {
1746 // If the track is stopped before the first frame was mixed,
1747 // do not apply ramp
1748 param = AudioMixer::RAMP_VOLUME;
1749 }
1750
1751 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001752 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001753 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001754 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001755 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001756 if (track->isPausing()) {
1757 track->setPaused();
1758 }
1759 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001760
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 // read original volumes with volume control
1762 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001764 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1765 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766
Eric Laurente0aed6d2010-09-10 17:44:44 -07001767 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001769 // Delegate volume control to effect in track effect chain if needed
1770 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1771 // Do not ramp volume if volume is controlled by effect
1772 param = AudioMixer::VOLUME;
1773 track->mHasVolumeController = true;
1774 } else {
1775 // force no volume ramp when volume controller was just disabled or removed
1776 // from effect chain to avoid volume spike
1777 if (track->mHasVolumeController) {
1778 param = AudioMixer::VOLUME;
1779 }
1780 track->mHasVolumeController = false;
1781 }
1782
1783 // Convert volumes from 8.24 to 4.12 format
1784 int16_t left, right, aux;
1785 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1786 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1787 left = int16_t(v_clamped);
1788 v_clamped = (vr + (1 << 11)) >> 12;
1789 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1790 right = int16_t(v_clamped);
1791
1792 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1793 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001794
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795 // XXX: these things DON'T need to be done each time
1796 mAudioMixer->setBufferProvider(track);
1797 mAudioMixer->enable(AudioMixer::MIXING);
1798
1799 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1800 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1801 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1802 mAudioMixer->setParameter(
1803 AudioMixer::TRACK,
1804 AudioMixer::FORMAT, (void *)track->format());
1805 mAudioMixer->setParameter(
1806 AudioMixer::TRACK,
1807 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
1808 mAudioMixer->setParameter(
1809 AudioMixer::RESAMPLE,
1810 AudioMixer::SAMPLE_RATE,
1811 (void *)(cblk->sampleRate));
1812 mAudioMixer->setParameter(
1813 AudioMixer::TRACK,
1814 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1815 mAudioMixer->setParameter(
1816 AudioMixer::TRACK,
1817 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1818
1819 // reset retry count
1820 track->mRetryCount = kMaxTrackRetries;
1821 mixerStatus = MIXER_TRACKS_READY;
1822 } else {
1823 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1824 if (track->isStopped()) {
1825 track->reset();
1826 }
1827 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1828 // We have consumed all the buffers of this track.
1829 // Remove it from the list of active tracks.
1830 tracksToRemove->add(track);
1831 } else {
1832 // No buffers for this track. Give it a few chances to
1833 // fill a buffer, then remove it from active list.
1834 if (--(track->mRetryCount) <= 0) {
1835 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1836 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07001837 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07001838 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839 } else if (mixerStatus != MIXER_TRACKS_READY) {
1840 mixerStatus = MIXER_TRACKS_ENABLED;
1841 }
1842 }
1843 mAudioMixer->disable(AudioMixer::MIXING);
1844 }
1845 }
1846
1847 // remove all the tracks that need to be...
1848 count = tracksToRemove->size();
1849 if (UNLIKELY(count)) {
1850 for (size_t i=0 ; i<count ; i++) {
1851 const sp<Track>& track = tracksToRemove->itemAt(i);
1852 mActiveTracks.remove(track);
1853 if (track->mainBuffer() != mMixBuffer) {
1854 chain = getEffectChain_l(track->sessionId());
1855 if (chain != 0) {
1856 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1857 chain->stopTrack();
1858 }
1859 }
1860 if (track->isTerminated()) {
1861 mTracks.remove(track);
1862 deleteTrackName_l(track->mName);
1863 }
1864 }
1865 }
1866
1867 // mix buffer must be cleared if all tracks are connected to an
1868 // effect chain as in this case the mixer will not write to
1869 // mix buffer and track effects will accumulate into it
1870 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1871 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1872 }
1873
1874 return mixerStatus;
1875}
1876
1877void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1878{
Eric Laurentde070132010-07-13 04:45:46 -07001879 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1880 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001882
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 size_t size = mTracks.size();
1884 for (size_t i = 0; i < size; i++) {
1885 sp<Track> t = mTracks[i];
1886 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07001887 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001888 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001889 }
1890 }
1891}
1892
1893
1894// getTrackName_l() must be called with ThreadBase::mLock held
1895int AudioFlinger::MixerThread::getTrackName_l()
1896{
1897 return mAudioMixer->getTrackName();
1898}
1899
1900// deleteTrackName_l() must be called with ThreadBase::mLock held
1901void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1902{
1903 LOGV("remove track (%d) and delete from mixer", name);
1904 mAudioMixer->deleteTrackName(name);
1905}
1906
1907// checkForNewParameters_l() must be called with ThreadBase::mLock held
1908bool AudioFlinger::MixerThread::checkForNewParameters_l()
1909{
1910 bool reconfig = false;
1911
1912 while (!mNewParameters.isEmpty()) {
1913 status_t status = NO_ERROR;
1914 String8 keyValuePair = mNewParameters[0];
1915 AudioParameter param = AudioParameter(keyValuePair);
1916 int value;
1917
1918 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1919 reconfig = true;
1920 }
1921 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001922 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 status = BAD_VALUE;
1924 } else {
1925 reconfig = true;
1926 }
1927 }
1928 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001929 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001930 status = BAD_VALUE;
1931 } else {
1932 reconfig = true;
1933 }
1934 }
1935 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1936 // do not accept frame count changes if tracks are open as the track buffer
1937 // size depends on frame count and correct behavior would not be garantied
1938 // if frame count is changed after track creation
1939 if (!mTracks.isEmpty()) {
1940 status = INVALID_OPERATION;
1941 } else {
1942 reconfig = true;
1943 }
1944 }
1945 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001946 // when changing the audio output device, call addBatteryData to notify
1947 // the change
1948 if (mDevice != value) {
1949 uint32_t params = 0;
1950 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07001951 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001952 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1953 }
1954
1955 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07001956 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08001957 // check if any other device (except speaker) is on
1958 if (value & deviceWithoutSpeaker ) {
1959 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1960 }
1961
1962 if (params != 0) {
1963 addBatteryData(params);
1964 }
1965 }
1966
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 // forward device change to effects that have requested to be
1968 // aware of attached audio device.
1969 mDevice = (uint32_t)value;
1970 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001971 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001972 }
1973 }
1974
1975 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001976 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07001977 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001979 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001980 mStandby = true;
1981 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07001982 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07001983 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984 }
1985 if (status == NO_ERROR && reconfig) {
1986 delete mAudioMixer;
1987 readOutputParameters();
1988 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1989 for (size_t i = 0; i < mTracks.size() ; i++) {
1990 int name = getTrackName_l();
1991 if (name < 0) break;
1992 mTracks[i]->mName = name;
1993 // limit track sample rate to 2 x new output sample rate
1994 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1995 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1996 }
1997 }
1998 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
1999 }
2000 }
2001
2002 mNewParameters.removeAt(0);
2003
2004 mParamStatus = status;
2005 mParamCond.signal();
2006 mWaitWorkCV.wait(mLock);
2007 }
2008 return reconfig;
2009}
2010
2011status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2012{
2013 const size_t SIZE = 256;
2014 char buffer[SIZE];
2015 String8 result;
2016
2017 PlaybackThread::dumpInternals(fd, args);
2018
2019 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2020 result.append(buffer);
2021 write(fd, result.string(), result.size());
2022 return NO_ERROR;
2023}
2024
2025uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2026{
Dima Zavin799a70e2011-04-18 16:57:27 -07002027 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028}
2029
2030uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2031{
Eric Laurent60e18242010-07-29 06:50:24 -07002032 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033}
2034
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002035uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2036{
2037 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2038}
2039
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002041AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002042 : PlaybackThread(audioFlinger, output, id, device)
2043{
2044 mType = PlaybackThread::DIRECT;
2045}
2046
2047AudioFlinger::DirectOutputThread::~DirectOutputThread()
2048{
2049}
2050
2051
2052static inline int16_t clamp16(int32_t sample)
2053{
2054 if ((sample>>15) ^ (sample>>31))
2055 sample = 0x7FFF ^ (sample>>31);
2056 return sample;
2057}
2058
2059static inline
2060int32_t mul(int16_t in, int16_t v)
2061{
2062#if defined(__arm__) && !defined(__thumb__)
2063 int32_t out;
2064 asm( "smulbb %[out], %[in], %[v] \n"
2065 : [out]"=r"(out)
2066 : [in]"%r"(in), [v]"r"(v)
2067 : );
2068 return out;
2069#else
2070 return in * int32_t(v);
2071#endif
2072}
2073
2074void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2075{
2076 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002077 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002078 return;
2079 }
2080
2081 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002082 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002083 size_t count = mFrameCount * mChannelCount;
2084 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2085 int16_t *dst = mMixBuffer + count-1;
2086 while(count--) {
2087 *dst-- = (int16_t)(*src--^0x80) << 8;
2088 }
2089 }
2090
2091 size_t frameCount = mFrameCount;
2092 int16_t *out = mMixBuffer;
2093 if (ramp) {
2094 if (mChannelCount == 1) {
2095 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2096 int32_t vlInc = d / (int32_t)frameCount;
2097 int32_t vl = ((int32_t)mLeftVolShort << 16);
2098 do {
2099 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2100 out++;
2101 vl += vlInc;
2102 } while (--frameCount);
2103
2104 } else {
2105 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2106 int32_t vlInc = d / (int32_t)frameCount;
2107 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2108 int32_t vrInc = d / (int32_t)frameCount;
2109 int32_t vl = ((int32_t)mLeftVolShort << 16);
2110 int32_t vr = ((int32_t)mRightVolShort << 16);
2111 do {
2112 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2113 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2114 out += 2;
2115 vl += vlInc;
2116 vr += vrInc;
2117 } while (--frameCount);
2118 }
2119 } else {
2120 if (mChannelCount == 1) {
2121 do {
2122 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2123 out++;
2124 } while (--frameCount);
2125 } else {
2126 do {
2127 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2128 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2129 out += 2;
2130 } while (--frameCount);
2131 }
2132 }
2133
2134 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002135 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002136 size_t count = mFrameCount * mChannelCount;
2137 int16_t *src = mMixBuffer;
2138 uint8_t *dst = (uint8_t *)mMixBuffer;
2139 while(count--) {
2140 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2141 }
2142 }
2143
2144 mLeftVolShort = leftVol;
2145 mRightVolShort = rightVol;
2146}
2147
2148bool AudioFlinger::DirectOutputThread::threadLoop()
2149{
2150 uint32_t mixerStatus = MIXER_IDLE;
2151 sp<Track> trackToRemove;
2152 sp<Track> activeTrack;
2153 nsecs_t standbyTime = systemTime();
2154 int8_t *curBuf;
2155 size_t mixBufferSize = mFrameCount*mFrameSize;
2156 uint32_t activeSleepTime = activeSleepTimeUs();
2157 uint32_t idleSleepTime = idleSleepTimeUs();
2158 uint32_t sleepTime = idleSleepTime;
2159 // use shorter standby delay as on normal output to release
2160 // hardware resources as soon as possible
2161 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2162
Mathias Agopian65ab4712010-07-14 17:59:35 -07002163 while (!exitPending())
2164 {
2165 bool rampVolume;
2166 uint16_t leftVol;
2167 uint16_t rightVol;
2168 Vector< sp<EffectChain> > effectChains;
2169
2170 processConfigEvents();
2171
2172 mixerStatus = MIXER_IDLE;
2173
2174 { // scope for the mLock
2175
2176 Mutex::Autolock _l(mLock);
2177
2178 if (checkForNewParameters_l()) {
2179 mixBufferSize = mFrameCount*mFrameSize;
2180 activeSleepTime = activeSleepTimeUs();
2181 idleSleepTime = idleSleepTimeUs();
2182 standbyDelay = microseconds(activeSleepTime*2);
2183 }
2184
2185 // put audio hardware into standby after short delay
2186 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2187 mSuspended) {
2188 // wait until we have something to do...
2189 if (!mStandby) {
2190 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002191 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 mStandby = true;
2193 mBytesWritten = 0;
2194 }
2195
2196 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2197 // we're about to wait, flush the binder command buffer
2198 IPCThreadState::self()->flushCommands();
2199
2200 if (exitPending()) break;
2201
2202 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2203 mWaitWorkCV.wait(mLock);
2204 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2205
2206 if (mMasterMute == false) {
2207 char value[PROPERTY_VALUE_MAX];
2208 property_get("ro.audio.silent", value, "0");
2209 if (atoi(value)) {
2210 LOGD("Silence is golden");
2211 setMasterMute(true);
2212 }
2213 }
2214
2215 standbyTime = systemTime() + standbyDelay;
2216 sleepTime = idleSleepTime;
2217 continue;
2218 }
2219 }
2220
2221 effectChains = mEffectChains;
2222
2223 // find out which tracks need to be processed
2224 if (mActiveTracks.size() != 0) {
2225 sp<Track> t = mActiveTracks[0].promote();
2226 if (t == 0) continue;
2227
2228 Track* const track = t.get();
2229 audio_track_cblk_t* cblk = track->cblk();
2230
2231 // The first time a track is added we wait
2232 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002233 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002234 !track->isPaused() && !track->isTerminated())
2235 {
2236 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2237
2238 if (track->mFillingUpStatus == Track::FS_FILLED) {
2239 track->mFillingUpStatus = Track::FS_ACTIVE;
2240 mLeftVolFloat = mRightVolFloat = 0;
2241 mLeftVolShort = mRightVolShort = 0;
2242 if (track->mState == TrackBase::RESUMING) {
2243 track->mState = TrackBase::ACTIVE;
2244 rampVolume = true;
2245 }
2246 } else if (cblk->server != 0) {
2247 // If the track is stopped before the first frame was mixed,
2248 // do not apply ramp
2249 rampVolume = true;
2250 }
2251 // compute volume for this track
2252 float left, right;
2253 if (track->isMuted() || mMasterMute || track->isPausing() ||
2254 mStreamTypes[track->type()].mute) {
2255 left = right = 0;
2256 if (track->isPausing()) {
2257 track->setPaused();
2258 }
2259 } else {
2260 float typeVolume = mStreamTypes[track->type()].volume;
2261 float v = mMasterVolume * typeVolume;
2262 float v_clamped = v * cblk->volume[0];
2263 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2264 left = v_clamped/MAX_GAIN;
2265 v_clamped = v * cblk->volume[1];
2266 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2267 right = v_clamped/MAX_GAIN;
2268 }
2269
2270 if (left != mLeftVolFloat || right != mRightVolFloat) {
2271 mLeftVolFloat = left;
2272 mRightVolFloat = right;
2273
2274 // If audio HAL implements volume control,
2275 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002276 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 left = 1.0f;
2278 right = 1.0f;
2279 }
2280
2281 // Convert volumes from float to 8.24
2282 uint32_t vl = (uint32_t)(left * (1 << 24));
2283 uint32_t vr = (uint32_t)(right * (1 << 24));
2284
2285 // Delegate volume control to effect in track effect chain if needed
2286 // only one effect chain can be present on DirectOutputThread, so if
2287 // there is one, the track is connected to it
2288 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002289 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002290 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002291 rampVolume = false;
2292 }
2293 }
2294
2295 // Convert volumes from 8.24 to 4.12 format
2296 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2297 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2298 leftVol = (uint16_t)v_clamped;
2299 v_clamped = (vr + (1 << 11)) >> 12;
2300 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2301 rightVol = (uint16_t)v_clamped;
2302 } else {
2303 leftVol = mLeftVolShort;
2304 rightVol = mRightVolShort;
2305 rampVolume = false;
2306 }
2307
2308 // reset retry count
2309 track->mRetryCount = kMaxTrackRetriesDirect;
2310 activeTrack = t;
2311 mixerStatus = MIXER_TRACKS_READY;
2312 } else {
2313 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2314 if (track->isStopped()) {
2315 track->reset();
2316 }
2317 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2318 // We have consumed all the buffers of this track.
2319 // Remove it from the list of active tracks.
2320 trackToRemove = track;
2321 } else {
2322 // No buffers for this track. Give it a few chances to
2323 // fill a buffer, then remove it from active list.
2324 if (--(track->mRetryCount) <= 0) {
2325 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2326 trackToRemove = track;
2327 } else {
2328 mixerStatus = MIXER_TRACKS_ENABLED;
2329 }
2330 }
2331 }
2332 }
2333
2334 // remove all the tracks that need to be...
2335 if (UNLIKELY(trackToRemove != 0)) {
2336 mActiveTracks.remove(trackToRemove);
2337 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002338 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2339 trackToRemove->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002340 effectChains[0]->stopTrack();
2341 }
2342 if (trackToRemove->isTerminated()) {
2343 mTracks.remove(trackToRemove);
2344 deleteTrackName_l(trackToRemove->mName);
2345 }
2346 }
2347
Eric Laurentde070132010-07-13 04:45:46 -07002348 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 }
2350
2351 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2352 AudioBufferProvider::Buffer buffer;
2353 size_t frameCount = mFrameCount;
2354 curBuf = (int8_t *)mMixBuffer;
2355 // output audio to hardware
2356 while (frameCount) {
2357 buffer.frameCount = frameCount;
2358 activeTrack->getNextBuffer(&buffer);
2359 if (UNLIKELY(buffer.raw == 0)) {
2360 memset(curBuf, 0, frameCount * mFrameSize);
2361 break;
2362 }
2363 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2364 frameCount -= buffer.frameCount;
2365 curBuf += buffer.frameCount * mFrameSize;
2366 activeTrack->releaseBuffer(&buffer);
2367 }
2368 sleepTime = 0;
2369 standbyTime = systemTime() + standbyDelay;
2370 } else {
2371 if (sleepTime == 0) {
2372 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2373 sleepTime = activeSleepTime;
2374 } else {
2375 sleepTime = idleSleepTime;
2376 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002377 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002378 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2379 sleepTime = 0;
2380 }
2381 }
2382
2383 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002384 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002385 }
2386 // sleepTime == 0 means we must write to audio hardware
2387 if (sleepTime == 0) {
2388 if (mixerStatus == MIXER_TRACKS_READY) {
2389 applyVolume(leftVol, rightVol, rampVolume);
2390 }
2391 for (size_t i = 0; i < effectChains.size(); i ++) {
2392 effectChains[i]->process_l();
2393 }
Eric Laurentde070132010-07-13 04:45:46 -07002394 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395
2396 mLastWriteTime = systemTime();
2397 mInWrite = true;
2398 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002399 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2401 mNumWrites++;
2402 mInWrite = false;
2403 mStandby = false;
2404 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002405 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 usleep(sleepTime);
2407 }
2408
2409 // finally let go of removed track, without the lock held
2410 // since we can't guarantee the destructors won't acquire that
2411 // same lock.
2412 trackToRemove.clear();
2413 activeTrack.clear();
2414
2415 // Effect chains will be actually deleted here if they were removed from
2416 // mEffectChains list during mixing or effects processing
2417 effectChains.clear();
2418 }
2419
2420 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002421 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 }
2423
2424 LOGV("DirectOutputThread %p exiting", this);
2425 return false;
2426}
2427
2428// getTrackName_l() must be called with ThreadBase::mLock held
2429int AudioFlinger::DirectOutputThread::getTrackName_l()
2430{
2431 return 0;
2432}
2433
2434// deleteTrackName_l() must be called with ThreadBase::mLock held
2435void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2436{
2437}
2438
2439// checkForNewParameters_l() must be called with ThreadBase::mLock held
2440bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2441{
2442 bool reconfig = false;
2443
2444 while (!mNewParameters.isEmpty()) {
2445 status_t status = NO_ERROR;
2446 String8 keyValuePair = mNewParameters[0];
2447 AudioParameter param = AudioParameter(keyValuePair);
2448 int value;
2449
2450 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2451 // do not accept frame count changes if tracks are open as the track buffer
2452 // size depends on frame count and correct behavior would not be garantied
2453 // if frame count is changed after track creation
2454 if (!mTracks.isEmpty()) {
2455 status = INVALID_OPERATION;
2456 } else {
2457 reconfig = true;
2458 }
2459 }
2460 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002461 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002462 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002464 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 mStandby = true;
2466 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002467 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002468 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002469 }
2470 if (status == NO_ERROR && reconfig) {
2471 readOutputParameters();
2472 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2473 }
2474 }
2475
2476 mNewParameters.removeAt(0);
2477
2478 mParamStatus = status;
2479 mParamCond.signal();
2480 mWaitWorkCV.wait(mLock);
2481 }
2482 return reconfig;
2483}
2484
2485uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2486{
2487 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002488 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002489 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 } else {
2491 time = 10000;
2492 }
2493 return time;
2494}
2495
2496uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2497{
2498 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002499 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002500 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 } else {
2502 time = 10000;
2503 }
2504 return time;
2505}
2506
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002507uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2508{
2509 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002510 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002511 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2512 } else {
2513 time = 10000;
2514 }
2515 return time;
2516}
2517
2518
Mathias Agopian65ab4712010-07-14 17:59:35 -07002519// ----------------------------------------------------------------------------
2520
2521AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2522 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2523{
2524 mType = PlaybackThread::DUPLICATING;
2525 addOutputTrack(mainThread);
2526}
2527
2528AudioFlinger::DuplicatingThread::~DuplicatingThread()
2529{
2530 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2531 mOutputTracks[i]->destroy();
2532 }
2533 mOutputTracks.clear();
2534}
2535
2536bool AudioFlinger::DuplicatingThread::threadLoop()
2537{
2538 Vector< sp<Track> > tracksToRemove;
2539 uint32_t mixerStatus = MIXER_IDLE;
2540 nsecs_t standbyTime = systemTime();
2541 size_t mixBufferSize = mFrameCount*mFrameSize;
2542 SortedVector< sp<OutputTrack> > outputTracks;
2543 uint32_t writeFrames = 0;
2544 uint32_t activeSleepTime = activeSleepTimeUs();
2545 uint32_t idleSleepTime = idleSleepTimeUs();
2546 uint32_t sleepTime = idleSleepTime;
2547 Vector< sp<EffectChain> > effectChains;
2548
2549 while (!exitPending())
2550 {
2551 processConfigEvents();
2552
2553 mixerStatus = MIXER_IDLE;
2554 { // scope for the mLock
2555
2556 Mutex::Autolock _l(mLock);
2557
2558 if (checkForNewParameters_l()) {
2559 mixBufferSize = mFrameCount*mFrameSize;
2560 updateWaitTime();
2561 activeSleepTime = activeSleepTimeUs();
2562 idleSleepTime = idleSleepTimeUs();
2563 }
2564
2565 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2566
2567 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2568 outputTracks.add(mOutputTracks[i]);
2569 }
2570
2571 // put audio hardware into standby after short delay
2572 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2573 mSuspended) {
2574 if (!mStandby) {
2575 for (size_t i = 0; i < outputTracks.size(); i++) {
2576 outputTracks[i]->stop();
2577 }
2578 mStandby = true;
2579 mBytesWritten = 0;
2580 }
2581
2582 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2583 // we're about to wait, flush the binder command buffer
2584 IPCThreadState::self()->flushCommands();
2585 outputTracks.clear();
2586
2587 if (exitPending()) break;
2588
2589 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2590 mWaitWorkCV.wait(mLock);
2591 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2592 if (mMasterMute == false) {
2593 char value[PROPERTY_VALUE_MAX];
2594 property_get("ro.audio.silent", value, "0");
2595 if (atoi(value)) {
2596 LOGD("Silence is golden");
2597 setMasterMute(true);
2598 }
2599 }
2600
2601 standbyTime = systemTime() + kStandbyTimeInNsecs;
2602 sleepTime = idleSleepTime;
2603 continue;
2604 }
2605 }
2606
2607 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2608
2609 // prevent any changes in effect chain list and in each effect chain
2610 // during mixing and effect process as the audio buffers could be deleted
2611 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002612 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002613 }
2614
2615 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2616 // mix buffers...
2617 if (outputsReady(outputTracks)) {
2618 mAudioMixer->process();
2619 } else {
2620 memset(mMixBuffer, 0, mixBufferSize);
2621 }
2622 sleepTime = 0;
2623 writeFrames = mFrameCount;
2624 } else {
2625 if (sleepTime == 0) {
2626 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2627 sleepTime = activeSleepTime;
2628 } else {
2629 sleepTime = idleSleepTime;
2630 }
2631 } else if (mBytesWritten != 0) {
2632 // flush remaining overflow buffers in output tracks
2633 for (size_t i = 0; i < outputTracks.size(); i++) {
2634 if (outputTracks[i]->isActive()) {
2635 sleepTime = 0;
2636 writeFrames = 0;
2637 memset(mMixBuffer, 0, mixBufferSize);
2638 break;
2639 }
2640 }
2641 }
2642 }
2643
2644 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002645 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 }
2647 // sleepTime == 0 means we must write to audio hardware
2648 if (sleepTime == 0) {
2649 for (size_t i = 0; i < effectChains.size(); i ++) {
2650 effectChains[i]->process_l();
2651 }
2652 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002653 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002654
2655 standbyTime = systemTime() + kStandbyTimeInNsecs;
2656 for (size_t i = 0; i < outputTracks.size(); i++) {
2657 outputTracks[i]->write(mMixBuffer, writeFrames);
2658 }
2659 mStandby = false;
2660 mBytesWritten += mixBufferSize;
2661 } else {
2662 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002663 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002664 usleep(sleepTime);
2665 }
2666
2667 // finally let go of all our tracks, without the lock held
2668 // since we can't guarantee the destructors won't acquire that
2669 // same lock.
2670 tracksToRemove.clear();
2671 outputTracks.clear();
2672
2673 // Effect chains will be actually deleted here if they were removed from
2674 // mEffectChains list during mixing or effects processing
2675 effectChains.clear();
2676 }
2677
2678 return false;
2679}
2680
2681void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2682{
2683 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2684 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2685 this,
2686 mSampleRate,
2687 mFormat,
2688 mChannelCount,
2689 frameCount);
2690 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002691 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 mOutputTracks.add(outputTrack);
2693 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2694 updateWaitTime();
2695 }
2696}
2697
2698void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2699{
2700 Mutex::Autolock _l(mLock);
2701 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2702 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2703 mOutputTracks[i]->destroy();
2704 mOutputTracks.removeAt(i);
2705 updateWaitTime();
2706 return;
2707 }
2708 }
2709 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2710}
2711
2712void AudioFlinger::DuplicatingThread::updateWaitTime()
2713{
2714 mWaitTimeMs = UINT_MAX;
2715 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2716 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2717 if (strong != NULL) {
2718 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2719 if (waitTimeMs < mWaitTimeMs) {
2720 mWaitTimeMs = waitTimeMs;
2721 }
2722 }
2723 }
2724}
2725
2726
2727bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2728{
2729 for (size_t i = 0; i < outputTracks.size(); i++) {
2730 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2731 if (thread == 0) {
2732 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2733 return false;
2734 }
2735 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2736 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2737 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2738 return false;
2739 }
2740 }
2741 return true;
2742}
2743
2744uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2745{
2746 return (mWaitTimeMs * 1000) / 2;
2747}
2748
2749// ----------------------------------------------------------------------------
2750
2751// TrackBase constructor must be called with AudioFlinger::mLock held
2752AudioFlinger::ThreadBase::TrackBase::TrackBase(
2753 const wp<ThreadBase>& thread,
2754 const sp<Client>& client,
2755 uint32_t sampleRate,
2756 int format,
2757 int channelCount,
2758 int frameCount,
2759 uint32_t flags,
2760 const sp<IMemory>& sharedBuffer,
2761 int sessionId)
2762 : RefBase(),
2763 mThread(thread),
2764 mClient(client),
2765 mCblk(0),
2766 mFrameCount(0),
2767 mState(IDLE),
2768 mClientTid(-1),
2769 mFormat(format),
2770 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2771 mSessionId(sessionId)
2772{
2773 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2774
2775 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2776 size_t size = sizeof(audio_track_cblk_t);
2777 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2778 if (sharedBuffer == 0) {
2779 size += bufferSize;
2780 }
2781
2782 if (client != NULL) {
2783 mCblkMemory = client->heap()->allocate(size);
2784 if (mCblkMemory != 0) {
2785 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2786 if (mCblk) { // construct the shared structure in-place.
2787 new(mCblk) audio_track_cblk_t();
2788 // clear all buffers
2789 mCblk->frameCount = frameCount;
2790 mCblk->sampleRate = sampleRate;
2791 mCblk->channelCount = (uint8_t)channelCount;
2792 if (sharedBuffer == 0) {
2793 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2794 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2795 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002796 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 mCblk->flags = CBLK_UNDERRUN_ON;
2798 } else {
2799 mBuffer = sharedBuffer->pointer();
2800 }
2801 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2802 }
2803 } else {
2804 LOGE("not enough memory for AudioTrack size=%u", size);
2805 client->heap()->dump("AudioTrack");
2806 return;
2807 }
2808 } else {
2809 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2810 if (mCblk) { // construct the shared structure in-place.
2811 new(mCblk) audio_track_cblk_t();
2812 // clear all buffers
2813 mCblk->frameCount = frameCount;
2814 mCblk->sampleRate = sampleRate;
2815 mCblk->channelCount = (uint8_t)channelCount;
2816 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2817 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2818 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002819 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002820 mCblk->flags = CBLK_UNDERRUN_ON;
2821 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2822 }
2823 }
2824}
2825
2826AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2827{
2828 if (mCblk) {
2829 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2830 if (mClient == NULL) {
2831 delete mCblk;
2832 }
2833 }
2834 mCblkMemory.clear(); // and free the shared memory
2835 if (mClient != NULL) {
2836 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2837 mClient.clear();
2838 }
2839}
2840
2841void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2842{
2843 buffer->raw = 0;
2844 mFrameCount = buffer->frameCount;
2845 step();
2846 buffer->frameCount = 0;
2847}
2848
2849bool AudioFlinger::ThreadBase::TrackBase::step() {
2850 bool result;
2851 audio_track_cblk_t* cblk = this->cblk();
2852
2853 result = cblk->stepServer(mFrameCount);
2854 if (!result) {
2855 LOGV("stepServer failed acquiring cblk mutex");
2856 mFlags |= STEPSERVER_FAILED;
2857 }
2858 return result;
2859}
2860
2861void AudioFlinger::ThreadBase::TrackBase::reset() {
2862 audio_track_cblk_t* cblk = this->cblk();
2863
2864 cblk->user = 0;
2865 cblk->server = 0;
2866 cblk->userBase = 0;
2867 cblk->serverBase = 0;
2868 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2869 LOGV("TrackBase::reset");
2870}
2871
2872sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2873{
2874 return mCblkMemory;
2875}
2876
2877int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2878 return (int)mCblk->sampleRate;
2879}
2880
2881int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
2882 return (int)mCblk->channelCount;
2883}
2884
2885void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2886 audio_track_cblk_t* cblk = this->cblk();
2887 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2888 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2889
2890 // Check validity of returned pointer in case the track control block would have been corrupted.
2891 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2892 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2893 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2894 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
2895 bufferStart, bufferEnd, mBuffer, mBufferEnd,
2896 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
2897 return 0;
2898 }
2899
2900 return bufferStart;
2901}
2902
2903// ----------------------------------------------------------------------------
2904
2905// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2906AudioFlinger::PlaybackThread::Track::Track(
2907 const wp<ThreadBase>& thread,
2908 const sp<Client>& client,
2909 int streamType,
2910 uint32_t sampleRate,
2911 int format,
2912 int channelCount,
2913 int frameCount,
2914 const sp<IMemory>& sharedBuffer,
2915 int sessionId)
2916 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07002917 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2918 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919{
2920 if (mCblk != NULL) {
2921 sp<ThreadBase> baseThread = thread.promote();
2922 if (baseThread != 0) {
2923 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2924 mName = playbackThread->getTrackName_l();
2925 mMainBuffer = playbackThread->mixBuffer();
2926 }
2927 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2928 if (mName < 0) {
2929 LOGE("no more track names available");
2930 }
2931 mVolume[0] = 1.0f;
2932 mVolume[1] = 1.0f;
2933 mStreamType = streamType;
2934 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2935 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Dima Zavinfce7a472011-04-19 22:30:36 -07002936 mCblk->frameSize = audio_is_linear_pcm(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002937 }
2938}
2939
2940AudioFlinger::PlaybackThread::Track::~Track()
2941{
2942 LOGV("PlaybackThread::Track destructor");
2943 sp<ThreadBase> thread = mThread.promote();
2944 if (thread != 0) {
2945 Mutex::Autolock _l(thread->mLock);
2946 mState = TERMINATED;
2947 }
2948}
2949
2950void AudioFlinger::PlaybackThread::Track::destroy()
2951{
2952 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2953 // by removing it from mTracks vector, so there is a risk that this Tracks's
2954 // desctructor is called. As the destructor needs to lock mLock,
2955 // we must acquire a strong reference on this Track before locking mLock
2956 // here so that the destructor is called only when exiting this function.
2957 // On the other hand, as long as Track::destroy() is only called by
2958 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2959 // this Track with its member mTrack.
2960 sp<Track> keep(this);
2961 { // scope for mLock
2962 sp<ThreadBase> thread = mThread.promote();
2963 if (thread != 0) {
2964 if (!isOutputTrack()) {
2965 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07002966 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07002967 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07002968 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002969
2970 // to track the speaker usage
2971 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002972 }
2973 AudioSystem::releaseOutput(thread->id());
2974 }
2975 Mutex::Autolock _l(thread->mLock);
2976 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2977 playbackThread->destroyTrack_l(this);
2978 }
2979 }
2980}
2981
2982void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
2983{
2984 snprintf(buffer, size, " %05d %05d %03u %03u %03u %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
2985 mName - AudioMixer::TRACK0,
2986 (mClient == NULL) ? getpid() : mClient->pid(),
2987 mStreamType,
2988 mFormat,
2989 mCblk->channelCount,
2990 mSessionId,
2991 mFrameCount,
2992 mState,
2993 mMute,
2994 mFillingUpStatus,
2995 mCblk->sampleRate,
2996 mCblk->volume[0],
2997 mCblk->volume[1],
2998 mCblk->server,
2999 mCblk->user,
3000 (int)mMainBuffer,
3001 (int)mAuxBuffer);
3002}
3003
3004status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3005{
3006 audio_track_cblk_t* cblk = this->cblk();
3007 uint32_t framesReady;
3008 uint32_t framesReq = buffer->frameCount;
3009
3010 // Check if last stepServer failed, try to step now
3011 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3012 if (!step()) goto getNextBuffer_exit;
3013 LOGV("stepServer recovered");
3014 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3015 }
3016
3017 framesReady = cblk->framesReady();
3018
3019 if (LIKELY(framesReady)) {
3020 uint32_t s = cblk->server;
3021 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3022
3023 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3024 if (framesReq > framesReady) {
3025 framesReq = framesReady;
3026 }
3027 if (s + framesReq > bufferEnd) {
3028 framesReq = bufferEnd - s;
3029 }
3030
3031 buffer->raw = getBuffer(s, framesReq);
3032 if (buffer->raw == 0) goto getNextBuffer_exit;
3033
3034 buffer->frameCount = framesReq;
3035 return NO_ERROR;
3036 }
3037
3038getNextBuffer_exit:
3039 buffer->raw = 0;
3040 buffer->frameCount = 0;
3041 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3042 return NOT_ENOUGH_DATA;
3043}
3044
3045bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003046 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047
3048 if (mCblk->framesReady() >= mCblk->frameCount ||
3049 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3050 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003051 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 return true;
3053 }
3054 return false;
3055}
3056
3057status_t AudioFlinger::PlaybackThread::Track::start()
3058{
3059 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003060 LOGV("start(%d), calling thread %d session %d",
3061 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 sp<ThreadBase> thread = mThread.promote();
3063 if (thread != 0) {
3064 Mutex::Autolock _l(thread->mLock);
3065 int state = mState;
3066 // here the track could be either new, or restarted
3067 // in both cases "unstop" the track
3068 if (mState == PAUSED) {
3069 mState = TrackBase::RESUMING;
3070 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3071 } else {
3072 mState = TrackBase::ACTIVE;
3073 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3074 }
3075
3076 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3077 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003078 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003079 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003080 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003082
3083 // to track the speaker usage
3084 if (status == NO_ERROR) {
3085 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3086 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003087 }
3088 if (status == NO_ERROR) {
3089 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3090 playbackThread->addTrack_l(this);
3091 } else {
3092 mState = state;
3093 }
3094 } else {
3095 status = BAD_VALUE;
3096 }
3097 return status;
3098}
3099
3100void AudioFlinger::PlaybackThread::Track::stop()
3101{
3102 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3103 sp<ThreadBase> thread = mThread.promote();
3104 if (thread != 0) {
3105 Mutex::Autolock _l(thread->mLock);
3106 int state = mState;
3107 if (mState > STOPPED) {
3108 mState = STOPPED;
3109 // If the track is not active (PAUSED and buffers full), flush buffers
3110 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3111 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3112 reset();
3113 }
3114 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3115 }
3116 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3117 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003118 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003119 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003120 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003122
3123 // to track the speaker usage
3124 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 }
3126 }
3127}
3128
3129void AudioFlinger::PlaybackThread::Track::pause()
3130{
3131 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3132 sp<ThreadBase> thread = mThread.promote();
3133 if (thread != 0) {
3134 Mutex::Autolock _l(thread->mLock);
3135 if (mState == ACTIVE || mState == RESUMING) {
3136 mState = PAUSING;
3137 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3138 if (!isOutputTrack()) {
3139 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003140 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003141 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003142 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003144
3145 // to track the speaker usage
3146 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 }
3148 }
3149 }
3150}
3151
3152void AudioFlinger::PlaybackThread::Track::flush()
3153{
3154 LOGV("flush(%d)", mName);
3155 sp<ThreadBase> thread = mThread.promote();
3156 if (thread != 0) {
3157 Mutex::Autolock _l(thread->mLock);
3158 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3159 return;
3160 }
3161 // No point remaining in PAUSED state after a flush => go to
3162 // STOPPED state
3163 mState = STOPPED;
3164
Eric Laurent38ccae22011-03-28 18:37:07 -07003165 // do not reset the track if it is still in the process of being stopped or paused.
3166 // this will be done by prepareTracks_l() when the track is stopped.
3167 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3168 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3169 reset();
3170 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003171 }
3172}
3173
3174void AudioFlinger::PlaybackThread::Track::reset()
3175{
3176 // Do not reset twice to avoid discarding data written just after a flush and before
3177 // the audioflinger thread detects the track is stopped.
3178 if (!mResetDone) {
3179 TrackBase::reset();
3180 // Force underrun condition to avoid false underrun callback until first data is
3181 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003182 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3183 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 mFillingUpStatus = FS_FILLING;
3185 mResetDone = true;
3186 }
3187}
3188
3189void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3190{
3191 mMute = muted;
3192}
3193
3194void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3195{
3196 mVolume[0] = left;
3197 mVolume[1] = right;
3198}
3199
3200status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3201{
3202 status_t status = DEAD_OBJECT;
3203 sp<ThreadBase> thread = mThread.promote();
3204 if (thread != 0) {
3205 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3206 status = playbackThread->attachAuxEffect(this, EffectId);
3207 }
3208 return status;
3209}
3210
3211void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3212{
3213 mAuxEffectId = EffectId;
3214 mAuxBuffer = buffer;
3215}
3216
3217// ----------------------------------------------------------------------------
3218
3219// RecordTrack constructor must be called with AudioFlinger::mLock held
3220AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3221 const wp<ThreadBase>& thread,
3222 const sp<Client>& client,
3223 uint32_t sampleRate,
3224 int format,
3225 int channelCount,
3226 int frameCount,
3227 uint32_t flags,
3228 int sessionId)
3229 : TrackBase(thread, client, sampleRate, format,
3230 channelCount, frameCount, flags, 0, sessionId),
3231 mOverflow(false)
3232{
3233 if (mCblk != NULL) {
3234 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003235 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 mCblk->frameSize = channelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003237 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003238 mCblk->frameSize = channelCount * sizeof(int8_t);
3239 } else {
3240 mCblk->frameSize = sizeof(int8_t);
3241 }
3242 }
3243}
3244
3245AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3246{
3247 sp<ThreadBase> thread = mThread.promote();
3248 if (thread != 0) {
3249 AudioSystem::releaseInput(thread->id());
3250 }
3251}
3252
3253status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3254{
3255 audio_track_cblk_t* cblk = this->cblk();
3256 uint32_t framesAvail;
3257 uint32_t framesReq = buffer->frameCount;
3258
3259 // Check if last stepServer failed, try to step now
3260 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3261 if (!step()) goto getNextBuffer_exit;
3262 LOGV("stepServer recovered");
3263 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3264 }
3265
3266 framesAvail = cblk->framesAvailable_l();
3267
3268 if (LIKELY(framesAvail)) {
3269 uint32_t s = cblk->server;
3270 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3271
3272 if (framesReq > framesAvail) {
3273 framesReq = framesAvail;
3274 }
3275 if (s + framesReq > bufferEnd) {
3276 framesReq = bufferEnd - s;
3277 }
3278
3279 buffer->raw = getBuffer(s, framesReq);
3280 if (buffer->raw == 0) goto getNextBuffer_exit;
3281
3282 buffer->frameCount = framesReq;
3283 return NO_ERROR;
3284 }
3285
3286getNextBuffer_exit:
3287 buffer->raw = 0;
3288 buffer->frameCount = 0;
3289 return NOT_ENOUGH_DATA;
3290}
3291
3292status_t AudioFlinger::RecordThread::RecordTrack::start()
3293{
3294 sp<ThreadBase> thread = mThread.promote();
3295 if (thread != 0) {
3296 RecordThread *recordThread = (RecordThread *)thread.get();
3297 return recordThread->start(this);
3298 } else {
3299 return BAD_VALUE;
3300 }
3301}
3302
3303void AudioFlinger::RecordThread::RecordTrack::stop()
3304{
3305 sp<ThreadBase> thread = mThread.promote();
3306 if (thread != 0) {
3307 RecordThread *recordThread = (RecordThread *)thread.get();
3308 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003309 TrackBase::reset();
3310 // Force overerrun condition to avoid false overrun callback until first data is
3311 // read from buffer
3312 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003313 }
3314}
3315
3316void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3317{
3318 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
3319 (mClient == NULL) ? getpid() : mClient->pid(),
3320 mFormat,
3321 mCblk->channelCount,
3322 mSessionId,
3323 mFrameCount,
3324 mState,
3325 mCblk->sampleRate,
3326 mCblk->server,
3327 mCblk->user);
3328}
3329
3330
3331// ----------------------------------------------------------------------------
3332
3333AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3334 const wp<ThreadBase>& thread,
3335 DuplicatingThread *sourceThread,
3336 uint32_t sampleRate,
3337 int format,
3338 int channelCount,
3339 int frameCount)
Dima Zavinfce7a472011-04-19 22:30:36 -07003340 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelCount, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 mActive(false), mSourceThread(sourceThread)
3342{
3343
3344 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3345 if (mCblk != NULL) {
3346 mCblk->flags |= CBLK_DIRECTION_OUT;
3347 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3348 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3349 mOutBuffer.frameCount = 0;
3350 playbackThread->mTracks.add(this);
3351 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3352 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
3353 } else {
3354 LOGW("Error creating output track on thread %p", playbackThread);
3355 }
3356}
3357
3358AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3359{
3360 clearBufferQueue();
3361}
3362
3363status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3364{
3365 status_t status = Track::start();
3366 if (status != NO_ERROR) {
3367 return status;
3368 }
3369
3370 mActive = true;
3371 mRetryCount = 127;
3372 return status;
3373}
3374
3375void AudioFlinger::PlaybackThread::OutputTrack::stop()
3376{
3377 Track::stop();
3378 clearBufferQueue();
3379 mOutBuffer.frameCount = 0;
3380 mActive = false;
3381}
3382
3383bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3384{
3385 Buffer *pInBuffer;
3386 Buffer inBuffer;
3387 uint32_t channelCount = mCblk->channelCount;
3388 bool outputBufferFull = false;
3389 inBuffer.frameCount = frames;
3390 inBuffer.i16 = data;
3391
3392 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3393
3394 if (!mActive && frames != 0) {
3395 start();
3396 sp<ThreadBase> thread = mThread.promote();
3397 if (thread != 0) {
3398 MixerThread *mixerThread = (MixerThread *)thread.get();
3399 if (mCblk->frameCount > frames){
3400 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3401 uint32_t startFrames = (mCblk->frameCount - frames);
3402 pInBuffer = new Buffer;
3403 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3404 pInBuffer->frameCount = startFrames;
3405 pInBuffer->i16 = pInBuffer->mBuffer;
3406 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3407 mBufferQueue.add(pInBuffer);
3408 } else {
3409 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3410 }
3411 }
3412 }
3413 }
3414
3415 while (waitTimeLeftMs) {
3416 // First write pending buffers, then new data
3417 if (mBufferQueue.size()) {
3418 pInBuffer = mBufferQueue.itemAt(0);
3419 } else {
3420 pInBuffer = &inBuffer;
3421 }
3422
3423 if (pInBuffer->frameCount == 0) {
3424 break;
3425 }
3426
3427 if (mOutBuffer.frameCount == 0) {
3428 mOutBuffer.frameCount = pInBuffer->frameCount;
3429 nsecs_t startTime = systemTime();
3430 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3431 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3432 outputBufferFull = true;
3433 break;
3434 }
3435 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3436 if (waitTimeLeftMs >= waitTimeMs) {
3437 waitTimeLeftMs -= waitTimeMs;
3438 } else {
3439 waitTimeLeftMs = 0;
3440 }
3441 }
3442
3443 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3444 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3445 mCblk->stepUser(outFrames);
3446 pInBuffer->frameCount -= outFrames;
3447 pInBuffer->i16 += outFrames * channelCount;
3448 mOutBuffer.frameCount -= outFrames;
3449 mOutBuffer.i16 += outFrames * channelCount;
3450
3451 if (pInBuffer->frameCount == 0) {
3452 if (mBufferQueue.size()) {
3453 mBufferQueue.removeAt(0);
3454 delete [] pInBuffer->mBuffer;
3455 delete pInBuffer;
3456 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3457 } else {
3458 break;
3459 }
3460 }
3461 }
3462
3463 // If we could not write all frames, allocate a buffer and queue it for next time.
3464 if (inBuffer.frameCount) {
3465 sp<ThreadBase> thread = mThread.promote();
3466 if (thread != 0 && !thread->standby()) {
3467 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3468 pInBuffer = new Buffer;
3469 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3470 pInBuffer->frameCount = inBuffer.frameCount;
3471 pInBuffer->i16 = pInBuffer->mBuffer;
3472 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3473 mBufferQueue.add(pInBuffer);
3474 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3475 } else {
3476 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3477 }
3478 }
3479 }
3480
3481 // Calling write() with a 0 length buffer, means that no more data will be written:
3482 // If no more buffers are pending, fill output track buffer to make sure it is started
3483 // by output mixer.
3484 if (frames == 0 && mBufferQueue.size() == 0) {
3485 if (mCblk->user < mCblk->frameCount) {
3486 frames = mCblk->frameCount - mCblk->user;
3487 pInBuffer = new Buffer;
3488 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3489 pInBuffer->frameCount = frames;
3490 pInBuffer->i16 = pInBuffer->mBuffer;
3491 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3492 mBufferQueue.add(pInBuffer);
3493 } else if (mActive) {
3494 stop();
3495 }
3496 }
3497
3498 return outputBufferFull;
3499}
3500
3501status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3502{
3503 int active;
3504 status_t result;
3505 audio_track_cblk_t* cblk = mCblk;
3506 uint32_t framesReq = buffer->frameCount;
3507
3508// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3509 buffer->frameCount = 0;
3510
3511 uint32_t framesAvail = cblk->framesAvailable();
3512
3513
3514 if (framesAvail == 0) {
3515 Mutex::Autolock _l(cblk->lock);
3516 goto start_loop_here;
3517 while (framesAvail == 0) {
3518 active = mActive;
3519 if (UNLIKELY(!active)) {
3520 LOGV("Not active and NO_MORE_BUFFERS");
3521 return AudioTrack::NO_MORE_BUFFERS;
3522 }
3523 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3524 if (result != NO_ERROR) {
3525 return AudioTrack::NO_MORE_BUFFERS;
3526 }
3527 // read the server count again
3528 start_loop_here:
3529 framesAvail = cblk->framesAvailable_l();
3530 }
3531 }
3532
3533// if (framesAvail < framesReq) {
3534// return AudioTrack::NO_MORE_BUFFERS;
3535// }
3536
3537 if (framesReq > framesAvail) {
3538 framesReq = framesAvail;
3539 }
3540
3541 uint32_t u = cblk->user;
3542 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3543
3544 if (u + framesReq > bufferEnd) {
3545 framesReq = bufferEnd - u;
3546 }
3547
3548 buffer->frameCount = framesReq;
3549 buffer->raw = (void *)cblk->buffer(u);
3550 return NO_ERROR;
3551}
3552
3553
3554void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3555{
3556 size_t size = mBufferQueue.size();
3557 Buffer *pBuffer;
3558
3559 for (size_t i = 0; i < size; i++) {
3560 pBuffer = mBufferQueue.itemAt(i);
3561 delete [] pBuffer->mBuffer;
3562 delete pBuffer;
3563 }
3564 mBufferQueue.clear();
3565}
3566
3567// ----------------------------------------------------------------------------
3568
3569AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3570 : RefBase(),
3571 mAudioFlinger(audioFlinger),
3572 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3573 mPid(pid)
3574{
3575 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3576}
3577
3578// Client destructor must be called with AudioFlinger::mLock held
3579AudioFlinger::Client::~Client()
3580{
3581 mAudioFlinger->removeClient_l(mPid);
3582}
3583
3584const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3585{
3586 return mMemoryDealer;
3587}
3588
3589// ----------------------------------------------------------------------------
3590
3591AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3592 const sp<IAudioFlingerClient>& client,
3593 pid_t pid)
3594 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3595{
3596}
3597
3598AudioFlinger::NotificationClient::~NotificationClient()
3599{
3600 mClient.clear();
3601}
3602
3603void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3604{
3605 sp<NotificationClient> keep(this);
3606 {
3607 mAudioFlinger->removeNotificationClient(mPid);
3608 }
3609}
3610
3611// ----------------------------------------------------------------------------
3612
3613AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3614 : BnAudioTrack(),
3615 mTrack(track)
3616{
3617}
3618
3619AudioFlinger::TrackHandle::~TrackHandle() {
3620 // just stop the track on deletion, associated resources
3621 // will be freed from the main thread once all pending buffers have
3622 // been played. Unless it's not in the active track list, in which
3623 // case we free everything now...
3624 mTrack->destroy();
3625}
3626
3627status_t AudioFlinger::TrackHandle::start() {
3628 return mTrack->start();
3629}
3630
3631void AudioFlinger::TrackHandle::stop() {
3632 mTrack->stop();
3633}
3634
3635void AudioFlinger::TrackHandle::flush() {
3636 mTrack->flush();
3637}
3638
3639void AudioFlinger::TrackHandle::mute(bool e) {
3640 mTrack->mute(e);
3641}
3642
3643void AudioFlinger::TrackHandle::pause() {
3644 mTrack->pause();
3645}
3646
3647void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3648 mTrack->setVolume(left, right);
3649}
3650
3651sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3652 return mTrack->getCblk();
3653}
3654
3655status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3656{
3657 return mTrack->attachAuxEffect(EffectId);
3658}
3659
3660status_t AudioFlinger::TrackHandle::onTransact(
3661 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3662{
3663 return BnAudioTrack::onTransact(code, data, reply, flags);
3664}
3665
3666// ----------------------------------------------------------------------------
3667
3668sp<IAudioRecord> AudioFlinger::openRecord(
3669 pid_t pid,
3670 int input,
3671 uint32_t sampleRate,
3672 int format,
3673 int channelCount,
3674 int frameCount,
3675 uint32_t flags,
3676 int *sessionId,
3677 status_t *status)
3678{
3679 sp<RecordThread::RecordTrack> recordTrack;
3680 sp<RecordHandle> recordHandle;
3681 sp<Client> client;
3682 wp<Client> wclient;
3683 status_t lStatus;
3684 RecordThread *thread;
3685 size_t inFrameCount;
3686 int lSessionId;
3687
3688 // check calling permissions
3689 if (!recordingAllowed()) {
3690 lStatus = PERMISSION_DENIED;
3691 goto Exit;
3692 }
3693
3694 // add client to list
3695 { // scope for mLock
3696 Mutex::Autolock _l(mLock);
3697 thread = checkRecordThread_l(input);
3698 if (thread == NULL) {
3699 lStatus = BAD_VALUE;
3700 goto Exit;
3701 }
3702
3703 wclient = mClients.valueFor(pid);
3704 if (wclient != NULL) {
3705 client = wclient.promote();
3706 } else {
3707 client = new Client(this, pid);
3708 mClients.add(pid, client);
3709 }
3710
3711 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07003712 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003713 lSessionId = *sessionId;
3714 } else {
Eric Laurentf5aafb22010-11-18 08:40:16 -08003715 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716 if (sessionId != NULL) {
3717 *sessionId = lSessionId;
3718 }
3719 }
3720 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
3721 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
3722 format, channelCount, frameCount, flags, lSessionId);
3723 }
3724 if (recordTrack->getCblk() == NULL) {
3725 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3726 // destructor is called by the TrackBase destructor with mLock held
3727 client.clear();
3728 recordTrack.clear();
3729 lStatus = NO_MEMORY;
3730 goto Exit;
3731 }
3732
3733 // return to handle to client
3734 recordHandle = new RecordHandle(recordTrack);
3735 lStatus = NO_ERROR;
3736
3737Exit:
3738 if (status) {
3739 *status = lStatus;
3740 }
3741 return recordHandle;
3742}
3743
3744// ----------------------------------------------------------------------------
3745
3746AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3747 : BnAudioRecord(),
3748 mRecordTrack(recordTrack)
3749{
3750}
3751
3752AudioFlinger::RecordHandle::~RecordHandle() {
3753 stop();
3754}
3755
3756status_t AudioFlinger::RecordHandle::start() {
3757 LOGV("RecordHandle::start()");
3758 return mRecordTrack->start();
3759}
3760
3761void AudioFlinger::RecordHandle::stop() {
3762 LOGV("RecordHandle::stop()");
3763 mRecordTrack->stop();
3764}
3765
3766sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3767 return mRecordTrack->getCblk();
3768}
3769
3770status_t AudioFlinger::RecordHandle::onTransact(
3771 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3772{
3773 return BnAudioRecord::onTransact(code, data, reply, flags);
3774}
3775
3776// ----------------------------------------------------------------------------
3777
Dima Zavin799a70e2011-04-18 16:57:27 -07003778AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
Mathias Agopian65ab4712010-07-14 17:59:35 -07003779 ThreadBase(audioFlinger, id),
3780 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
3781{
Dima Zavinfce7a472011-04-19 22:30:36 -07003782 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003783 mReqSampleRate = sampleRate;
3784 readInputParameters();
3785}
3786
3787
3788AudioFlinger::RecordThread::~RecordThread()
3789{
3790 delete[] mRsmpInBuffer;
3791 if (mResampler != 0) {
3792 delete mResampler;
3793 delete[] mRsmpOutBuffer;
3794 }
3795}
3796
3797void AudioFlinger::RecordThread::onFirstRef()
3798{
3799 const size_t SIZE = 256;
3800 char buffer[SIZE];
3801
3802 snprintf(buffer, SIZE, "Record Thread %p", this);
3803
3804 run(buffer, PRIORITY_URGENT_AUDIO);
3805}
3806
3807bool AudioFlinger::RecordThread::threadLoop()
3808{
3809 AudioBufferProvider::Buffer buffer;
3810 sp<RecordTrack> activeTrack;
3811
Eric Laurent44d98482010-09-30 16:12:31 -07003812 nsecs_t lastWarning = 0;
3813
Mathias Agopian65ab4712010-07-14 17:59:35 -07003814 // start recording
3815 while (!exitPending()) {
3816
3817 processConfigEvents();
3818
3819 { // scope for mLock
3820 Mutex::Autolock _l(mLock);
3821 checkForNewParameters_l();
3822 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3823 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003824 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825 mStandby = true;
3826 }
3827
3828 if (exitPending()) break;
3829
3830 LOGV("RecordThread: loop stopping");
3831 // go to sleep
3832 mWaitWorkCV.wait(mLock);
3833 LOGV("RecordThread: loop starting");
3834 continue;
3835 }
3836 if (mActiveTrack != 0) {
3837 if (mActiveTrack->mState == TrackBase::PAUSING) {
3838 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003839 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003840 mStandby = true;
3841 }
3842 mActiveTrack.clear();
3843 mStartStopCond.broadcast();
3844 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3845 if (mReqChannelCount != mActiveTrack->channelCount()) {
3846 mActiveTrack.clear();
3847 mStartStopCond.broadcast();
3848 } else if (mBytesRead != 0) {
3849 // record start succeeds only if first read from audio input
3850 // succeeds
3851 if (mBytesRead > 0) {
3852 mActiveTrack->mState = TrackBase::ACTIVE;
3853 } else {
3854 mActiveTrack.clear();
3855 }
3856 mStartStopCond.broadcast();
3857 }
3858 mStandby = false;
3859 }
3860 }
3861 }
3862
3863 if (mActiveTrack != 0) {
3864 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3865 mActiveTrack->mState != TrackBase::RESUMING) {
3866 usleep(5000);
3867 continue;
3868 }
3869 buffer.frameCount = mFrameCount;
3870 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3871 size_t framesOut = buffer.frameCount;
3872 if (mResampler == 0) {
3873 // no resampling
3874 while (framesOut) {
3875 size_t framesIn = mFrameCount - mRsmpInIndex;
3876 if (framesIn) {
3877 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3878 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3879 if (framesIn > framesOut)
3880 framesIn = framesOut;
3881 mRsmpInIndex += framesIn;
3882 framesOut -= framesIn;
3883 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07003884 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 memcpy(dst, src, framesIn * mFrameSize);
3886 } else {
3887 int16_t *src16 = (int16_t *)src;
3888 int16_t *dst16 = (int16_t *)dst;
3889 if (mChannelCount == 1) {
3890 while (framesIn--) {
3891 *dst16++ = *src16;
3892 *dst16++ = *src16++;
3893 }
3894 } else {
3895 while (framesIn--) {
3896 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3897 src16 += 2;
3898 }
3899 }
3900 }
3901 }
3902 if (framesOut && mFrameCount == mRsmpInIndex) {
3903 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07003904 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003905 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 framesOut = 0;
3907 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07003908 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003909 mRsmpInIndex = 0;
3910 }
3911 if (mBytesRead < 0) {
3912 LOGE("Error reading audio input");
3913 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3914 // Force input into standby so that it tries to
3915 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07003916 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003917 usleep(5000);
3918 }
3919 mRsmpInIndex = mFrameCount;
3920 framesOut = 0;
3921 buffer.frameCount = 0;
3922 }
3923 }
3924 }
3925 } else {
3926 // resampling
3927
3928 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3929 // alter output frame count as if we were expecting stereo samples
3930 if (mChannelCount == 1 && mReqChannelCount == 1) {
3931 framesOut >>= 1;
3932 }
3933 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3934 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3935 // are 32 bit aligned which should be always true.
3936 if (mChannelCount == 2 && mReqChannelCount == 1) {
3937 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3938 // the resampler always outputs stereo samples: do post stereo to mono conversion
3939 int16_t *src = (int16_t *)mRsmpOutBuffer;
3940 int16_t *dst = buffer.i16;
3941 while (framesOut--) {
3942 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3943 src += 2;
3944 }
3945 } else {
3946 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3947 }
3948
3949 }
3950 mActiveTrack->releaseBuffer(&buffer);
3951 mActiveTrack->overflow();
3952 }
3953 // client isn't retrieving buffers fast enough
3954 else {
Eric Laurent44d98482010-09-30 16:12:31 -07003955 if (!mActiveTrack->setOverflow()) {
3956 nsecs_t now = systemTime();
3957 if ((now - lastWarning) > kWarningThrottle) {
3958 LOGW("RecordThread: buffer overflow");
3959 lastWarning = now;
3960 }
3961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 // Release the processor for a while before asking for a new buffer.
3963 // This will give the application more chance to read from the buffer and
3964 // clear the overflow.
3965 usleep(5000);
3966 }
3967 }
3968 }
3969
3970 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003971 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003972 }
3973 mActiveTrack.clear();
3974
3975 mStartStopCond.broadcast();
3976
3977 LOGV("RecordThread %p exiting", this);
3978 return false;
3979}
3980
3981status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
3982{
3983 LOGV("RecordThread::start");
3984 sp <ThreadBase> strongMe = this;
3985 status_t status = NO_ERROR;
3986 {
3987 AutoMutex lock(&mLock);
3988 if (mActiveTrack != 0) {
3989 if (recordTrack != mActiveTrack.get()) {
3990 status = -EBUSY;
3991 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
3992 mActiveTrack->mState = TrackBase::ACTIVE;
3993 }
3994 return status;
3995 }
3996
3997 recordTrack->mState = TrackBase::IDLE;
3998 mActiveTrack = recordTrack;
3999 mLock.unlock();
4000 status_t status = AudioSystem::startInput(mId);
4001 mLock.lock();
4002 if (status != NO_ERROR) {
4003 mActiveTrack.clear();
4004 return status;
4005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 mRsmpInIndex = mFrameCount;
4007 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004008 if (mResampler != NULL) {
4009 mResampler->reset();
4010 }
4011 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004012 // signal thread to start
4013 LOGV("Signal record thread");
4014 mWaitWorkCV.signal();
4015 // do not wait for mStartStopCond if exiting
4016 if (mExiting) {
4017 mActiveTrack.clear();
4018 status = INVALID_OPERATION;
4019 goto startError;
4020 }
4021 mStartStopCond.wait(mLock);
4022 if (mActiveTrack == 0) {
4023 LOGV("Record failed to start");
4024 status = BAD_VALUE;
4025 goto startError;
4026 }
4027 LOGV("Record started OK");
4028 return status;
4029 }
4030startError:
4031 AudioSystem::stopInput(mId);
4032 return status;
4033}
4034
4035void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4036 LOGV("RecordThread::stop");
4037 sp <ThreadBase> strongMe = this;
4038 {
4039 AutoMutex lock(&mLock);
4040 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4041 mActiveTrack->mState = TrackBase::PAUSING;
4042 // do not wait for mStartStopCond if exiting
4043 if (mExiting) {
4044 return;
4045 }
4046 mStartStopCond.wait(mLock);
4047 // if we have been restarted, recordTrack == mActiveTrack.get() here
4048 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4049 mLock.unlock();
4050 AudioSystem::stopInput(mId);
4051 mLock.lock();
4052 LOGV("Record stopped OK");
4053 }
4054 }
4055 }
4056}
4057
4058status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4059{
4060 const size_t SIZE = 256;
4061 char buffer[SIZE];
4062 String8 result;
4063 pid_t pid = 0;
4064
4065 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4066 result.append(buffer);
4067
4068 if (mActiveTrack != 0) {
4069 result.append("Active Track:\n");
4070 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
4071 mActiveTrack->dump(buffer, SIZE);
4072 result.append(buffer);
4073
4074 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4075 result.append(buffer);
4076 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4077 result.append(buffer);
4078 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4079 result.append(buffer);
4080 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4081 result.append(buffer);
4082 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4083 result.append(buffer);
4084
4085
4086 } else {
4087 result.append("No record client\n");
4088 }
4089 write(fd, result.string(), result.size());
4090
4091 dumpBase(fd, args);
4092
4093 return NO_ERROR;
4094}
4095
4096status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4097{
4098 size_t framesReq = buffer->frameCount;
4099 size_t framesReady = mFrameCount - mRsmpInIndex;
4100 int channelCount;
4101
4102 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004103 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004104 if (mBytesRead < 0) {
4105 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4106 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4107 // Force input into standby so that it tries to
4108 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004109 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 usleep(5000);
4111 }
4112 buffer->raw = 0;
4113 buffer->frameCount = 0;
4114 return NOT_ENOUGH_DATA;
4115 }
4116 mRsmpInIndex = 0;
4117 framesReady = mFrameCount;
4118 }
4119
4120 if (framesReq > framesReady) {
4121 framesReq = framesReady;
4122 }
4123
4124 if (mChannelCount == 1 && mReqChannelCount == 2) {
4125 channelCount = 1;
4126 } else {
4127 channelCount = 2;
4128 }
4129 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4130 buffer->frameCount = framesReq;
4131 return NO_ERROR;
4132}
4133
4134void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4135{
4136 mRsmpInIndex += buffer->frameCount;
4137 buffer->frameCount = 0;
4138}
4139
4140bool AudioFlinger::RecordThread::checkForNewParameters_l()
4141{
4142 bool reconfig = false;
4143
4144 while (!mNewParameters.isEmpty()) {
4145 status_t status = NO_ERROR;
4146 String8 keyValuePair = mNewParameters[0];
4147 AudioParameter param = AudioParameter(keyValuePair);
4148 int value;
4149 int reqFormat = mFormat;
4150 int reqSamplingRate = mReqSampleRate;
4151 int reqChannelCount = mReqChannelCount;
4152
4153 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4154 reqSamplingRate = value;
4155 reconfig = true;
4156 }
4157 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4158 reqFormat = value;
4159 reconfig = true;
4160 }
4161 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004162 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 reconfig = true;
4164 }
4165 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4166 // do not accept frame count changes if tracks are open as the track buffer
4167 // size depends on frame count and correct behavior would not be garantied
4168 // if frame count is changed after track creation
4169 if (mActiveTrack != 0) {
4170 status = INVALID_OPERATION;
4171 } else {
4172 reconfig = true;
4173 }
4174 }
4175 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004176 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004178 mInput->stream->common.standby(&mInput->stream->common);
4179 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 }
4181 if (reconfig) {
4182 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004183 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004184 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004185 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4186 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004187 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188 status = NO_ERROR;
4189 }
4190 if (status == NO_ERROR) {
4191 readInputParameters();
4192 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4193 }
4194 }
4195 }
4196
4197 mNewParameters.removeAt(0);
4198
4199 mParamStatus = status;
4200 mParamCond.signal();
4201 mWaitWorkCV.wait(mLock);
4202 }
4203 return reconfig;
4204}
4205
4206String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4207{
Dima Zavinfce7a472011-04-19 22:30:36 -07004208 char *s;
4209 String8 out_s8;
4210
Dima Zavin799a70e2011-04-18 16:57:27 -07004211 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004212 out_s8 = String8(s);
4213 free(s);
4214 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004215}
4216
4217void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4218 AudioSystem::OutputDescriptor desc;
4219 void *param2 = 0;
4220
4221 switch (event) {
4222 case AudioSystem::INPUT_OPENED:
4223 case AudioSystem::INPUT_CONFIG_CHANGED:
4224 desc.channels = mChannels;
4225 desc.samplingRate = mSampleRate;
4226 desc.format = mFormat;
4227 desc.frameCount = mFrameCount;
4228 desc.latency = 0;
4229 param2 = &desc;
4230 break;
4231
4232 case AudioSystem::INPUT_CLOSED:
4233 default:
4234 break;
4235 }
4236 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4237}
4238
4239void AudioFlinger::RecordThread::readInputParameters()
4240{
4241 if (mRsmpInBuffer) delete mRsmpInBuffer;
4242 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4243 if (mResampler) delete mResampler;
4244 mResampler = 0;
4245
Dima Zavin799a70e2011-04-18 16:57:27 -07004246 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
4247 mChannels = mInput->stream->common.get_channels(&mInput->stream->common);
Dima Zavinfce7a472011-04-19 22:30:36 -07004248 mChannelCount = (uint16_t)popcount(mChannels);
Dima Zavin799a70e2011-04-18 16:57:27 -07004249 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4250 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4251 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 mFrameCount = mInputBytes / mFrameSize;
4253 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4254
4255 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4256 {
4257 int channelCount;
4258 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4259 // stereo to mono post process as the resampler always outputs stereo.
4260 if (mChannelCount == 1 && mReqChannelCount == 2) {
4261 channelCount = 1;
4262 } else {
4263 channelCount = 2;
4264 }
4265 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4266 mResampler->setSampleRate(mSampleRate);
4267 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4268 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4269
4270 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4271 if (mChannelCount == 1 && mReqChannelCount == 1) {
4272 mFrameCount >>= 1;
4273 }
4274
4275 }
4276 mRsmpInIndex = mFrameCount;
4277}
4278
4279unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4280{
Dima Zavin799a70e2011-04-18 16:57:27 -07004281 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004282}
4283
4284// ----------------------------------------------------------------------------
4285
4286int AudioFlinger::openOutput(uint32_t *pDevices,
4287 uint32_t *pSamplingRate,
4288 uint32_t *pFormat,
4289 uint32_t *pChannels,
4290 uint32_t *pLatencyMs,
4291 uint32_t flags)
4292{
4293 status_t status;
4294 PlaybackThread *thread = NULL;
4295 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4296 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4297 uint32_t format = pFormat ? *pFormat : 0;
4298 uint32_t channels = pChannels ? *pChannels : 0;
4299 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004300 audio_stream_out_t *outStream;
4301 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004302
4303 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4304 pDevices ? *pDevices : 0,
4305 samplingRate,
4306 format,
4307 channels,
4308 flags);
4309
4310 if (pDevices == NULL || *pDevices == 0) {
4311 return 0;
4312 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004313
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314 Mutex::Autolock _l(mLock);
4315
Dima Zavin799a70e2011-04-18 16:57:27 -07004316 outHwDev = findSuitableHwDev_l(*pDevices);
4317 if (outHwDev == NULL)
4318 return 0;
4319
4320 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4321 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004323 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004324 samplingRate,
4325 format,
4326 channels,
4327 status);
4328
4329 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004330 if (outStream != NULL) {
4331 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurentf5aafb22010-11-18 08:40:16 -08004332 int id = nextUniqueId_l();
Dima Zavin799a70e2011-04-18 16:57:27 -07004333
Dima Zavinfce7a472011-04-19 22:30:36 -07004334 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4335 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4336 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337 thread = new DirectOutputThread(this, output, id, *pDevices);
4338 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4339 } else {
4340 thread = new MixerThread(this, output, id, *pDevices);
4341 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 }
4343 mPlaybackThreads.add(id, thread);
4344
4345 if (pSamplingRate) *pSamplingRate = samplingRate;
4346 if (pFormat) *pFormat = format;
4347 if (pChannels) *pChannels = channels;
4348 if (pLatencyMs) *pLatencyMs = thread->latency();
4349
4350 // notify client processes of the new output creation
4351 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4352 return id;
4353 }
4354
4355 return 0;
4356}
4357
4358int AudioFlinger::openDuplicateOutput(int output1, int output2)
4359{
4360 Mutex::Autolock _l(mLock);
4361 MixerThread *thread1 = checkMixerThread_l(output1);
4362 MixerThread *thread2 = checkMixerThread_l(output2);
4363
4364 if (thread1 == NULL || thread2 == NULL) {
4365 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4366 return 0;
4367 }
4368
Eric Laurentf5aafb22010-11-18 08:40:16 -08004369 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4371 thread->addOutputTrack(thread2);
4372 mPlaybackThreads.add(id, thread);
4373 // notify client processes of the new output creation
4374 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4375 return id;
4376}
4377
4378status_t AudioFlinger::closeOutput(int output)
4379{
4380 // keep strong reference on the playback thread so that
4381 // it is not destroyed while exit() is executed
4382 sp <PlaybackThread> thread;
4383 {
4384 Mutex::Autolock _l(mLock);
4385 thread = checkPlaybackThread_l(output);
4386 if (thread == NULL) {
4387 return BAD_VALUE;
4388 }
4389
4390 LOGV("closeOutput() %d", output);
4391
4392 if (thread->type() == PlaybackThread::MIXER) {
4393 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4394 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4395 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4396 dupThread->removeOutputTrack((MixerThread *)thread.get());
4397 }
4398 }
4399 }
4400 void *param2 = 0;
4401 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4402 mPlaybackThreads.removeItem(output);
4403 }
4404 thread->exit();
4405
4406 if (thread->type() != PlaybackThread::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004407 AudioStreamOut *out = thread->getOutput();
4408 out->hwDev->close_output_stream(out->hwDev, out->stream);
4409 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004410 }
4411 return NO_ERROR;
4412}
4413
4414status_t AudioFlinger::suspendOutput(int output)
4415{
4416 Mutex::Autolock _l(mLock);
4417 PlaybackThread *thread = checkPlaybackThread_l(output);
4418
4419 if (thread == NULL) {
4420 return BAD_VALUE;
4421 }
4422
4423 LOGV("suspendOutput() %d", output);
4424 thread->suspend();
4425
4426 return NO_ERROR;
4427}
4428
4429status_t AudioFlinger::restoreOutput(int output)
4430{
4431 Mutex::Autolock _l(mLock);
4432 PlaybackThread *thread = checkPlaybackThread_l(output);
4433
4434 if (thread == NULL) {
4435 return BAD_VALUE;
4436 }
4437
4438 LOGV("restoreOutput() %d", output);
4439
4440 thread->restore();
4441
4442 return NO_ERROR;
4443}
4444
4445int AudioFlinger::openInput(uint32_t *pDevices,
4446 uint32_t *pSamplingRate,
4447 uint32_t *pFormat,
4448 uint32_t *pChannels,
4449 uint32_t acoustics)
4450{
4451 status_t status;
4452 RecordThread *thread = NULL;
4453 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4454 uint32_t format = pFormat ? *pFormat : 0;
4455 uint32_t channels = pChannels ? *pChannels : 0;
4456 uint32_t reqSamplingRate = samplingRate;
4457 uint32_t reqFormat = format;
4458 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004459 audio_stream_in_t *inStream;
4460 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461
4462 if (pDevices == NULL || *pDevices == 0) {
4463 return 0;
4464 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004465
Mathias Agopian65ab4712010-07-14 17:59:35 -07004466 Mutex::Autolock _l(mLock);
4467
Dima Zavin799a70e2011-04-18 16:57:27 -07004468 inHwDev = findSuitableHwDev_l(*pDevices);
4469 if (inHwDev == NULL)
4470 return 0;
4471
4472 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4473 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004474 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004475 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004476 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004477 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478 samplingRate,
4479 format,
4480 channels,
4481 acoustics,
4482 status);
4483
4484 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4485 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4486 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004487 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004488 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004490 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004492 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4493 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004494 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004495 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004496 }
4497
Dima Zavin799a70e2011-04-18 16:57:27 -07004498 if (inStream != NULL) {
4499 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4500
Eric Laurentf5aafb22010-11-18 08:40:16 -08004501 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004502 // Start record thread
4503 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4504 mRecordThreads.add(id, thread);
4505 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4506 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4507 if (pFormat) *pFormat = format;
4508 if (pChannels) *pChannels = reqChannels;
4509
Dima Zavin799a70e2011-04-18 16:57:27 -07004510 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004511
4512 // notify client processes of the new input creation
4513 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4514 return id;
4515 }
4516
4517 return 0;
4518}
4519
4520status_t AudioFlinger::closeInput(int input)
4521{
4522 // keep strong reference on the record thread so that
4523 // it is not destroyed while exit() is executed
4524 sp <RecordThread> thread;
4525 {
4526 Mutex::Autolock _l(mLock);
4527 thread = checkRecordThread_l(input);
4528 if (thread == NULL) {
4529 return BAD_VALUE;
4530 }
4531
4532 LOGV("closeInput() %d", input);
4533 void *param2 = 0;
4534 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4535 mRecordThreads.removeItem(input);
4536 }
4537 thread->exit();
4538
Dima Zavin799a70e2011-04-18 16:57:27 -07004539 AudioStreamIn *in = thread->getInput();
4540 in->hwDev->close_input_stream(in->hwDev, in->stream);
4541 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542
4543 return NO_ERROR;
4544}
4545
4546status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4547{
4548 Mutex::Autolock _l(mLock);
4549 MixerThread *dstThread = checkMixerThread_l(output);
4550 if (dstThread == NULL) {
4551 LOGW("setStreamOutput() bad output id %d", output);
4552 return BAD_VALUE;
4553 }
4554
4555 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4556 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4557
4558 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4559 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4560 if (thread != dstThread &&
4561 thread->type() != PlaybackThread::DIRECT) {
4562 MixerThread *srcThread = (MixerThread *)thread;
4563 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004564 }
Eric Laurentde070132010-07-13 04:45:46 -07004565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004566
4567 return NO_ERROR;
4568}
4569
4570
4571int AudioFlinger::newAudioSessionId()
4572{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004573 AutoMutex _l(mLock);
4574 return nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004575}
4576
4577// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4578AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4579{
4580 PlaybackThread *thread = NULL;
4581 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4582 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4583 }
4584 return thread;
4585}
4586
4587// checkMixerThread_l() must be called with AudioFlinger::mLock held
4588AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4589{
4590 PlaybackThread *thread = checkPlaybackThread_l(output);
4591 if (thread != NULL) {
4592 if (thread->type() == PlaybackThread::DIRECT) {
4593 thread = NULL;
4594 }
4595 }
4596 return (MixerThread *)thread;
4597}
4598
4599// checkRecordThread_l() must be called with AudioFlinger::mLock held
4600AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4601{
4602 RecordThread *thread = NULL;
4603 if (mRecordThreads.indexOfKey(input) >= 0) {
4604 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4605 }
4606 return thread;
4607}
4608
Eric Laurentf5aafb22010-11-18 08:40:16 -08004609// nextUniqueId_l() must be called with AudioFlinger::mLock held
4610int AudioFlinger::nextUniqueId_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004612 return mNextUniqueId++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004613}
4614
4615// ----------------------------------------------------------------------------
4616// Effect management
4617// ----------------------------------------------------------------------------
4618
4619
4620status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4621{
Eric Laurentde070132010-07-13 04:45:46 -07004622 // check calling permissions
4623 if (!settingsAllowed()) {
4624 return PERMISSION_DENIED;
4625 }
4626 // only allow libraries loaded from /system/lib/soundfx for now
4627 if (strncmp(gEffectLibPath, libPath, strlen(gEffectLibPath)) != 0) {
4628 return PERMISSION_DENIED;
4629 }
4630
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 Mutex::Autolock _l(mLock);
4632 return EffectLoadLibrary(libPath, handle);
4633}
4634
4635status_t AudioFlinger::unloadEffectLibrary(int handle)
4636{
Eric Laurentde070132010-07-13 04:45:46 -07004637 // check calling permissions
4638 if (!settingsAllowed()) {
4639 return PERMISSION_DENIED;
4640 }
4641
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642 Mutex::Autolock _l(mLock);
4643 return EffectUnloadLibrary(handle);
4644}
4645
4646status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4647{
4648 Mutex::Autolock _l(mLock);
4649 return EffectQueryNumberEffects(numEffects);
4650}
4651
4652status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4653{
4654 Mutex::Autolock _l(mLock);
4655 return EffectQueryEffect(index, descriptor);
4656}
4657
4658status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4659{
4660 Mutex::Autolock _l(mLock);
4661 return EffectGetDescriptor(pUuid, descriptor);
4662}
4663
4664
4665// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4666static const effect_uuid_t VISUALIZATION_UUID_ =
4667 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4668
4669sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4670 effect_descriptor_t *pDesc,
4671 const sp<IEffectClient>& effectClient,
4672 int32_t priority,
4673 int output,
4674 int sessionId,
4675 status_t *status,
4676 int *id,
4677 int *enabled)
4678{
4679 status_t lStatus = NO_ERROR;
4680 sp<EffectHandle> handle;
4681 effect_interface_t itfe;
4682 effect_descriptor_t desc;
4683 sp<Client> client;
4684 wp<Client> wclient;
4685
Eric Laurentde070132010-07-13 04:45:46 -07004686 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4687 pid, effectClient.get(), priority, sessionId, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004688
4689 if (pDesc == NULL) {
4690 lStatus = BAD_VALUE;
4691 goto Exit;
4692 }
4693
Eric Laurent84e9a102010-09-23 16:10:16 -07004694 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07004695 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004696 lStatus = PERMISSION_DENIED;
4697 goto Exit;
4698 }
4699
Dima Zavinfce7a472011-04-19 22:30:36 -07004700 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07004701 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07004702 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004703 lStatus = PERMISSION_DENIED;
4704 goto Exit;
4705 }
4706
4707 // check recording permission for visualizer
4708 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4709 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4710 !recordingAllowed()) {
4711 lStatus = PERMISSION_DENIED;
4712 goto Exit;
4713 }
4714
4715 if (output == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004716 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004717 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07004718 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07004719 lStatus = BAD_VALUE;
4720 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07004721 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004722 // if the output returned by getOutputForEffect() is removed before we lock the
4723 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4724 // and we will exit safely
4725 output = AudioSystem::getOutputForEffect(&desc);
4726 }
4727 }
4728
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729 {
4730 Mutex::Autolock _l(mLock);
4731
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732
4733 if (!EffectIsNullUuid(&pDesc->uuid)) {
4734 // if uuid is specified, request effect descriptor
4735 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4736 if (lStatus < 0) {
4737 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4738 goto Exit;
4739 }
4740 } else {
4741 // if uuid is not specified, look for an available implementation
4742 // of the required type in effect factory
4743 if (EffectIsNullUuid(&pDesc->type)) {
4744 LOGW("createEffect() no effect type");
4745 lStatus = BAD_VALUE;
4746 goto Exit;
4747 }
4748 uint32_t numEffects = 0;
4749 effect_descriptor_t d;
4750 bool found = false;
4751
4752 lStatus = EffectQueryNumberEffects(&numEffects);
4753 if (lStatus < 0) {
4754 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4755 goto Exit;
4756 }
4757 for (uint32_t i = 0; i < numEffects; i++) {
4758 lStatus = EffectQueryEffect(i, &desc);
4759 if (lStatus < 0) {
4760 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4761 continue;
4762 }
4763 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4764 // If matching type found save effect descriptor. If the session is
4765 // 0 and the effect is not auxiliary, continue enumeration in case
4766 // an auxiliary version of this effect type is available
4767 found = true;
4768 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07004769 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004770 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4771 break;
4772 }
4773 }
4774 }
4775 if (!found) {
4776 lStatus = BAD_VALUE;
4777 LOGW("createEffect() effect not found");
4778 goto Exit;
4779 }
4780 // For same effect type, chose auxiliary version over insert version if
4781 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07004782 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4784 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4785 }
4786 }
4787
4788 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004789 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004790 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4791 lStatus = INVALID_OPERATION;
4792 goto Exit;
4793 }
4794
Mathias Agopian65ab4712010-07-14 17:59:35 -07004795 // return effect descriptor
4796 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4797
4798 // If output is not specified try to find a matching audio session ID in one of the
4799 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004800 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4801 // because of code checking output when entering the function.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004802 if (output == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004803 // look for the thread where the specified audio session is present
4804 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4805 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4806 output = mPlaybackThreads.keyAt(i);
4807 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004809 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004810 // If no output thread contains the requested session ID, default to
4811 // first output. The effect chain will be moved to the correct output
4812 // thread when a track with the same session ID is created
4813 if (output == 0 && mPlaybackThreads.size()) {
4814 output = mPlaybackThreads.keyAt(0);
4815 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004816 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004817 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004818 PlaybackThread *thread = checkPlaybackThread_l(output);
4819 if (thread == NULL) {
Eric Laurentde070132010-07-13 04:45:46 -07004820 LOGE("createEffect() unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 lStatus = BAD_VALUE;
4822 goto Exit;
4823 }
4824
Eric Laurent84e9a102010-09-23 16:10:16 -07004825 // TODO: allow attachment of effect to inputs
4826
Mathias Agopian65ab4712010-07-14 17:59:35 -07004827 wclient = mClients.valueFor(pid);
4828
4829 if (wclient != NULL) {
4830 client = wclient.promote();
4831 } else {
4832 client = new Client(this, pid);
4833 mClients.add(pid, client);
4834 }
4835
4836 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07004837 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4838 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004839 if (handle != 0 && id != NULL) {
4840 *id = handle->id();
4841 }
4842 }
4843
4844Exit:
4845 if(status) {
4846 *status = lStatus;
4847 }
4848 return handle;
4849}
4850
Eric Laurentde070132010-07-13 04:45:46 -07004851status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4852{
4853 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4854 session, srcOutput, dstOutput);
4855 Mutex::Autolock _l(mLock);
4856 if (srcOutput == dstOutput) {
4857 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4858 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004859 }
Eric Laurentde070132010-07-13 04:45:46 -07004860 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4861 if (srcThread == NULL) {
4862 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4863 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864 }
Eric Laurentde070132010-07-13 04:45:46 -07004865 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4866 if (dstThread == NULL) {
4867 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4868 return BAD_VALUE;
4869 }
4870
4871 Mutex::Autolock _dl(dstThread->mLock);
4872 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07004873 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07004874
Mathias Agopian65ab4712010-07-14 17:59:35 -07004875 return NO_ERROR;
4876}
4877
Eric Laurentde070132010-07-13 04:45:46 -07004878// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4879status_t AudioFlinger::moveEffectChain_l(int session,
4880 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07004881 AudioFlinger::PlaybackThread *dstThread,
4882 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07004883{
4884 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4885 session, srcThread, dstThread);
4886
4887 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4888 if (chain == 0) {
4889 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4890 session, srcThread);
4891 return INVALID_OPERATION;
4892 }
4893
Eric Laurent39e94f82010-07-28 01:32:47 -07004894 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004895 // so that a new chain is created with correct parameters when first effect is added. This is
4896 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4897 // removed.
4898 srcThread->removeEffectChain_l(chain);
4899
4900 // transfer all effects one by one so that new effect chain is created on new thread with
4901 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004902 int dstOutput = dstThread->id();
4903 sp<EffectChain> dstChain;
4904 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07004905 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4906 while (effect != 0) {
4907 srcThread->removeEffect_l(effect);
4908 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07004909 // if the move request is not received from audio policy manager, the effect must be
4910 // re-registered with the new strategy and output
4911 if (dstChain == 0) {
4912 dstChain = effect->chain().promote();
4913 if (dstChain == 0) {
4914 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4915 srcThread->addEffect_l(effect);
4916 return NO_INIT;
4917 }
4918 strategy = dstChain->strategy();
4919 }
4920 if (reRegister) {
4921 AudioSystem::unregisterEffect(effect->id());
4922 AudioSystem::registerEffect(&effect->desc(),
4923 dstOutput,
4924 strategy,
4925 session,
4926 effect->id());
4927 }
Eric Laurentde070132010-07-13 04:45:46 -07004928 effect = chain->getEffectFromId_l(0);
4929 }
4930
4931 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004932}
4933
4934// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4935sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4936 const sp<AudioFlinger::Client>& client,
4937 const sp<IEffectClient>& effectClient,
4938 int32_t priority,
4939 int sessionId,
4940 effect_descriptor_t *desc,
4941 int *enabled,
4942 status_t *status
4943 )
4944{
4945 sp<EffectModule> effect;
4946 sp<EffectHandle> handle;
4947 status_t lStatus;
4948 sp<Track> track;
4949 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07004950 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004951 bool effectCreated = false;
4952 bool effectRegistered = false;
4953
4954 if (mOutput == 0) {
4955 LOGW("createEffect_l() Audio driver not initialized.");
4956 lStatus = NO_INIT;
4957 goto Exit;
4958 }
4959
4960 // Do not allow auxiliary effect on session other than 0
4961 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004962 sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -07004963 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4964 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004965 lStatus = BAD_VALUE;
4966 goto Exit;
4967 }
4968
4969 // Do not allow effects with session ID 0 on direct output or duplicating threads
4970 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07004971 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07004972 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4973 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004974 lStatus = BAD_VALUE;
4975 goto Exit;
4976 }
4977
4978 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4979
4980 { // scope for mLock
4981 Mutex::Autolock _l(mLock);
4982
4983 // check for existing effect chain with the requested audio session
4984 chain = getEffectChain_l(sessionId);
4985 if (chain == 0) {
4986 // create a new chain for this session
4987 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4988 chain = new EffectChain(this, sessionId);
4989 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07004990 chain->setStrategy(getStrategyForSession_l(sessionId));
4991 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004992 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07004993 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004994 }
4995
4996 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4997
4998 if (effect == 0) {
Eric Laurentf5aafb22010-11-18 08:40:16 -08004999 int id = mAudioFlinger->nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005000 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005001 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005002 if (lStatus != NO_ERROR) {
5003 goto Exit;
5004 }
5005 effectRegistered = true;
5006 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005007 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 lStatus = effect->status();
5009 if (lStatus != NO_ERROR) {
5010 goto Exit;
5011 }
Eric Laurentcab11242010-07-15 12:50:15 -07005012 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005013 if (lStatus != NO_ERROR) {
5014 goto Exit;
5015 }
5016 effectCreated = true;
5017
5018 effect->setDevice(mDevice);
5019 effect->setMode(mAudioFlinger->getMode());
5020 }
5021 // create effect handle and connect it to effect module
5022 handle = new EffectHandle(effect, client, effectClient, priority);
5023 lStatus = effect->addHandle(handle);
5024 if (enabled) {
5025 *enabled = (int)effect->isEnabled();
5026 }
5027 }
5028
5029Exit:
5030 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005031 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005032 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005033 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005034 }
5035 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005036 AudioSystem::unregisterEffect(effect->id());
5037 }
5038 if (chainCreated) {
5039 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005040 }
5041 handle.clear();
5042 }
5043
5044 if(status) {
5045 *status = lStatus;
5046 }
5047 return handle;
5048}
5049
Eric Laurentde070132010-07-13 04:45:46 -07005050// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5051// PlaybackThread::mLock held
5052status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5053{
5054 // check for existing effect chain with the requested audio session
5055 int sessionId = effect->sessionId();
5056 sp<EffectChain> chain = getEffectChain_l(sessionId);
5057 bool chainCreated = false;
5058
5059 if (chain == 0) {
5060 // create a new chain for this session
5061 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5062 chain = new EffectChain(this, sessionId);
5063 addEffectChain_l(chain);
5064 chain->setStrategy(getStrategyForSession_l(sessionId));
5065 chainCreated = true;
5066 }
5067 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5068
5069 if (chain->getEffectFromId_l(effect->id()) != 0) {
5070 LOGW("addEffect_l() %p effect %s already present in chain %p",
5071 this, effect->desc().name, chain.get());
5072 return BAD_VALUE;
5073 }
5074
5075 status_t status = chain->addEffect_l(effect);
5076 if (status != NO_ERROR) {
5077 if (chainCreated) {
5078 removeEffectChain_l(chain);
5079 }
5080 return status;
5081 }
5082
5083 effect->setDevice(mDevice);
5084 effect->setMode(mAudioFlinger->getMode());
5085 return NO_ERROR;
5086}
5087
5088void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5089
5090 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005092 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5093 detachAuxEffect_l(effect->id());
5094 }
5095
5096 sp<EffectChain> chain = effect->chain().promote();
5097 if (chain != 0) {
5098 // remove effect chain if removing last effect
5099 if (chain->removeEffect_l(effect) == 0) {
5100 removeEffectChain_l(chain);
5101 }
5102 } else {
5103 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5104 }
5105}
5106
5107void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5108 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005110 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 // delete the effect module if removing last handle on it
5112 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005113 removeEffect_l(effect);
5114 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005115 }
5116}
5117
5118status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5119{
5120 int session = chain->sessionId();
5121 int16_t *buffer = mMixBuffer;
5122 bool ownsBuffer = false;
5123
5124 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5125 if (session > 0) {
5126 // Only one effect chain can be present in direct output thread and it uses
5127 // the mix buffer as input
5128 if (mType != DIRECT) {
5129 size_t numSamples = mFrameCount * mChannelCount;
5130 buffer = new int16_t[numSamples];
5131 memset(buffer, 0, numSamples * sizeof(int16_t));
5132 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5133 ownsBuffer = true;
5134 }
5135
5136 // Attach all tracks with same session ID to this chain.
5137 for (size_t i = 0; i < mTracks.size(); ++i) {
5138 sp<Track> track = mTracks[i];
5139 if (session == track->sessionId()) {
5140 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5141 track->setMainBuffer(buffer);
5142 }
5143 }
5144
5145 // indicate all active tracks in the chain
5146 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5147 sp<Track> track = mActiveTracks[i].promote();
5148 if (track == 0) continue;
5149 if (session == track->sessionId()) {
5150 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
5151 chain->startTrack();
5152 }
5153 }
5154 }
5155
5156 chain->setInBuffer(buffer, ownsBuffer);
5157 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005158 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005159 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005160 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5161 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005163 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5164 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005165 // Effect chain for other sessions are inserted at beginning of effect
5166 // chains list to be processed before output mix effects. Relative order between other
5167 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 size_t size = mEffectChains.size();
5169 size_t i = 0;
5170 for (i = 0; i < size; i++) {
5171 if (mEffectChains[i]->sessionId() < session) break;
5172 }
5173 mEffectChains.insertAt(chain, i);
5174
5175 return NO_ERROR;
5176}
5177
5178size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5179{
5180 int session = chain->sessionId();
5181
5182 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5183
5184 for (size_t i = 0; i < mEffectChains.size(); i++) {
5185 if (chain == mEffectChains[i]) {
5186 mEffectChains.removeAt(i);
5187 // detach all tracks with same session ID from this chain
5188 for (size_t i = 0; i < mTracks.size(); ++i) {
5189 sp<Track> track = mTracks[i];
5190 if (session == track->sessionId()) {
5191 track->setMainBuffer(mMixBuffer);
5192 }
5193 }
Eric Laurentde070132010-07-13 04:45:46 -07005194 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005195 }
5196 }
5197 return mEffectChains.size();
5198}
5199
Eric Laurentde070132010-07-13 04:45:46 -07005200void AudioFlinger::PlaybackThread::lockEffectChains_l(
5201 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202{
Eric Laurentde070132010-07-13 04:45:46 -07005203 effectChains = mEffectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005204 for (size_t i = 0; i < mEffectChains.size(); i++) {
5205 mEffectChains[i]->lock();
5206 }
5207}
5208
Eric Laurentde070132010-07-13 04:45:46 -07005209void AudioFlinger::PlaybackThread::unlockEffectChains(
5210 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211{
Eric Laurentde070132010-07-13 04:45:46 -07005212 for (size_t i = 0; i < effectChains.size(); i++) {
5213 effectChains[i]->unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 }
5215}
5216
Eric Laurentde070132010-07-13 04:45:46 -07005217
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5219{
5220 sp<EffectModule> effect;
5221
5222 sp<EffectChain> chain = getEffectChain_l(sessionId);
5223 if (chain != 0) {
Eric Laurentcab11242010-07-15 12:50:15 -07005224 effect = chain->getEffectFromId_l(effectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 }
5226 return effect;
5227}
5228
Eric Laurentde070132010-07-13 04:45:46 -07005229status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5230 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005231{
5232 Mutex::Autolock _l(mLock);
5233 return attachAuxEffect_l(track, EffectId);
5234}
5235
Eric Laurentde070132010-07-13 04:45:46 -07005236status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5237 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005238{
5239 status_t status = NO_ERROR;
5240
5241 if (EffectId == 0) {
5242 track->setAuxBuffer(0, NULL);
5243 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005244 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5245 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005246 if (effect != 0) {
5247 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5248 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5249 } else {
5250 status = INVALID_OPERATION;
5251 }
5252 } else {
5253 status = BAD_VALUE;
5254 }
5255 }
5256 return status;
5257}
5258
5259void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5260{
5261 for (size_t i = 0; i < mTracks.size(); ++i) {
5262 sp<Track> track = mTracks[i];
5263 if (track->auxEffectId() == effectId) {
5264 attachAuxEffect_l(track, 0);
5265 }
5266 }
5267}
5268
5269// ----------------------------------------------------------------------------
5270// EffectModule implementation
5271// ----------------------------------------------------------------------------
5272
5273#undef LOG_TAG
5274#define LOG_TAG "AudioFlinger::EffectModule"
5275
5276AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5277 const wp<AudioFlinger::EffectChain>& chain,
5278 effect_descriptor_t *desc,
5279 int id,
5280 int sessionId)
5281 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5282 mStatus(NO_INIT), mState(IDLE)
5283{
5284 LOGV("Constructor %p", this);
5285 int lStatus;
5286 sp<ThreadBase> thread = mThread.promote();
5287 if (thread == 0) {
5288 return;
5289 }
5290 PlaybackThread *p = (PlaybackThread *)thread.get();
5291
5292 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5293
5294 // create effect engine from effect factory
5295 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5296
5297 if (mStatus != NO_ERROR) {
5298 return;
5299 }
5300 lStatus = init();
5301 if (lStatus < 0) {
5302 mStatus = lStatus;
5303 goto Error;
5304 }
5305
5306 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5307 return;
5308Error:
5309 EffectRelease(mEffectInterface);
5310 mEffectInterface = NULL;
5311 LOGV("Constructor Error %d", mStatus);
5312}
5313
5314AudioFlinger::EffectModule::~EffectModule()
5315{
5316 LOGV("Destructor %p", this);
5317 if (mEffectInterface != NULL) {
5318 // release effect engine
5319 EffectRelease(mEffectInterface);
5320 }
5321}
5322
5323status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5324{
5325 status_t status;
5326
5327 Mutex::Autolock _l(mLock);
5328 // First handle in mHandles has highest priority and controls the effect module
5329 int priority = handle->priority();
5330 size_t size = mHandles.size();
5331 sp<EffectHandle> h;
5332 size_t i;
5333 for (i = 0; i < size; i++) {
5334 h = mHandles[i].promote();
5335 if (h == 0) continue;
5336 if (h->priority() <= priority) break;
5337 }
5338 // if inserted in first place, move effect control from previous owner to this handle
5339 if (i == 0) {
5340 if (h != 0) {
5341 h->setControl(false, true);
5342 }
5343 handle->setControl(true, false);
5344 status = NO_ERROR;
5345 } else {
5346 status = ALREADY_EXISTS;
5347 }
5348 mHandles.insertAt(handle, i);
5349 return status;
5350}
5351
5352size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5353{
5354 Mutex::Autolock _l(mLock);
5355 size_t size = mHandles.size();
5356 size_t i;
5357 for (i = 0; i < size; i++) {
5358 if (mHandles[i] == handle) break;
5359 }
5360 if (i == size) {
5361 return size;
5362 }
5363 mHandles.removeAt(i);
5364 size = mHandles.size();
5365 // if removed from first place, move effect control from this handle to next in line
5366 if (i == 0 && size != 0) {
5367 sp<EffectHandle> h = mHandles[0].promote();
5368 if (h != 0) {
5369 h->setControl(true, true);
5370 }
5371 }
5372
Eric Laurentdac69112010-09-28 14:09:57 -07005373 // Release effect engine here so that it is done immediately. Otherwise it will be released
5374 // by the destructor when the last strong reference on the this object is released which can
5375 // happen after next process is called on this effect.
5376 if (size == 0 && mEffectInterface != NULL) {
5377 // release effect engine
5378 EffectRelease(mEffectInterface);
5379 mEffectInterface = NULL;
5380 }
5381
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382 return size;
5383}
5384
5385void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5386{
5387 // keep a strong reference on this EffectModule to avoid calling the
5388 // destructor before we exit
5389 sp<EffectModule> keep(this);
5390 {
5391 sp<ThreadBase> thread = mThread.promote();
5392 if (thread != 0) {
5393 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5394 playbackThread->disconnectEffect(keep, handle);
5395 }
5396 }
5397}
5398
5399void AudioFlinger::EffectModule::updateState() {
5400 Mutex::Autolock _l(mLock);
5401
5402 switch (mState) {
5403 case RESTART:
5404 reset_l();
5405 // FALL THROUGH
5406
5407 case STARTING:
5408 // clear auxiliary effect input buffer for next accumulation
5409 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5410 memset(mConfig.inputCfg.buffer.raw,
5411 0,
5412 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5413 }
5414 start_l();
5415 mState = ACTIVE;
5416 break;
5417 case STOPPING:
5418 stop_l();
5419 mDisableWaitCnt = mMaxDisableWaitCnt;
5420 mState = STOPPED;
5421 break;
5422 case STOPPED:
5423 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5424 // turn off sequence.
5425 if (--mDisableWaitCnt == 0) {
5426 reset_l();
5427 mState = IDLE;
5428 }
5429 break;
5430 default: //IDLE , ACTIVE
5431 break;
5432 }
5433}
5434
5435void AudioFlinger::EffectModule::process()
5436{
5437 Mutex::Autolock _l(mLock);
5438
5439 if (mEffectInterface == NULL ||
5440 mConfig.inputCfg.buffer.raw == NULL ||
5441 mConfig.outputCfg.buffer.raw == NULL) {
5442 return;
5443 }
5444
Eric Laurent8f45bd72010-08-31 13:50:07 -07005445 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005446 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5447 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5448 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5449 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005450 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 }
5452
5453 // do the actual processing in the effect engine
5454 int ret = (*mEffectInterface)->process(mEffectInterface,
5455 &mConfig.inputCfg.buffer,
5456 &mConfig.outputCfg.buffer);
5457
5458 // force transition to IDLE state when engine is ready
5459 if (mState == STOPPED && ret == -ENODATA) {
5460 mDisableWaitCnt = 1;
5461 }
5462
5463 // clear auxiliary effect input buffer for next accumulation
5464 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005465 memset(mConfig.inputCfg.buffer.raw, 0,
5466 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005467 }
5468 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005469 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5470 // If an insert effect is idle and input buffer is different from output buffer,
5471 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472 sp<EffectChain> chain = mChain.promote();
5473 if (chain != 0 && chain->activeTracks() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005474 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5475 int16_t *in = mConfig.inputCfg.buffer.s16;
5476 int16_t *out = mConfig.outputCfg.buffer.s16;
5477 for (size_t i = 0; i < frameCnt; i++) {
5478 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005479 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 }
5481 }
5482}
5483
5484void AudioFlinger::EffectModule::reset_l()
5485{
5486 if (mEffectInterface == NULL) {
5487 return;
5488 }
5489 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5490}
5491
5492status_t AudioFlinger::EffectModule::configure()
5493{
5494 uint32_t channels;
5495 if (mEffectInterface == NULL) {
5496 return NO_INIT;
5497 }
5498
5499 sp<ThreadBase> thread = mThread.promote();
5500 if (thread == 0) {
5501 return DEAD_OBJECT;
5502 }
5503
5504 // TODO: handle configuration of effects replacing track process
5505 if (thread->channelCount() == 1) {
5506 channels = CHANNEL_MONO;
5507 } else {
5508 channels = CHANNEL_STEREO;
5509 }
5510
5511 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5512 mConfig.inputCfg.channels = CHANNEL_MONO;
5513 } else {
5514 mConfig.inputCfg.channels = channels;
5515 }
5516 mConfig.outputCfg.channels = channels;
5517 mConfig.inputCfg.format = SAMPLE_FORMAT_PCM_S15;
5518 mConfig.outputCfg.format = SAMPLE_FORMAT_PCM_S15;
5519 mConfig.inputCfg.samplingRate = thread->sampleRate();
5520 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5521 mConfig.inputCfg.bufferProvider.cookie = NULL;
5522 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5523 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5524 mConfig.outputCfg.bufferProvider.cookie = NULL;
5525 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5526 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5527 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5528 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005529 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005530 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005531 // - in other sessions:
5532 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5533 // other effect: overwrites output buffer: input buffer == output buffer
5534 // Auxiliary effect:
5535 // accumulates in output buffer: input buffer != output buffer
5536 // Therefore: accumulate <=> input buffer != output buffer
5537 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5538 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5539 } else {
5540 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5541 }
5542 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5543 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5544 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5545 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5546
Eric Laurentde070132010-07-13 04:45:46 -07005547 LOGV("configure() %p thread %p buffer %p framecount %d",
5548 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5549
Mathias Agopian65ab4712010-07-14 17:59:35 -07005550 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005551 uint32_t size = sizeof(int);
5552 status_t status = (*mEffectInterface)->command(mEffectInterface,
5553 EFFECT_CMD_CONFIGURE,
5554 sizeof(effect_config_t),
5555 &mConfig,
5556 &size,
5557 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005558 if (status == 0) {
5559 status = cmdStatus;
5560 }
5561
5562 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5563 (1000 * mConfig.outputCfg.buffer.frameCount);
5564
5565 return status;
5566}
5567
5568status_t AudioFlinger::EffectModule::init()
5569{
5570 Mutex::Autolock _l(mLock);
5571 if (mEffectInterface == NULL) {
5572 return NO_INIT;
5573 }
5574 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005575 uint32_t size = sizeof(status_t);
5576 status_t status = (*mEffectInterface)->command(mEffectInterface,
5577 EFFECT_CMD_INIT,
5578 0,
5579 NULL,
5580 &size,
5581 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 if (status == 0) {
5583 status = cmdStatus;
5584 }
5585 return status;
5586}
5587
5588status_t AudioFlinger::EffectModule::start_l()
5589{
5590 if (mEffectInterface == NULL) {
5591 return NO_INIT;
5592 }
5593 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005594 uint32_t size = sizeof(status_t);
5595 status_t status = (*mEffectInterface)->command(mEffectInterface,
5596 EFFECT_CMD_ENABLE,
5597 0,
5598 NULL,
5599 &size,
5600 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 if (status == 0) {
5602 status = cmdStatus;
5603 }
5604 return status;
5605}
5606
5607status_t AudioFlinger::EffectModule::stop_l()
5608{
5609 if (mEffectInterface == NULL) {
5610 return NO_INIT;
5611 }
5612 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005613 uint32_t size = sizeof(status_t);
5614 status_t status = (*mEffectInterface)->command(mEffectInterface,
5615 EFFECT_CMD_DISABLE,
5616 0,
5617 NULL,
5618 &size,
5619 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620 if (status == 0) {
5621 status = cmdStatus;
5622 }
5623 return status;
5624}
5625
Eric Laurent25f43952010-07-28 05:40:18 -07005626status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5627 uint32_t cmdSize,
5628 void *pCmdData,
5629 uint32_t *replySize,
5630 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631{
5632 Mutex::Autolock _l(mLock);
5633// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5634
5635 if (mEffectInterface == NULL) {
5636 return NO_INIT;
5637 }
Eric Laurent25f43952010-07-28 05:40:18 -07005638 status_t status = (*mEffectInterface)->command(mEffectInterface,
5639 cmdCode,
5640 cmdSize,
5641 pCmdData,
5642 replySize,
5643 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005645 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 for (size_t i = 1; i < mHandles.size(); i++) {
5647 sp<EffectHandle> h = mHandles[i].promote();
5648 if (h != 0) {
5649 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5650 }
5651 }
5652 }
5653 return status;
5654}
5655
5656status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5657{
5658 Mutex::Autolock _l(mLock);
5659 LOGV("setEnabled %p enabled %d", this, enabled);
5660
5661 if (enabled != isEnabled()) {
5662 switch (mState) {
5663 // going from disabled to enabled
5664 case IDLE:
5665 mState = STARTING;
5666 break;
5667 case STOPPED:
5668 mState = RESTART;
5669 break;
5670 case STOPPING:
5671 mState = ACTIVE;
5672 break;
5673
5674 // going from enabled to disabled
5675 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005676 mState = STOPPED;
5677 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 case STARTING:
5679 mState = IDLE;
5680 break;
5681 case ACTIVE:
5682 mState = STOPPING;
5683 break;
5684 }
5685 for (size_t i = 1; i < mHandles.size(); i++) {
5686 sp<EffectHandle> h = mHandles[i].promote();
5687 if (h != 0) {
5688 h->setEnabled(enabled);
5689 }
5690 }
5691 }
5692 return NO_ERROR;
5693}
5694
5695bool AudioFlinger::EffectModule::isEnabled()
5696{
5697 switch (mState) {
5698 case RESTART:
5699 case STARTING:
5700 case ACTIVE:
5701 return true;
5702 case IDLE:
5703 case STOPPING:
5704 case STOPPED:
5705 default:
5706 return false;
5707 }
5708}
5709
Eric Laurent8f45bd72010-08-31 13:50:07 -07005710bool AudioFlinger::EffectModule::isProcessEnabled()
5711{
5712 switch (mState) {
5713 case RESTART:
5714 case ACTIVE:
5715 case STOPPING:
5716 case STOPPED:
5717 return true;
5718 case IDLE:
5719 case STARTING:
5720 default:
5721 return false;
5722 }
5723}
5724
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5726{
5727 Mutex::Autolock _l(mLock);
5728 status_t status = NO_ERROR;
5729
5730 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5731 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07005732 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07005733 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5734 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005735 status_t cmdStatus;
5736 uint32_t volume[2];
5737 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07005738 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 volume[0] = *left;
5740 volume[1] = *right;
5741 if (controller) {
5742 pVolume = volume;
5743 }
Eric Laurent25f43952010-07-28 05:40:18 -07005744 status = (*mEffectInterface)->command(mEffectInterface,
5745 EFFECT_CMD_SET_VOLUME,
5746 size,
5747 volume,
5748 &size,
5749 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5751 *left = volume[0];
5752 *right = volume[1];
5753 }
5754 }
5755 return status;
5756}
5757
5758status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5759{
5760 Mutex::Autolock _l(mLock);
5761 status_t status = NO_ERROR;
5762 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5763 // convert device bit field from AudioSystem to EffectApi format.
5764 device = deviceAudioSystemToEffectApi(device);
5765 if (device == 0) {
5766 return BAD_VALUE;
5767 }
5768 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005769 uint32_t size = sizeof(status_t);
5770 status = (*mEffectInterface)->command(mEffectInterface,
5771 EFFECT_CMD_SET_DEVICE,
5772 sizeof(uint32_t),
5773 &device,
5774 &size,
5775 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 if (status == NO_ERROR) {
5777 status = cmdStatus;
5778 }
5779 }
5780 return status;
5781}
5782
5783status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5784{
5785 Mutex::Autolock _l(mLock);
5786 status_t status = NO_ERROR;
5787 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
5788 // convert audio mode from AudioSystem to EffectApi format.
5789 int effectMode = modeAudioSystemToEffectApi(mode);
5790 if (effectMode < 0) {
5791 return BAD_VALUE;
5792 }
5793 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005794 uint32_t size = sizeof(status_t);
5795 status = (*mEffectInterface)->command(mEffectInterface,
5796 EFFECT_CMD_SET_AUDIO_MODE,
5797 sizeof(int),
5798 &effectMode,
5799 &size,
5800 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005801 if (status == NO_ERROR) {
5802 status = cmdStatus;
5803 }
5804 }
5805 return status;
5806}
5807
5808// update this table when AudioSystem::audio_devices or audio_device_e (in EffectApi.h) are modified
5809const uint32_t AudioFlinger::EffectModule::sDeviceConvTable[] = {
Dima Zavinfce7a472011-04-19 22:30:36 -07005810 DEVICE_EARPIECE, // AUDIO_DEVICE_OUT_EARPIECE
5811 DEVICE_SPEAKER, // AUDIO_DEVICE_OUT_SPEAKER
5812 DEVICE_WIRED_HEADSET, // case AUDIO_DEVICE_OUT_WIRED_HEADSET
5813 DEVICE_WIRED_HEADPHONE, // AUDIO_DEVICE_OUT_WIRED_HEADPHONE
5814 DEVICE_BLUETOOTH_SCO, // AUDIO_DEVICE_OUT_BLUETOOTH_SCO
5815 DEVICE_BLUETOOTH_SCO_HEADSET, // AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET
5816 DEVICE_BLUETOOTH_SCO_CARKIT, // AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT
5817 DEVICE_BLUETOOTH_A2DP, // AUDIO_DEVICE_OUT_BLUETOOTH_A2DP
5818 DEVICE_BLUETOOTH_A2DP_HEADPHONES, // AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES
5819 DEVICE_BLUETOOTH_A2DP_SPEAKER, // AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER
5820 DEVICE_AUX_DIGITAL // AUDIO_DEVICE_OUT_AUX_DIGITAL
Mathias Agopian65ab4712010-07-14 17:59:35 -07005821};
5822
5823uint32_t AudioFlinger::EffectModule::deviceAudioSystemToEffectApi(uint32_t device)
5824{
5825 uint32_t deviceOut = 0;
5826 while (device) {
5827 const uint32_t i = 31 - __builtin_clz(device);
5828 device &= ~(1 << i);
5829 if (i >= sizeof(sDeviceConvTable)/sizeof(uint32_t)) {
Glenn Kasten4bcae822011-04-04 10:50:50 -07005830 LOGE("device conversion error for AudioSystem device 0x%08x", device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831 return 0;
5832 }
5833 deviceOut |= (uint32_t)sDeviceConvTable[i];
5834 }
5835 return deviceOut;
5836}
5837
5838// update this table when AudioSystem::audio_mode or audio_mode_e (in EffectApi.h) are modified
5839const uint32_t AudioFlinger::EffectModule::sModeConvTable[] = {
Dima Zavinfce7a472011-04-19 22:30:36 -07005840 AUDIO_EFFECT_MODE_NORMAL, // AUDIO_MODE_NORMAL
5841 AUDIO_EFFECT_MODE_RINGTONE, // AUDIO_MODE_RINGTONE
5842 AUDIO_EFFECT_MODE_IN_CALL, // AUDIO_MODE_IN_CALL
5843 AUDIO_EFFECT_MODE_IN_CALL // AUDIO_MODE_IN_COMMUNICATION, same conversion as for AUDIO_MODE_IN_CALL
Mathias Agopian65ab4712010-07-14 17:59:35 -07005844};
5845
5846int AudioFlinger::EffectModule::modeAudioSystemToEffectApi(uint32_t mode)
5847{
5848 int modeOut = -1;
5849 if (mode < sizeof(sModeConvTable) / sizeof(uint32_t)) {
5850 modeOut = (int)sModeConvTable[mode];
5851 }
5852 return modeOut;
5853}
5854
5855status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5856{
5857 const size_t SIZE = 256;
5858 char buffer[SIZE];
5859 String8 result;
5860
5861 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5862 result.append(buffer);
5863
5864 bool locked = tryLock(mLock);
5865 // failed to lock - AudioFlinger is probably deadlocked
5866 if (!locked) {
5867 result.append("\t\tCould not lock Fx mutex:\n");
5868 }
5869
5870 result.append("\t\tSession Status State Engine:\n");
5871 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5872 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5873 result.append(buffer);
5874
5875 result.append("\t\tDescriptor:\n");
5876 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5877 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5878 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5879 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5880 result.append(buffer);
5881 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5882 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5883 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5884 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5885 result.append(buffer);
5886 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5887 mDescriptor.apiVersion,
5888 mDescriptor.flags);
5889 result.append(buffer);
5890 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5891 mDescriptor.name);
5892 result.append(buffer);
5893 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5894 mDescriptor.implementor);
5895 result.append(buffer);
5896
5897 result.append("\t\t- Input configuration:\n");
5898 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5899 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5900 (uint32_t)mConfig.inputCfg.buffer.raw,
5901 mConfig.inputCfg.buffer.frameCount,
5902 mConfig.inputCfg.samplingRate,
5903 mConfig.inputCfg.channels,
5904 mConfig.inputCfg.format);
5905 result.append(buffer);
5906
5907 result.append("\t\t- Output configuration:\n");
5908 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5909 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5910 (uint32_t)mConfig.outputCfg.buffer.raw,
5911 mConfig.outputCfg.buffer.frameCount,
5912 mConfig.outputCfg.samplingRate,
5913 mConfig.outputCfg.channels,
5914 mConfig.outputCfg.format);
5915 result.append(buffer);
5916
5917 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5918 result.append(buffer);
5919 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5920 for (size_t i = 0; i < mHandles.size(); ++i) {
5921 sp<EffectHandle> handle = mHandles[i].promote();
5922 if (handle != 0) {
5923 handle->dump(buffer, SIZE);
5924 result.append(buffer);
5925 }
5926 }
5927
5928 result.append("\n");
5929
5930 write(fd, result.string(), result.length());
5931
5932 if (locked) {
5933 mLock.unlock();
5934 }
5935
5936 return NO_ERROR;
5937}
5938
5939// ----------------------------------------------------------------------------
5940// EffectHandle implementation
5941// ----------------------------------------------------------------------------
5942
5943#undef LOG_TAG
5944#define LOG_TAG "AudioFlinger::EffectHandle"
5945
5946AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5947 const sp<AudioFlinger::Client>& client,
5948 const sp<IEffectClient>& effectClient,
5949 int32_t priority)
5950 : BnEffect(),
5951 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5952{
5953 LOGV("constructor %p", this);
5954
5955 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5956 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5957 if (mCblkMemory != 0) {
5958 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5959
5960 if (mCblk) {
5961 new(mCblk) effect_param_cblk_t();
5962 mBuffer = (uint8_t *)mCblk + bufOffset;
5963 }
5964 } else {
5965 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5966 return;
5967 }
5968}
5969
5970AudioFlinger::EffectHandle::~EffectHandle()
5971{
5972 LOGV("Destructor %p", this);
5973 disconnect();
5974}
5975
5976status_t AudioFlinger::EffectHandle::enable()
5977{
5978 if (!mHasControl) return INVALID_OPERATION;
5979 if (mEffect == 0) return DEAD_OBJECT;
5980
5981 return mEffect->setEnabled(true);
5982}
5983
5984status_t AudioFlinger::EffectHandle::disable()
5985{
5986 if (!mHasControl) return INVALID_OPERATION;
5987 if (mEffect == NULL) return DEAD_OBJECT;
5988
5989 return mEffect->setEnabled(false);
5990}
5991
5992void AudioFlinger::EffectHandle::disconnect()
5993{
5994 if (mEffect == 0) {
5995 return;
5996 }
5997 mEffect->disconnect(this);
5998 // release sp on module => module destructor can be called now
5999 mEffect.clear();
6000 if (mCblk) {
6001 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6002 }
6003 mCblkMemory.clear(); // and free the shared memory
6004 if (mClient != 0) {
6005 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6006 mClient.clear();
6007 }
6008}
6009
Eric Laurent25f43952010-07-28 05:40:18 -07006010status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6011 uint32_t cmdSize,
6012 void *pCmdData,
6013 uint32_t *replySize,
6014 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006015{
Eric Laurent25f43952010-07-28 05:40:18 -07006016// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6017// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018
6019 // only get parameter command is permitted for applications not controlling the effect
6020 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6021 return INVALID_OPERATION;
6022 }
6023 if (mEffect == 0) return DEAD_OBJECT;
6024
6025 // handle commands that are not forwarded transparently to effect engine
6026 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6027 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6028 // no risk to block the whole media server process or mixer threads is we are stuck here
6029 Mutex::Autolock _l(mCblk->lock);
6030 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6031 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6032 mCblk->serverIndex = 0;
6033 mCblk->clientIndex = 0;
6034 return BAD_VALUE;
6035 }
6036 status_t status = NO_ERROR;
6037 while (mCblk->serverIndex < mCblk->clientIndex) {
6038 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006039 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006040 int *p = (int *)(mBuffer + mCblk->serverIndex);
6041 int size = *p++;
6042 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6043 LOGW("command(): invalid parameter block size");
6044 break;
6045 }
6046 effect_param_t *param = (effect_param_t *)p;
6047 if (param->psize == 0 || param->vsize == 0) {
6048 LOGW("command(): null parameter or value size");
6049 mCblk->serverIndex += size;
6050 continue;
6051 }
Eric Laurent25f43952010-07-28 05:40:18 -07006052 uint32_t psize = sizeof(effect_param_t) +
6053 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6054 param->vsize;
6055 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6056 psize,
6057 p,
6058 &rsize,
6059 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006060 // stop at first error encountered
6061 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006062 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006063 *(int *)pReplyData = reply;
6064 break;
6065 } else if (reply != NO_ERROR) {
6066 *(int *)pReplyData = reply;
6067 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006068 }
6069 mCblk->serverIndex += size;
6070 }
6071 mCblk->serverIndex = 0;
6072 mCblk->clientIndex = 0;
6073 return status;
6074 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006075 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006076 return enable();
6077 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006078 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006079 return disable();
6080 }
6081
6082 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6083}
6084
6085sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6086 return mCblkMemory;
6087}
6088
6089void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6090{
6091 LOGV("setControl %p control %d", this, hasControl);
6092
6093 mHasControl = hasControl;
6094 if (signal && mEffectClient != 0) {
6095 mEffectClient->controlStatusChanged(hasControl);
6096 }
6097}
6098
Eric Laurent25f43952010-07-28 05:40:18 -07006099void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6100 uint32_t cmdSize,
6101 void *pCmdData,
6102 uint32_t replySize,
6103 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006104{
6105 if (mEffectClient != 0) {
6106 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6107 }
6108}
6109
6110
6111
6112void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6113{
6114 if (mEffectClient != 0) {
6115 mEffectClient->enableStatusChanged(enabled);
6116 }
6117}
6118
6119status_t AudioFlinger::EffectHandle::onTransact(
6120 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6121{
6122 return BnEffect::onTransact(code, data, reply, flags);
6123}
6124
6125
6126void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6127{
6128 bool locked = tryLock(mCblk->lock);
6129
6130 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6131 (mClient == NULL) ? getpid() : mClient->pid(),
6132 mPriority,
6133 mHasControl,
6134 !locked,
6135 mCblk->clientIndex,
6136 mCblk->serverIndex
6137 );
6138
6139 if (locked) {
6140 mCblk->lock.unlock();
6141 }
6142}
6143
6144#undef LOG_TAG
6145#define LOG_TAG "AudioFlinger::EffectChain"
6146
6147AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6148 int sessionId)
Eric Laurentcab11242010-07-15 12:50:15 -07006149 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mOwnInBuffer(false),
Eric Laurent8569f0d2010-07-29 23:43:43 -07006150 mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6151 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006152{
Dima Zavinfce7a472011-04-19 22:30:36 -07006153 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006154}
6155
6156AudioFlinger::EffectChain::~EffectChain()
6157{
6158 if (mOwnInBuffer) {
6159 delete mInBuffer;
6160 }
6161
6162}
6163
Eric Laurentcab11242010-07-15 12:50:15 -07006164// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6165sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166{
6167 sp<EffectModule> effect;
6168 size_t size = mEffects.size();
6169
6170 for (size_t i = 0; i < size; i++) {
6171 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6172 effect = mEffects[i];
6173 break;
6174 }
6175 }
6176 return effect;
6177}
6178
Eric Laurentcab11242010-07-15 12:50:15 -07006179// getEffectFromId_l() must be called with PlaybackThread::mLock held
6180sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006181{
6182 sp<EffectModule> effect;
6183 size_t size = mEffects.size();
6184
6185 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006186 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6187 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 effect = mEffects[i];
6189 break;
6190 }
6191 }
6192 return effect;
6193}
6194
6195// Must be called with EffectChain::mLock locked
6196void AudioFlinger::EffectChain::process_l()
6197{
Eric Laurentdac69112010-09-28 14:09:57 -07006198 sp<ThreadBase> thread = mThread.promote();
6199 if (thread == 0) {
6200 LOGW("process_l(): cannot promote mixer thread");
6201 return;
6202 }
6203 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Dima Zavinfce7a472011-04-19 22:30:36 -07006204 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6205 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006206 bool tracksOnSession = false;
6207 if (!isGlobalSession) {
6208 tracksOnSession =
6209 playbackThread->hasAudioSession(mSessionId) & PlaybackThread::TRACK_SESSION;
6210 }
6211
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006213 // do not process effect if no track is present in same audio session
6214 if (isGlobalSession || tracksOnSession) {
6215 for (size_t i = 0; i < size; i++) {
6216 mEffects[i]->process();
6217 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218 }
6219 for (size_t i = 0; i < size; i++) {
6220 mEffects[i]->updateState();
6221 }
6222 // if no track is active, input buffer must be cleared here as the mixer process
6223 // will not do it
Eric Laurentdac69112010-09-28 14:09:57 -07006224 if (tracksOnSession &&
6225 activeTracks() == 0) {
6226 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6227 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 }
6229}
6230
Eric Laurentcab11242010-07-15 12:50:15 -07006231// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006232status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233{
6234 effect_descriptor_t desc = effect->desc();
6235 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6236
6237 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006238 effect->setChain(this);
6239 sp<ThreadBase> thread = mThread.promote();
6240 if (thread == 0) {
6241 return NO_INIT;
6242 }
6243 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006244
6245 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6246 // Auxiliary effects are inserted at the beginning of mEffects vector as
6247 // they are processed first and accumulated in chain input buffer
6248 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006249
Mathias Agopian65ab4712010-07-14 17:59:35 -07006250 // the input buffer for auxiliary effect contains mono samples in
6251 // 32 bit format. This is to avoid saturation in AudoMixer
6252 // accumulation stage. Saturation is done in EffectModule::process() before
6253 // calling the process in effect engine
6254 size_t numSamples = thread->frameCount();
6255 int32_t *buffer = new int32_t[numSamples];
6256 memset(buffer, 0, numSamples * sizeof(int32_t));
6257 effect->setInBuffer((int16_t *)buffer);
6258 // auxiliary effects output samples to chain input buffer for further processing
6259 // by insert effects
6260 effect->setOutBuffer(mInBuffer);
6261 } else {
6262 // Insert effects are inserted at the end of mEffects vector as they are processed
6263 // after track and auxiliary effects.
6264 // Insert effect order as a function of indicated preference:
6265 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6266 // another effect is present
6267 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6268 // last effect claiming first position
6269 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6270 // first effect claiming last position
6271 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6272 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6273 // already present
6274
6275 int size = (int)mEffects.size();
6276 int idx_insert = size;
6277 int idx_insert_first = -1;
6278 int idx_insert_last = -1;
6279
6280 for (int i = 0; i < size; i++) {
6281 effect_descriptor_t d = mEffects[i]->desc();
6282 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6283 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6284 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6285 // check invalid effect chaining combinations
6286 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6287 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006288 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006289 return INVALID_OPERATION;
6290 }
6291 // remember position of first insert effect and by default
6292 // select this as insert position for new effect
6293 if (idx_insert == size) {
6294 idx_insert = i;
6295 }
6296 // remember position of last insert effect claiming
6297 // first position
6298 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6299 idx_insert_first = i;
6300 }
6301 // remember position of first insert effect claiming
6302 // last position
6303 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6304 idx_insert_last == -1) {
6305 idx_insert_last = i;
6306 }
6307 }
6308 }
6309
6310 // modify idx_insert from first position if needed
6311 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6312 if (idx_insert_last != -1) {
6313 idx_insert = idx_insert_last;
6314 } else {
6315 idx_insert = size;
6316 }
6317 } else {
6318 if (idx_insert_first != -1) {
6319 idx_insert = idx_insert_first + 1;
6320 }
6321 }
6322
6323 // always read samples from chain input buffer
6324 effect->setInBuffer(mInBuffer);
6325
6326 // if last effect in the chain, output samples to chain
6327 // output buffer, otherwise to chain input buffer
6328 if (idx_insert == size) {
6329 if (idx_insert != 0) {
6330 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6331 mEffects[idx_insert-1]->configure();
6332 }
6333 effect->setOutBuffer(mOutBuffer);
6334 } else {
6335 effect->setOutBuffer(mInBuffer);
6336 }
6337 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338
Eric Laurentcab11242010-07-15 12:50:15 -07006339 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 }
6341 effect->configure();
6342 return NO_ERROR;
6343}
6344
Eric Laurentcab11242010-07-15 12:50:15 -07006345// removeEffect_l() must be called with PlaybackThread::mLock held
6346size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347{
6348 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 int size = (int)mEffects.size();
6350 int i;
6351 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6352
6353 for (i = 0; i < size; i++) {
6354 if (effect == mEffects[i]) {
6355 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6356 delete[] effect->inBuffer();
6357 } else {
6358 if (i == size - 1 && i != 0) {
6359 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6360 mEffects[i - 1]->configure();
6361 }
6362 }
6363 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006364 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365 break;
6366 }
6367 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368
6369 return mEffects.size();
6370}
6371
Eric Laurentcab11242010-07-15 12:50:15 -07006372// setDevice_l() must be called with PlaybackThread::mLock held
6373void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374{
6375 size_t size = mEffects.size();
6376 for (size_t i = 0; i < size; i++) {
6377 mEffects[i]->setDevice(device);
6378 }
6379}
6380
Eric Laurentcab11242010-07-15 12:50:15 -07006381// setMode_l() must be called with PlaybackThread::mLock held
6382void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383{
6384 size_t size = mEffects.size();
6385 for (size_t i = 0; i < size; i++) {
6386 mEffects[i]->setMode(mode);
6387 }
6388}
6389
Eric Laurentcab11242010-07-15 12:50:15 -07006390// setVolume_l() must be called with PlaybackThread::mLock held
6391bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392{
6393 uint32_t newLeft = *left;
6394 uint32_t newRight = *right;
6395 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006396 int ctrlIdx = -1;
6397 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398
Eric Laurentcab11242010-07-15 12:50:15 -07006399 // first update volume controller
6400 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006401 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006402 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6403 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006404 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006405 break;
6406 }
6407 }
6408
6409 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006410 if (hasControl) {
6411 *left = mNewLeftVolume;
6412 *right = mNewRightVolume;
6413 }
6414 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006415 }
6416
6417 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006418 mLeftVolume = newLeft;
6419 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006420
6421 // second get volume update from volume controller
6422 if (ctrlIdx >= 0) {
6423 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006424 mNewLeftVolume = newLeft;
6425 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 }
6427 // then indicate volume to all other effects in chain.
6428 // Pass altered volume to effects before volume controller
6429 // and requested volume to effects after controller
6430 uint32_t lVol = newLeft;
6431 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006432
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006434 if ((int)i == ctrlIdx) continue;
6435 // this also works for ctrlIdx == -1 when there is no volume controller
6436 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437 lVol = *left;
6438 rVol = *right;
6439 }
6440 mEffects[i]->setVolume(&lVol, &rVol, false);
6441 }
6442 *left = newLeft;
6443 *right = newRight;
6444
6445 return hasControl;
6446}
6447
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6449{
6450 const size_t SIZE = 256;
6451 char buffer[SIZE];
6452 String8 result;
6453
6454 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6455 result.append(buffer);
6456
6457 bool locked = tryLock(mLock);
6458 // failed to lock - AudioFlinger is probably deadlocked
6459 if (!locked) {
6460 result.append("\tCould not lock mutex:\n");
6461 }
6462
Eric Laurentcab11242010-07-15 12:50:15 -07006463 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6464 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006465 mEffects.size(),
6466 (uint32_t)mInBuffer,
6467 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006468 mActiveTrackCnt);
6469 result.append(buffer);
6470 write(fd, result.string(), result.size());
6471
6472 for (size_t i = 0; i < mEffects.size(); ++i) {
6473 sp<EffectModule> effect = mEffects[i];
6474 if (effect != 0) {
6475 effect->dump(fd, args);
6476 }
6477 }
6478
6479 if (locked) {
6480 mLock.unlock();
6481 }
6482
6483 return NO_ERROR;
6484}
6485
6486#undef LOG_TAG
6487#define LOG_TAG "AudioFlinger"
6488
6489// ----------------------------------------------------------------------------
6490
6491status_t AudioFlinger::onTransact(
6492 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6493{
6494 return BnAudioFlinger::onTransact(code, data, reply, flags);
6495}
6496
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497}; // namespace android